问:
Specifying a relative path in Post-Deployment SQL files
We have a post-deployment script in our SQL Server project which essentially performs a bulk-insert to populate tables after they're created. This is done by reading several .csv files:

```<code>BULK INSERT
    [dbo].[Table1]
    FROM '.\SubFolder\TestData\Data1.csv'
    WITH
    (
        ROWTERMINATOR = '0x0a',
        FIELDTERMINATOR = ','
    )

BULK INSERT
    [dbo].[Table2]
    FROM '.\SubFolder\TestData\Data2.csv'
    WITH
    (
        ROWTERMINATOR = '0x0a',
        FIELDTERMINATOR = ','
    )
</code>```

The problem is Visual Studio is having a hard time finding the files:

```<code>Cannot bulk load because the file ".\SubFolder\TestData\Data1.csv" could not be opened.
Operating system error code 3(The system cannot find the path specified.).
</code>```

The .csv files are checked in to the source control and I do see them when I go to the folder they're mapped to on my machine. I assume the problem is . isn't returning current path for the sql file being executed. Is there a way to get the relative path? Is there a macro (or a SQLCMD Variable maybe) that would give me current path of the file?

答:
I know this question is very old but still relevant. I found a working solution to this problem under the following conditions (what are optional because there are ways to overcome it) :

You will use the "publish" option within the Visual studio IDE to deploy your app.

The csv file is part of your project and configured to be copied to output folder.

Here are the steps:

Open Project Properties and go to SQLCMD Variables Section.

Add a new variable (for example $(CurrentPath))

In default Value put: $(ProjectDir)$(OutputPath)

Change your BULK code to:

BULK INSERT
    [dbo].[Table1]
    FROM '$(CurrentPath)\PathToFolderInsideOutputDirectory\Data1.csv'
    WITH
    (
        ROWTERMINATOR = '0x0a',
        FIELDTERMINATOR = ','
    )
```

Save all and compile.

Test your deploy using publish, ensure the $(CurrentPath) variable shows the right path(or press "Load values" button), press the publish button, all should work.

Body:
We have a post-deployment script in our SQL Server project which essentially performs a bulk-insert to populate tables after they're created. This is done by reading several .csv files:

BULK INSERT
    [dbo].[Table1]
    FROM '.\SubFolder\TestData\Data1.csv'
    WITH
    (
        ROWTERMINATOR = '0x0a',
        FIELDTERMINATOR = ','
    )

BULK INSERT
    [dbo].[Table2]
    FROM '.\SubFolder\TestData\Data2.csv'
    WITH
    (
        ROWTERMINATOR = '0x0a',
        FIELDTERMINATOR = ','
    )

The problem is Visual Studio is having a hard time finding the files:

Cannot bulk load because the file ".\SubFolder\TestData\Data1.csv" could not be opened.
Operating system error code 3(The system cannot find the path specified.).

The .csv files are checked in to the source control and I do see them when I go to the folder they're mapped to on my machine. I assume the problem is . isn't returning current path for the sql file being executed. Is there a way to get the relative path? Is there a macro (or a SQLCMD Variable maybe) that would give me current path of the file?

Body:
I know this question is very old but still relevant. I found a working solution to this problem under the following conditions (what are optional because there are ways to overcome it) :

You will use the "publish" option within the Visual studio IDE to deploy your app.

The csv file is part of your project and configured to be copied to output folder.

Here are the steps:

Open Project Properties and go to SQLCMD Variables Section.

Add a new variable (for example $(CurrentPath))

In default Value put: $(ProjectDir)$(OutputPath)

Change your BULK code to:

BULK INSERT
    [dbo].[Table1]
    FROM '$(CurrentPath)\PathToFolderInsideOutputDirectory\Data1.csv'
    WITH
    (
        ROWTERMINATOR = '0x0a',
        FIELDTERMINATOR = ','
    )

Save all and compile.

Test your deploy using publish, ensure the $(CurrentPath) variable shows the right path(or press "Load values" button), press the publish button, all should work.


来源: stackexchange

问:
How to read comma separated data set using scanf_s - C Programming
I don't have a working code I can share right now, but basically what I am trying to achieve is to read a user input or from a file in the following format:

```<code>1,2
2,5
3,4
4,5
etc...
</code>```

or

1,3 4,5 6,7 8,6 ...
So a comma separated pair of real numbers and I would need to assign them to an array or 2d array and calculate their means, median, mode etc...

I tried scanf_s("%d,",&n) and stuff like that but none of them have worked out so far. I am really new to C and came from Java so everything been very confusing. If any tips or just an example would be greatly appreciated. I know you can also use fgets, gets or sscanf, however I have not learned those yet.

This was a code sent by another user:(but i don't really understand it, because it gave me src could be 0 error)

```<code>#include <stdio.h>
#include <stdlib.h>
int main( void )
{
  char *src = (char*)malloc(sizeof(char) * 500);
  fgets(src, 500, stdin);
  int arr[500];
  int index = 0;
  int n;

  while ( sscanf ( src, "%d,%n", &arr[index], &n ) == 1 ) {
    printf("%d\n", arr[index]);
    index++;
    src += n;
  }
  return 0;
}
</code>```

答:
If the input format may really vary (your question is not very certain about it), strtod() is your main weapon.

```<code>char *P = MyLine, *NewP;   //MyLine is the input line
double Val[2];
do {
  Val[0]=strtod(P, &NewP);  //It reads the first value and shifts the pointer.
  if (NewP==P) return ERROR_EMPTY_STRING; //No values found! Sometimes maybe OK, if empty lines are allowed.
  P=NewP;
  while (*P == ' ') P++; //Omitting empty space between first value and comma.
  if (*P!=',') return ERROR_WRONG_FORMAT; //Wrong input: no comma between the values!
  Val[1]=strtod(P, &NewP);  //It reads the second value and shifts the pointer.
  if (NewP==P) return ERROR_WRONG_FORMAT; //No second value found! This is definitely not OK.
  P=NewP;
  while (*P == ' ') P++; //Omitting probable trailing spaces (we don't need it for strtod() because it does it by itself, but we need it for the endline check);
  ProcessSomehow(Val);   //Process the pair
} while (*P && *P != '\r' && *P != '\n' );
return LINE_ENDED_OK;
</code>```

This code will parse

```<code>1,2
3,4
5,6
</code>```

as well as

```<code>1,2 3,4 5,6
7,8 9,10 11,12
</code>```

or even this

```<code> 2, 4 1 , 5 6 ,8
1,3 4, 4
1,4 6 ,4    6, 8   2,7  2, 12  4, 8
</code>```

everything as long as they are comma-separated pairs and every pair is separated by at least one space. You can also easily modify it to allow 1,2; 4, 3; 2, 3  7, 2 or any other additional separators.

#define error codes according to your own taste (or use any other error handling, if you want to).

ContentLicense: CC BY-SA 4.0

Body:
I don't have a working code I can share right now, but basically what I am trying to achieve is to read a user input or from a file in the following format:

1,2
2,5
3,4
4,5
etc...

or

1,3 4,5 6,7 8,6 ...
So a comma separated pair of real numbers and I would need to assign them to an array or 2d array and calculate their means, median, mode etc...

I tried scanf_s("%d,",&n) and stuff like that but none of them have worked out so far. I am really new to C and came from Java so everything been very confusing. If any tips or just an example would be greatly appreciated. I know you can also use fgets, gets or sscanf, however I have not learned those yet.

This was a code sent by another user:(but i don't really understand it, because it gave me src could be 0 error)

#include <stdio.h>
#include <stdlib.h>
int main( void )
{
  char *src = (char*)malloc(sizeof(char) * 500);
  fgets(src, 500, stdin);
  int arr[500];
  int index = 0;
  int n;

  while ( sscanf ( src, "%d,%n", &arr[index], &n ) == 1 ) {
    printf("%d\n", arr[index]);
    index++;
    src += n;
  }
  return 0;
}

Body:
If the input format may really vary (your question is not very certain about it), strtod() is your main weapon.

char *P = MyLine, *NewP;   //MyLine is the input line
double Val[2];
do {
  Val[0]=strtod(P, &NewP);  //It reads the first value and shifts the pointer.
  if (NewP==P) return ERROR_EMPTY_STRING; //No values found! Sometimes maybe OK, if empty lines are allowed.
  P=NewP;
  while (*P == ' ') P++; //Omitting empty space between first value and comma.
  if (*P!=',') return ERROR_WRONG_FORMAT; //Wrong input: no comma between the values!
  Val[1]=strtod(P, &NewP);  //It reads the second value and shifts the pointer.
  if (NewP==P) return ERROR_WRONG_FORMAT; //No second value found! This is definitely not OK.
  P=NewP;
  while (*P == ' ') P++; //Omitting probable trailing spaces (we don't need it for strtod() because it does it by itself, but we need it for the endline check);
  ProcessSomehow(Val);   //Process the pair
} while (*P && *P != '\r' && *P != '\n' );
return LINE_ENDED_OK;

This code will parse

1,2
3,4
5,6

as well as

1,2 3,4 5,6
7,8 9,10 11,12

or even this

 2, 4 1 , 5 6 ,8
1,3 4, 4
1,4 6 ,4    6, 8   2,7  2, 12  4, 8

everything as long as they are comma-separated pairs and every pair is separated by at least one space. You can also easily modify it to allow 1,2; 4, 3; 2, 3  7, 2 or any other additional separators.

#define error codes according to your own taste (or use any other error handling, if you want to).


问:
Serenity/Cucumber test are not running because of a java.lang.ClassNotFoundException: cucumber.runner.TimeServiceEventBus
When I run my Serenity BDD tests from commandline I get the following stacktrace:

```<code>initializationError(net.persgroep.targetqa.webTests.WebTest)  Time elapsed: 0.002 s  <<< ERROR!
java.lang.NoClassDefFoundError: cucumber/runner/TimeServiceEventBus
Caused by: java.lang.ClassNotFoundException: cucumber.runner.TimeServiceEventBus
</code>```

On the Serenity chat they suggested that I changed my dependency versions. So I did that but still I've got the error.

These are my dependencies in my pom file:

```<code>   <dependency>
        <groupId>net.serenity-bdd</groupId>
        <artifactId>serenity-core</artifactId>
        <version>${serenity.version}</version>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>io.cucumber</groupId>
                <artifactId>cucumber-core</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>io.cucumber</groupId>
        <artifactId>cucumber-java</artifactId>
        <version>${cucumber.version}</version>
    </dependency>
    <dependency>
        <groupId>io.cucumber</groupId>
        <artifactId>cucumber-junit</artifactId>
        <version>${cucumber.version}</version>
    </dependency>
    <dependency>
        <groupId>net.serenity-bdd</groupId>
        <artifactId>serenity-junit</artifactId>
        <version>${serenity.version}</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>net.serenity-bdd</groupId>
        <artifactId>serenity-screenplay</artifactId>
        <version>${serenity.version}</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>net.serenity-bdd</groupId>
        <artifactId>serenity-screenplay-webdriver</artifactId>
        <version>${serenity.version}</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>net.serenity-bdd</groupId>
        <artifactId>serenity-model</artifactId>
        <version>${serenity.version}</version>
    </dependency>
    <dependency>
        <groupId>net.serenity-bdd</groupId>
        <artifactId>serenity-cucumber</artifactId>
        <version>1.9.48</version>
    </dependency>
    <dependency>
        <groupId>net.serenity-bdd</groupId>
        <artifactId>serenity-core</artifactId>
        <version>${serenity.version}</version>
    </dependency>
</code>```

The versions :

```<code> <serenity.version>2.0.89</serenity.version>
        <serenity.maven.version>2.0.89</serenity.maven.version>
        <serenity.cucumber.version>1.9.48</serenity.cucumber.version>
        <cucumber.version>4.8.0</cucumber.version>
</code>```

It used to work before, some team members suggested I should using declarative programming, so we changed a few for loops and I wanted to check if the test were still running.
Thats when I got this error.

答:
First you have an exclusion for:

```<code>    <exclusions>
        <exclusion>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-core</artifactId>
        </exclusion>
    </exclusions>
</code>```

which should explain the "ClassNotFoundException: cucumber.runner.TimeServiceEventBus" error.

Further you have duplicate dependencies. You should really investigate all the warnings that Maven is giving you. And lastly, you are forcing possibly incompatible pieces of Serenity onto itself, by explicitly declaring individual bits of Serenity. Unless you have a particularly good reason for this, you should really avoid that!

In any case, the one simple dependency:

```<code>            <dependency>
                    <groupId>net.serenity-bdd</groupId>
                    <artifactId>serenity-cucumber</artifactId>
                    <version>${serenity.version}</version>
            </dependency>
</code>```

brings in everything you will need: all of Cucumber, all of Selenium, JUnit, and of course all of Serenity.

You can also use:

```<code>            <dependency>
                    <groupId>net.serenity-bdd</groupId>
                    <artifactId>serenity-cucumber4</artifactId>
                    <version>${serenity.version}</version>
            </dependency>
</code>```

note the extra 4 there, if you want to use Cucumber version 4. Although last time I checked (admittedly it has been a while), this was still experimental.

See mvn dependency:tree to make sure.

Body:
When I run my Serenity BDD tests from commandline I get the following stacktrace:

initializationError(net.persgroep.targetqa.webTests.WebTest)  Time elapsed: 0.002 s  <<< ERROR!
java.lang.NoClassDefFoundError: cucumber/runner/TimeServiceEventBus
Caused by: java.lang.ClassNotFoundException: cucumber.runner.TimeServiceEventBus

On the Serenity chat they suggested that I changed my dependency versions. So I did that but still I've got the error.

These are my dependencies in my pom file:

   <dependency>
        <groupId>net.serenity-bdd</groupId>
        <artifactId>serenity-core</artifactId>
        <version>${serenity.version}</version>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>io.cucumber</groupId>
                <artifactId>cucumber-core</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>io.cucumber</groupId>
        <artifactId>cucumber-java</artifactId>
        <version>${cucumber.version}</version>
    </dependency>
    <dependency>
        <groupId>io.cucumber</groupId>
        <artifactId>cucumber-junit</artifactId>
        <version>${cucumber.version}</version>
    </dependency>
    <dependency>
        <groupId>net.serenity-bdd</groupId>
        <artifactId>serenity-junit</artifactId>
        <version>${serenity.version}</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>net.serenity-bdd</groupId>
        <artifactId>serenity-screenplay</artifactId>
        <version>${serenity.version}</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>net.serenity-bdd</groupId>
        <artifactId>serenity-screenplay-webdriver</artifactId>
        <version>${serenity.version}</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>net.serenity-bdd</groupId>
        <artifactId>serenity-model</artifactId>
        <version>${serenity.version}</version>
    </dependency>
    <dependency>
        <groupId>net.serenity-bdd</groupId>
        <artifactId>serenity-cucumber</artifactId>
        <version>1.9.48</version>
    </dependency>
    <dependency>
        <groupId>net.serenity-bdd</groupId>
        <artifactId>serenity-core</artifactId>
        <version>${serenity.version}</version>
    </dependency>

The versions :

 <serenity.version>2.0.89</serenity.version>
        <serenity.maven.version>2.0.89</serenity.maven.version>
        <serenity.cucumber.version>1.9.48</serenity.cucumber.version>
        <cucumber.version>4.8.0</cucumber.version>

It used to work before, some team members suggested I should using declarative programming, so we changed a few for loops and I wanted to check if the test were still running.
Thats when I got this error.

Body:
First you have an exclusion for:

    <exclusions>
        <exclusion>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-core</artifactId>
        </exclusion>
    </exclusions>

which should explain the "ClassNotFoundException: cucumber.runner.TimeServiceEventBus" error.

Further you have duplicate dependencies. You should really investigate all the warnings that Maven is giving you. And lastly, you are forcing possibly incompatible pieces of Serenity onto itself, by explicitly declaring individual bits of Serenity. Unless you have a particularly good reason for this, you should really avoid that!

In any case, the one simple dependency:

            <dependency>
                    <groupId>net.serenity-bdd</groupId>
                    <artifactId>serenity-cucumber</artifactId>
                    <version>${serenity.version}</version>
            </dependency>

brings in everything you will need: all of Cucumber, all of Selenium, JUnit, and of course all of Serenity.

You can also use:

            <dependency>
                    <groupId>net.serenity-bdd</groupId>
                    <artifactId>serenity-cucumber4</artifactId>
                    <version>${serenity.version}</version>
            </dependency>

note the extra 4 there, if you want to use Cucumber version 4. Although last time I checked (admittedly it has been a while), this was still experimental.

See mvn dependency:tree to make sure.


问:
What's the preferred way to create a jQuery object with attributes?
When creating jQuery objects I've used the following syntax lately, as described here:

```<code>var $el = $('<div/>', {
   class: 'class-1 class-2'
});
</code>```

Safari 5.0.5 gives a syntax error at the point where I use the above construction.

Removing the second argument and adding classes with addClass removes the error, but seems rather unelegant.

How do you create your objects? I tried with attr({class: 'class-1'}), as well, but received the same syntax error.

答:
You get an error as class is a reserved keyword. You can use a string as identifier when a property name is a reserved keyword:

```<code>var $el = $('<div/>', {
   'class': 'class-1 class-2'
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
When creating jQuery objects I've used the following syntax lately, as described here:

var $el = $('
', {
   class: 'class-1 class-2'
});

Safari 5.0.5 gives a syntax error at the point where I use the above construction.

Removing the second argument and adding classes with addClass removes the error, but seems rather unelegant.

How do you create your objects? I tried with attr({class: 'class-1'}), as well, but received the same syntax error.

Body:
You get an error as class is a reserved keyword. You can use a string as identifier when a property name is a reserved keyword:

var $el = $('<div/>', {
   'class': 'class-1 class-2'
});


问:
MarkLogic CORB - How to avoid timeout when run corb
How to avoid CORB timeout when run large batch of data pull over 10 million docs pdf/xml? Do I need to reduce thread-count and batch-size.

uris-module:

```<code>let $uris := cts:uris(
(),
(),
cts:and-query((
    cts:collection-query("/sites"),
    cts:field-range-query("cdate","<","2019-10-01"),
    cts:not-query(
        cts:or-query((
            cts:field-word-query("dcax","200"),
            more code...,
            ))
    )
))
return (fn:count($uris), $uris)
</code>```

process.xqy:

```<code>declare variable $URI as xs:string external;
let $uris := fn:tokenize($URI,";")
let $outputJson := "/output/json/"
let $outputPdf := "/output/pdf/"

for $uri1 in $uris
let $accStr := fn:substring-before(fn:substring-after($uri1,"/sites/"),".xml")
let $pdfUri := fn:concat("/pdf/iadb/",$accStr,".pdf")
let $doc := fn:doc($uri1)
let $obj := json:object()
let $_ := map:put($obj,"PaginationOrMediaCount",fn:number($doc/rec/MediaCount))
let $_ := map:put($obj,"Abstract",fn:replace($doc/rec/Abstract/text(),"[^a-zA-Z0-9 ,.\-\r\n]",""))
let $_ := map:put($obj,"Descriptors",json:to-array($doc/rec/Descriptor/text()))
    let $_ := map:put($obj,"FullText",fn:replace($doc/rec/FullText/text(),"[^a-zA-Z0-9 ,.\-\r\n]",""))
let $_ := xdmp:save(
    fn:concat($outputJson,$accStr,".json"),
    xdmp:to-json($obj)
)
let $_ := if (fn:doc-available($pdfUri))
    then xdmp:save(
        fn:concat($outputPdf,$accStr,".pdf"),
        fn:doc($pdfUri)
    )
    else ()

return $URI
</code>```

答:
It would be easier to diagnose and suggest improvements if you shared the CoRB job options and the code for your URIS-MODULE and PROCESS-MODULE

The general concept of a CoRB job is that is splits up the work to perform multiple module executions rather than trying to do all of the work in a single execution, in order to avoid timeout issues and excessive memory consumption.

For instance, if you wanted to download 10 million documents, the URIS-MODULE would select the URIs of all of those documents, and then each URI would be sent to the PROCESS-MODULE, which would be responsible for retrieving it. Depending upon the THREAD-COUNT, you could be downloading several documents at a time but they should all be returning very quickly.

Is the execution of the URIs module what is timing out, or the process module?

You can increase the timeout limit from the default limit up to the maximum timeout limit by using: xdmp:request-set-time-limit()

Generally, the process modules should execute quickly and shouldn't be timing out. One possible reason would be performing too much work in the transform (i.e. setting BATCH-SIZE really large and doing too much at once) or maybe a misconfiguration or poorly written query (i.e. rather than fetching a single doc with the $URI value, performing a search and retrieving all of the docs each time that the process module is executed).

Body:
How to avoid CORB timeout when run large batch of data pull over 10 million docs pdf/xml? Do I need to reduce thread-count and batch-size.

uris-module:

let $uris := cts:uris(
(),
(),
cts:and-query((
    cts:collection-query("/sites"),
    cts:field-range-query("cdate","<","2019-10-01"),
    cts:not-query(
        cts:or-query((
            cts:field-word-query("dcax","200"),
            more code...,
            ))
    )
))
return (fn:count($uris), $uris)

process.xqy:

declare variable $URI as xs:string external;
let $uris := fn:tokenize($URI,";")
let $outputJson := "/output/json/"
let $outputPdf := "/output/pdf/"

for $uri1 in $uris
let $accStr := fn:substring-before(fn:substring-after($uri1,"/sites/"),".xml")
let $pdfUri := fn:concat("/pdf/iadb/",$accStr,".pdf")
let $doc := fn:doc($uri1)
let $obj := json:object()
let $_ := map:put($obj,"PaginationOrMediaCount",fn:number($doc/rec/MediaCount))
let $_ := map:put($obj,"Abstract",fn:replace($doc/rec/Abstract/text(),"[^a-zA-Z0-9 ,.\-\r\n]",""))
let $_ := map:put($obj,"Descriptors",json:to-array($doc/rec/Descriptor/text()))
    let $_ := map:put($obj,"FullText",fn:replace($doc/rec/FullText/text(),"[^a-zA-Z0-9 ,.\-\r\n]",""))
let $_ := xdmp:save(
    fn:concat($outputJson,$accStr,".json"),
    xdmp:to-json($obj)
)
let $_ := if (fn:doc-available($pdfUri))
    then xdmp:save(
        fn:concat($outputPdf,$accStr,".pdf"),
        fn:doc($pdfUri)
    )
    else ()

return $URI


问:
RegGetValue cannot find name under current user?
I am testing this function ::RegGetValue. The code below returns success.

```<code>DWORD data_size = 0;
LONG result = ::RegGetValue(HKEY_LOCAL_MACHINE,
                            _T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\OUTLOOK.EXE"),
                            _T("Path"),
                            RRF_RT_REG_SZ,
                            NULL, NULL,
                            &data_size);
</code>```

But if I try to find different entry under current user, it fails even though the entry does exist.

```<code>DWORD data_size = 0;
LONG result = ::RegGetValue(HKEY_CURRENT_USER,
                            _T("Software\\Microsoft\\Internet Explorer\\Main\\FeatureControl\\FEATURE_BROWSER_EMULATION"),
                            _T("OUTLOOK.EXE"),
                            RRF_RT_REG_SZ,
                            NULL, NULL,
                            &data_size);
</code>```

答:
All of the values in the FEATURE_BROWSER_EMULATION key are DWORD values, not String values, per MSDN documentation:

Internet Feature Controls (B..C): Browser Emulation

By specifying RRF_RT_REG_SZ, you are telling RegGetValue() to read only String values.  That makes sense when reading a "Path" value from the App Paths key, but when reading from the FEATURE_BROWSER_EMULATION key you need to specify RRF_RT_REG_DWORD instead.

Body:
I am testing this function ::RegGetValue. The code below returns success.

DWORD data_size = 0;
LONG result = ::RegGetValue(HKEY_LOCAL_MACHINE,
                            _T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\OUTLOOK.EXE"),
                            _T("Path"),
                            RRF_RT_REG_SZ,
                            NULL, NULL,
                            &data_size);

But if I try to find different entry under current user, it fails even though the entry does exist.

DWORD data_size = 0;
LONG result = ::RegGetValue(HKEY_CURRENT_USER,
                            _T("Software\\Microsoft\\Internet Explorer\\Main\\FeatureControl\\FEATURE_BROWSER_EMULATION"),
                            _T("OUTLOOK.EXE"),
                            RRF_RT_REG_SZ,
                            NULL, NULL,
                            &data_size);


问:
Crafted hex string correct in string format, malforms once passed to unhexlify()
```<code>def craft_integration(xintegration_time):

 integration_time = xintegration_time
 integration_time_str = str(integration_time)
 integration_time_str = integration_time_str.encode('utf-8')
 integration_time_hex = integration_time_str.hex()

 return integration_time_hex

def send_set_integration(xtime):

 int_time_hex = decoder_crafter.craft_integration(xtime)

 set_hex = "c1c000000000000010001100000000000000000000000004"+int_time_hex+"1400000000000000000000000000000000000000c5c4c3c2"
 set_hex = str(set_hex)
 print(set_hex)
 set_hex = unhexlify(set_hex)
</code>```

For example, input is '1000'.
That becomes 31303030 with craft_integration().
It is then inserted into the default hex string.

Output is:

c1c000000000000010001100000000000000000000000004313030301400000000000000000000000000000000000000c5c4c3c2

When unhexlify() is used, output is:

b'\xc1\xc0\x00\x00\x00\x00\x00\x00\x10\x00\x11\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x041000\x14\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xc5\xc4\xc3\xc2'

\x041000 is an conjunction of \x04 and 1000 which was the original input value, not the converted value.

Why would this happen?

答:
What you have in fact is simply your desired value being rendered into a form by the default implementation of bytes.__repr__ that you were not expecting to the point that it was unhelpful to what you want.

To start from a more basic level: in Python, any element (well, any "byte", i.e. a group of 8 bits) inside a bytes type are typically being stored as raw digital representation somewhere in a machine as binary.  In order to "print" them out onto a console for human consumption it must be turned into a form that may be interpreted by the console such that the correct glyph may be used to represent the underlying value.  For many values, such as 0 (or 00000000 in binary), Python would use \x00 to represent that.  The \ is the escape character to start an escape sequence, the x that follows signifies that the escape sequence is to be followed by 2 hexadecimal characters, and combining those two characters with the whole sequence would form the representation of that single byte using four characters.  Likewise for 255, in binary that would be 11111111, and this same value as part of a bytes type will be encoded as \xff.

Now there are exceptions - if a given value falls inside the ASCII range, and that it in the range of printable characters, the representation will instead be the corresponding ASCII character.  So in the case of the hexadecimal 30 (decimal 48), rendering of that as part of a bytes type will show 0 instead of \x30, as 0 is the corresponding printable character.

So for your case, a bytes representation that was printed out in the console in the form of b'\x041000', is not in fact a big \x value, as the \x escape sequence is only applied to exactly two subsequent characters - all following characters (i.e. 1000) are in fact being represented using the printable characters that would otherwise be represented as \x31\x30\x30\x30.

There is another method available to those who don't mind working with the decimal representation of bytes - simply cast the bytes into a bytearray then into a list.  We will take two nul bytes (b'\x00\x00') as an example:

```<code>>>> list(bytearray(b'\x00\x00'))
[0, 0]
</code>```

Clearly those two nul bytes will correspond to two zero values.  Now try using the confusing b'\x04\x31\x30\x30\x30' which got rendered into b'\x041000':

```<code>>>> list(bytearray(b'\x041000'))
[4, 49, 48, 48, 48]
</code>```

We can note that it was in fact 5 bytes rendered with the corresponding decimal numbers in a list of 5 elements.

It is often easy to get confused with what the actual value is, vs. what is being shown and visualized on the computer console.  Unfortunately the tools we use sometimes amplify that confusion, but as programmers we should understand this and seek ways to minimize this for users of our work, as this example shows that not everyone may have the intuition that certain representations of bytes may instead be represented as printable ASCII.

Body:
def craft_integration(xintegration_time):

 integration_time = xintegration_time
 integration_time_str = str(integration_time)
 integration_time_str = integration_time_str.encode('utf-8')
 integration_time_hex = integration_time_str.hex()

 return integration_time_hex

def send_set_integration(xtime):

 int_time_hex = decoder_crafter.craft_integration(xtime)

 set_hex = "c1c000000000000010001100000000000000000000000004"+int_time_hex+"1400000000000000000000000000000000000000c5c4c3c2"
 set_hex = str(set_hex)
 print(set_hex)
 set_hex = unhexlify(set_hex)

For example, input is '1000'.
That becomes 31303030 with craft_integration().
It is then inserted into the default hex string.

Output is:

c1c000000000000010001100000000000000000000000004313030301400000000000000000000000000000000000000c5c4c3c2

When unhexlify() is used, output is:

b'\xc1\xc0\x00\x00\x00\x00\x00\x00\x10\x00\x11\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x041000\x14\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xc5\xc4\xc3\xc2'

\x041000 is an conjunction of \x04 and 1000 which was the original input value, not the converted value.

Why would this happen?

Body:
What you have in fact is simply your desired value being rendered into a form by the default implementation of bytes.__repr__ that you were not expecting to the point that it was unhelpful to what you want.

To start from a more basic level: in Python, any element (well, any "byte", i.e. a group of 8 bits) inside a bytes type are typically being stored as raw digital representation somewhere in a machine as binary.  In order to "print" them out onto a console for human consumption it must be turned into a form that may be interpreted by the console such that the correct glyph may be used to represent the underlying value.  For many values, such as 0 (or 00000000 in binary), Python would use \x00 to represent that.  The \ is the escape character to start an escape sequence, the x that follows signifies that the escape sequence is to be followed by 2 hexadecimal characters, and combining those two characters with the whole sequence would form the representation of that single byte using four characters.  Likewise for 255, in binary that would be 11111111, and this same value as part of a bytes type will be encoded as \xff.

Now there are exceptions - if a given value falls inside the ASCII range, and that it in the range of printable characters, the representation will instead be the corresponding ASCII character.  So in the case of the hexadecimal 30 (decimal 48), rendering of that as part of a bytes type will show 0 instead of \x30, as 0 is the corresponding printable character.

So for your case, a bytes representation that was printed out in the console in the form of b'\x041000', is not in fact a big \x value, as the \x escape sequence is only applied to exactly two subsequent characters - all following characters (i.e. 1000) are in fact being represented using the printable characters that would otherwise be represented as \x31\x30\x30\x30.

There is another method available to those who don't mind working with the decimal representation of bytes - simply cast the bytes into a bytearray then into a list.  We will take two nul bytes (b'\x00\x00') as an example:

>>> list(bytearray(b'\x00\x00'))
[0, 0]

Clearly those two nul bytes will correspond to two zero values.  Now try using the confusing b'\x04\x31\x30\x30\x30' which got rendered into b'\x041000':

>>> list(bytearray(b'\x041000'))
[4, 49, 48, 48, 48]

We can note that it was in fact 5 bytes rendered with the corresponding decimal numbers in a list of 5 elements.

It is often easy to get confused with what the actual value is, vs. what is being shown and visualized on the computer console.  Unfortunately the tools we use sometimes amplify that confusion, but as programmers we should understand this and seek ways to minimize this for users of our work, as this example shows that not everyone may have the intuition that certain representations of bytes may instead be represented as printable ASCII.


问:
Problems with running py scripts from cmd
I have recently installed another Python without deleting previous and now when I am trying to run my script from cmd, Windows pushing me to choose the app that will run py.script.</p>

答:
as alex067 stated, you have to set the PATH variable in your Environment Variables.

You can follow the instructions here https://superuser.com/questions/143119/how-do-i-add-python-to-the-windows-path


问:
Difference between android Home key and Back key and their behaviour
Can anyone point me out or explain what is the difference between android Home key and Back key and their respective behavior related to an android app/activity.

Thank you.

答: Back key destroys the current Activity, home key doesn't. In the Activity lyfecycle, pressing back calls all the way to current activity's onDestroy() method. On the other hand, pressing home pauses the Activity, which stays alive in background.</p>


问:
Efficiently removing shared elements from grouped data
I have the following data.table:

```<code>dt
#    unique_id group_id primary_id  ph1  ph2  ph3
# 1:         1        1       TRUE   07   03 <NA>
# 2:         2        1      FALSE   07   03   84
# 3:         3        2      FALSE   10 <NA> <NA>
# 4:         4        2       TRUE <NA>   10 <NA>
# 5:         5        2      FALSE <NA> <NA>   10
# 6:         6        3      FALSE   22   03 <NA>
# 7:         7        3       TRUE <NA>   13   03
</code>```

unique_ids are grouped by common phone numbers (ph1, ph2, ph3) which are common across rows (e.g. in the first group "07", "03" are common across the group and in the third group, "03" is shared, but not in the same column, as per group 2).

Each group has 1 primary_id.

Within each group I want to remove the common phone number element(s) in the non primary_id's and retain it for the primary id, so they are no longer linked.

I can achieve this easily in a for loop, however, it's across millions of groups and it's extremely slow.

Looking for a quicker method.

Data:

```<code>library(data.table)

dt <- data.table(structure(list(unique_id = c(1, 2, 3, 4, 5, 6, 7), group_id = c(1,
    1, 2, 2, 2, 3, 3), primary_id = c(TRUE, FALSE, FALSE, TRUE, FALSE,
    FALSE, TRUE), ph1 = c("07", "07", "10", NA, NA, "22", NA), ph2 = c("03",
    "03", NA, "10", NA, "03", "13"), ph3 = c(NA, "84", NA, NA, "10",
    NA, "03")), class = "data.frame", row.names = c(NA, -7L))
)
</code>```

Desired output is:

```<code>output <- data.table(structure(list(unique_id = c(1, 2, 3, 4, 5, 6, 7), group_id = c(1,
1, 2, 2, 2, 3, 3), primary_id = c(TRUE, FALSE, FALSE, TRUE, FALSE,
FALSE, TRUE), ph1 = c("07", NA, NA, NA, NA, "22", NA), ph2 = c("03",
NA, NA, "10", NA, NA, "13"), ph3 = c(NA, "84", NA, NA, NA, NA,
"03")), class = "data.frame", row.names = c(NA, -7L)))

output
#    unique_id group_id primary_id  ph1  ph2  ph3
# 1:         1        1       TRUE   07   03 <NA>
# 2:         2        1      FALSE <NA> <NA>   84
# 3:         3        2      FALSE <NA> <NA> <NA>
# 4:         4        2       TRUE <NA>   10 <NA>
# 5:         5        2      FALSE <NA> <NA> <NA>
# 6:         6        3      FALSE   22 <NA> <NA>
# 7:         7        3       TRUE <NA>   13   03
</code>```

If still unclear, it may be easier to visualize it like this:

答:
Here is a way to do this in tidyverse, I am sure there is an equivalent in data.table as well.

We get the data in long format, group_by group_id and replace value with NA where it is duplicated and is not a primary id.

```<code>library(dplyr)
library(tidyr)

dt %>%
  pivot_longer(cols = starts_with('ph')) %>%
  group_by(group_id) %>%
  mutate(value = replace(value, (duplicated(value) |
           duplicated(value, fromLast = TRUE)) & !primary_id, NA)) %>%
  pivot_wider()

# unique_id group_id primary_id ph1   ph2   ph3
#      <dbl>    <dbl> <lgl>      <chr> <chr> <chr>
#1         1        1 TRUE       07    03    NA
#2         2        1 FALSE      NA    NA    84
#3         3        2 FALSE      NA    NA    NA
#4         4        2 TRUE       NA    10    NA
#5         5        2 FALSE      NA    NA    NA
#6         6        3 FALSE      22    NA    NA
#7         7        3 TRUE       NA    13    03
</code>```

Body:
I have the following data.table:

dt
#    unique_id group_id primary_id  ph1  ph2  ph3
# 1:         1        1       TRUE   07   03 <NA>
# 2:         2        1      FALSE   07   03   84
# 3:         3        2      FALSE   10 <NA> <NA>
# 4:         4        2       TRUE <NA>   10 <NA>
# 5:         5        2      FALSE <NA> <NA>   10
# 6:         6        3      FALSE   22   03 <NA>
# 7:         7        3       TRUE <NA>   13   03

unique_ids are grouped by common phone numbers (ph1, ph2, ph3) which are common across rows (e.g. in the first group "07", "03" are common across the group and in the third group, "03" is shared, but not in the same column, as per group 2).

Each group has 1 primary_id.

Within each group I want to remove the common phone number element(s) in the non primary_id's and retain it for the primary id, so they are no longer linked.

I can achieve this easily in a for loop, however, it's across millions of groups and it's extremely slow.

Looking for a quicker method.

Data:

library(data.table)

dt <- data.table(structure(list(unique_id = c(1, 2, 3, 4, 5, 6, 7), group_id = c(1,
    1, 2, 2, 2, 3, 3), primary_id = c(TRUE, FALSE, FALSE, TRUE, FALSE,
    FALSE, TRUE), ph1 = c("07", "07", "10", NA, NA, "22", NA), ph2 = c("03",
    "03", NA, "10", NA, "03", "13"), ph3 = c(NA, "84", NA, NA, "10",
    NA, "03")), class = "data.frame", row.names = c(NA, -7L))
)

Desired output is:

output <- data.table(structure(list(unique_id = c(1, 2, 3, 4, 5, 6, 7), group_id = c(1,
1, 2, 2, 2, 3, 3), primary_id = c(TRUE, FALSE, FALSE, TRUE, FALSE,
FALSE, TRUE), ph1 = c("07", NA, NA, NA, NA, "22", NA), ph2 = c("03",
NA, NA, "10", NA, NA, "13"), ph3 = c(NA, "84", NA, NA, NA, NA,
"03")), class = "data.frame", row.names = c(NA, -7L)))

output
#    unique_id group_id primary_id  ph1  ph2  ph3
# 1:         1        1       TRUE   07   03 <NA>
# 2:         2        1      FALSE <NA> <NA>   84
# 3:         3        2      FALSE <NA> <NA> <NA>
# 4:         4        2       TRUE <NA>   10 <NA>
# 5:         5        2      FALSE <NA> <NA> <NA>
# 6:         6        3      FALSE   22 <NA> <NA>
# 7:         7        3       TRUE <NA>   13   03

If still unclear, it may be easier to visualize it like this:

Body:
Here is a way to do this in tidyverse, I am sure there is an equivalent in data.table as well.

We get the data in long format, group_by group_id and replace value with NA where it is duplicated and is not a primary id.

library(dplyr)
library(tidyr)

dt %>%
  pivot_longer(cols = starts_with('ph')) %>%
  group_by(group_id) %>%
  mutate(value = replace(value, (duplicated(value) |
           duplicated(value, fromLast = TRUE)) & !primary_id, NA)) %>%
  pivot_wider()

# unique_id group_id primary_id ph1   ph2   ph3
#      <dbl>    <dbl> <lgl>      <chr> <chr> <chr>
#1         1        1 TRUE       07    03    NA
#2         2        1 FALSE      NA    NA    84
#3         3        2 FALSE      NA    NA    NA
#4         4        2 TRUE       NA    10    NA
#5         5        2 FALSE      NA    NA    NA
#6         6        3 FALSE      22    NA    NA
#7         7        3 TRUE       NA    13    03


问:
Tackling Duplicate Content Links
What's the best practise for accessibility when you have redundant links on a page. For example, a page containing blog listings often has a clickable title and a read more link:

```<code><article>
  <h2><a>My awesome blog post title</a></h2>
  <p>This is the excerpt...</p>
  <a>Read More</a>
</article>
<!-- more blog listings... -->
</code>```

My first approach would be to add an aria label to the read more link to give it some context.

```<code><article>
  <h2><a>My awesome blog post title</a></h2>
  <p>This is the excerpt...</p>
  <a aria-label="My awesome blog post title">Read More</a>
</article>
<!-- more blog listings... -->
</code>```

However now there are two identical links and I can see how this would be irritating for people using screen readers - especially if the page contains a large number of articles.

Would this be a good use case for hiding the extraneous link from screen readers and/or people navigating using the keyboard. Something like this?

```<code> <article>
  <h2><a>My awesome blog post title</a></h2>
  <p>This is the excerpt...</p>
  <a role="presentation" tabindex="-1">Read More</a>
</article>
<!-- more blog listings... -->
</code>```

Not sure whether this is one of those situations where trying to help may actually make things worse. Would appreciate any advice!

Thanks, Adam

答:
In my personal recommendation, I would combine it to one link... Anytime you can combine redundant links that's a great win.

```<code><article>
  <h2><a href="example.com">My awesome blog post title</a></h2>
  <p>This is the excerpt...</p>
  Read More
</article>
<!-- more blog listings... -->
</code>```

If you really need both links you can use an onclick function and remove the href.

```<code><article>
  <h2 id="Foo"><a href="foo.html">My awesome blog post title</a></h2>
  <p>This is the excerpt...</p>
  <a onclick="examplefunction()"id="Bar" aria-labelledby="Bar Foo">Read More</a>
</article>
</code>```

This removes that redundant link error and removes the second link from achieving focus. The link can still work if someone clicks on it, but it removes it from the tab order. This is perfectly valid.

Though it's always best to have HTML handle links instead of using javascript to do it.

Good Luck,

Giovani

Title: Tackling Duplicate Content Links

Body:
What's the best practise for accessibility when you have redundant links on a page. For example, a page containing blog listings often has a clickable title and a read more link:

My awesome blog post title

This is the excerpt...

  Read More

My first approach would be to add an aria label to the read more link to give it some context.

My awesome blog post title

This is the excerpt...

  Read More

However now there are two identical links and I can see how this would be irritating for people using screen readers - especially if the page contains a large number of articles.

Would this be a good use case for hiding the extraneous link from screen readers and/or people navigating using the keyboard. Something like this?

My awesome blog post title

This is the excerpt...

  Read More

Not sure whether this is one of those situations where trying to help may actually make things worse. Would appreciate any advice!

Thanks, Adam

Body:
In my personal recommendation, I would combine it to one link... Anytime you can combine redundant links that's a great win.

<article>
  <h2><a href="example.com">My awesome blog post title</a></h2>
  <p>This is the excerpt...</p>
  Read More
</article>
<!-- more blog listings... -->

If you really need both links you can use an onclick function and remove the href.

<article>
  <h2 id="Foo"><a href="foo.html">My awesome blog post title</a></h2>
  <p>This is the excerpt...</p>
  <a onclick="examplefunction()"id="Bar" aria-labelledby="Bar Foo">Read More</a>
</article>

This removes that redundant link error and removes the second link from achieving focus. The link can still work if someone clicks on it, but it removes it from the tab order. This is perfectly valid.

Though it's always best to have HTML handle links instead of using javascript to do it.

Good Luck,

Giovani


问:
After Connecting OpenVPN with Google VPC, can not able to surf internet
I have connected OpenVPN with Google Cloud VPC by following youtube video

https://www.youtube.com/watch?v=avYcoMKaXRc

Right now I am in Singapore and wants to connect Google Cloud India, setup is perfect but after successful connection if I try to open any website, on-one is opening, like there is no internet connection.

Can any one help me what is the issue? thanks

答:
To monitor and solve common issues with Cloud VPN, follow the GCP Cloud VPN troubleshooting guide and OpenVPN troubleshooting.

Even the VPN gateways are configured correctly, there could be issue in the peer network between the hosts and the gateway, or with the network between the peer gateway and the Cloud VPN gateway.

Check for the Cloud VPN logs in Stackdriver Logging and verify these steps.

Verify connectivity between your host and Google Cloud VMs;

Are you able to reach peer VPN gateway from your host.

Verify that traffic is flowing between the two VPN gateways in both directions. In the VPN logs, check for reported incoming messages from the other VPN gateway.

Make sure to configure your peer VPN gateway to use MTU of no greater than 1460 bytes.

Check network throughput, both within GCP and your host.

Check if supported IKE ciphers are configured.


问:
I have a list, in which one of column data has to formatted in such a way that $ sign and Comma should be removed
```<code>data = Index(['borough', 'neighborhood', 'building_class_category',
       'tax_class_at_present', 'block', 'lot', 'ease_ment',
       'building_class_at_present', 'address', 'apart_ment_number', 'zip_code',
       'residential_units', 'commercial_units', 'total_units',
       'land_square_feet', 'gross_square_feet', 'year_built',
       'tax_class_at_time_of_sale', 'building_class_at_time_of_sale',
       'sale_price', 'sale_date'],
      dtype='object')
</code>```

Convert the field “sale_price” to numeric (it is currently formatted as currency which cannot be
used in calculations.) (Hint, you will need to remove the commas and dollar signs.

I tried

```<code>df=data
df['sale_price']=df['sale_price'].replace('$','')
using

df['sale_price'] = df['sale_price'].str.replace(',', '').str.replace('$', '').astype(int)
</code>```

答:
If I understand your problem correctly, this answer should help:

converting currency with $ to numbers in Python pandas

Body:
data = Index(['borough', 'neighborhood', 'building_class_category',
       'tax_class_at_present', 'block', 'lot', 'ease_ment',
       'building_class_at_present', 'address', 'apart_ment_number', 'zip_code',
       'residential_units', 'commercial_units', 'total_units',
       'land_square_feet', 'gross_square_feet', 'year_built',
       'tax_class_at_time_of_sale', 'building_class_at_time_of_sale',
       'sale_price', 'sale_date'],
      dtype='object')

Convert the field “sale_price” to numeric (it is currently formatted as currency which cannot be
used in calculations.) (Hint, you will need to remove the commas and dollar signs.

I tried

df=data
df['sale_price']=df['sale_price'].replace('$','')
using

df['sale_price'] = df['sale_price'].str.replace(',', '').str.replace('$', '').astype(int)


问:
Check if the path exists in Databricks
I try to check if the path exists in Databricks using Python:

```<code>try:
  dirs = dbutils.fs.ls ("/my/path")
  pass
except IOError:
  print("The path does not exist")
</code>```

If the path does not exist, I expect that the except statement executes.
However, instead of except statement, the try statement fails with the error:

```<code>java.io.FileNotFoundException: GET ...
ErrorMessage=The specified path does not exist.
</code>```

How to properly catch FileNotFoundException?

答:
here is alternative </p>

```<code>import os
dir = "/dbfs/path_to_directory"

if not os.path.exists(dir):
  print('The path does not exist')
  raise IOError
</code>```

Title: Check if the path exists in Databricks

Body:
I try to check if the path exists in Databricks using Python:

try:
  dirs = dbutils.fs.ls ("/my/path")
  pass
except IOError:
  print("The path does not exist")

If the path does not exist, I expect that the except statement executes.
However, instead of except statement, the try statement fails with the error:

java.io.FileNotFoundException: GET ...
ErrorMessage=The specified path does not exist.

How to properly catch FileNotFoundException?

Body:
here is alternative

import os
dir = "/dbfs/path_to_directory"

if not os.path.exists(dir):
  print('The path does not exist')
  raise IOError


问:
How do I programmatically change the color of the hamburger menu icon using hex values in xamarin forms?
I am working on a mvvm light xamarin forms application where i allow the user to create there own theme with in the application itself. As of right now, i have everything working as intended with the exception of the send button(image icon), add button (image icon), and hamburger menu icon.

The user selects a image/name, then the hex value from that color is applied to the control/font. But i have run into the issue when trying to programmatically set the hamburger menu color.I started with the android side of things.I can set the color once using styles.xml.

But this not sufficient for what i am trying to do. I haven't figure out how to get a reference to the toggledrawer to change the color without creating a new reference and supplying drawables.

I will also need to have the same action happen on iOS(changeable color hamburger menu). I don't want to supply images because the user will set the color based on a hex value...what is my best option? Is what i am trying to do even possible at this point?

```<code>   public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
    {
        protected ActionBarDrawerToggle drawerToggle;
        protected override void OnCreate(Bundle savedInstanceState)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource = Resource.Layout.Toolbar;

            base.OnCreate(savedInstanceState);
            Rg.Plugins.Popup.Popup.Init(this, savedInstanceState);
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
            LoadApplication(new App());

    drawerToggle.getDrawerArrowDrawable().setColor(getResources().getColor(R.color.white));
        }
    }
</code>```

i found this code here:

```<code>drawerToggle.getDrawerArrowDrawable().setColor(getResources().getColor(R.color.white));
</code>```

It would be ideal, but i don't have a reference to drawerToggle...(the object is null)

i also tried to setting it using  styles.xml as should below:

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

  <style name="MainTheme" parent="MainTheme.Base">
  </style>
  <!-- Base theme applied no matter what API -->
  <style name="MainTheme.Base" parent="Theme.AppCompat.Light.DarkActionBar">
    <!--If you are using revision 22.1 please use just windowNoTitle. Without android:-->
    <item name="windowNoTitle">true</item>
    <!--We will be using the toolbar so no need to show ActionBar-->
    <item name="windowActionBar">false</item>
    <!-- Set theme colors from http://www.google.com/design/spec/style/color.html#color-color-palette -->
    <!-- colorPrimary is used for the default action bar background -->
    <item name="colorPrimary">#2196F3</item>
    <!-- colorPrimaryDark is used for the status bar -->
    <item name="colorPrimaryDark">#1976D2</item>
    <!-- colorAccent is used as the default value for colorControlActivated
         which is used to tint widgets -->
    <item name="colorAccent">#FF4081</item>
    <!-- You can also set colorControlNormal, colorControlActivated
         colorControlHighlight and colorSwitchThumbNormal. -->
    <item name="windowActionModeOverlay">true</item>

    <item name="android:datePickerDialogTheme">@style/AppCompatDialogStyle</item>
  <item name="drawerArrowStyle">@style/DrawerArrowStyle</item>
  </style>

  <style name="DrawerArrowStyle" parent="@style/Widget.AppCompat.DrawerArrowToggle">
    <item name="spinBars">true</item>
    <item name="color">@android:color/green</item>
  </style>

  <style name="AppCompatDialogStyle" parent="Theme.AppCompat.Light.Dialog">
    <item name="colorAccent">#FF4081</item>
  </style>
</resources>
</code>```

This code does work to set it once, but i need it reset within the application by a button click. So this is not sufficient for the what i am trying to do.

答:
add hamburger menu icon to drawable folder

Add code where you wish to change it.

```<code>var toolbar = FindViewById<AndroidToolbar>(Resource.Id.toolbar);
var view = (AppCompatImageButton)toolbar.GetChildAt(2);
    // 1. actionmenuview (primary/secondary menu icons),
    // 2. appcompattextview (title),
    // 3. appcompatimagebutton (hamburger icon)
view.SetImageDrawable(d);
           // view.SetImageDrawable(d);
</code>```

In my case, I have menu Icons so I select GetChildAt(2) [the third item]

Body:
I am working on a mvvm light xamarin forms application where i allow the user to create there own theme with in the application itself. As of right now, i have everything working as intended with the exception of the send button(image icon), add button (image icon), and hamburger menu icon.

The user selects a image/name, then the hex value from that color is applied to the control/font. But i have run into the issue when trying to programmatically set the hamburger menu color.I started with the android side of things.I can set the color once using styles.xml.

But this not sufficient for what i am trying to do. I haven't figure out how to get a reference to the toggledrawer to change the color without creating a new reference and supplying drawables.

I will also need to have the same action happen on iOS(changeable color hamburger menu). I don't want to supply images because the user will set the color based on a hex value...what is my best option? Is what i am trying to do even possible at this point?

   public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
    {
        protected ActionBarDrawerToggle drawerToggle;
        protected override void OnCreate(Bundle savedInstanceState)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource = Resource.Layout.Toolbar;

            base.OnCreate(savedInstanceState);
            Rg.Plugins.Popup.Popup.Init(this, savedInstanceState);
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
            LoadApplication(new App());

    drawerToggle.getDrawerArrowDrawable().setColor(getResources().getColor(R.color.white));
        }
    }

i found this code here:

drawerToggle.getDrawerArrowDrawable().setColor(getResources().getColor(R.color.white));

It would be ideal, but i don't have a reference to drawerToggle...(the object is null)

i also tried to setting it using  styles.xml as should below:

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

</resources>

This code does work to set it once, but i need it reset within the application by a button click. So this is not sufficient for the what i am trying to do.

Body:
add hamburger menu icon to drawable folder

Add code where you wish to change it.

var toolbar = FindViewById<AndroidToolbar>(Resource.Id.toolbar);
var view = (AppCompatImageButton)toolbar.GetChildAt(2);
    // 1. actionmenuview (primary/secondary menu icons),
    // 2. appcompattextview (title),
    // 3. appcompatimagebutton (hamburger icon)
view.SetImageDrawable(d);
           // view.SetImageDrawable(d);

In my case, I have menu Icons so I select GetChildAt(2) [the third item]


问:
MongoDB/Mongoose query: How to get different sets of data based on a field's value
I'm using nodejs with mongoose library for my mongoDB interaction.

I'm building a landing page query (think Netflix page) and need to get ~15 results for each categories (think Comedy, Horror, Drama, ...).

It seems not like a great solution to send a query for each "category" and deal with the callback issues as well as a heavy request on the database for a simple page load...as illustrated below:

```<code>const categories = ['horror','drama','comedy']
let counterCallback = 0
let allShows = []
categories.map(category =>{
    Show.find({category: category},{limit: 15}, (err, shows)=>{
       if(shows){ allShows.push(shows)}
       allShows++
       if(allShows === categories.length){ return res.json(allShows) }
    })
})
</code>```

I was thinking maybe of making an $or request, but I can't limit for the number for each "or"s ...

```<code>const categories = ['horror','drama','comedy']
Show.find({
    $or:categories.map(category=> {return {category: category} })
},{limit: 10})
</code>```

How can I achieve a request that limits the number of results per "category"?

Thanks

答:
You may use MongoDB Aggregation framework with $group operation.

I assume you have MongoDB v4.2. For earlier versions, instead of {$replaceWith:"$data"} use {$ReplaceRoot:{newRoot:"$data"}}

```<code>Show.aggregate([
  {
    $match: {
      category: {
        $in: [
          "horror",
          "comedy",
          "drama"
        ]
      }
    }
  },
  {
    $group: {
      _id: "$category",
      data: {
        $push: "$$ROOT"
      }
    }
  },
  {
    $addFields: {
      data: {
        $slice: [
          "$data",
          15
        ]
      }
    }
  },
  {
    $unwind: "$data"
  },
  {
    $replaceWith: "$data"
  }
]).exec((err, shows) => {
    if (err) throw err;
    console.log(shows);
})
</code>```

MongoPlayground

Body:
I'm using nodejs with mongoose library for my mongoDB interaction.

I'm building a landing page query (think Netflix page) and need to get ~15 results for each categories (think Comedy, Horror, Drama, ...).

It seems not like a great solution to send a query for each "category" and deal with the callback issues as well as a heavy request on the database for a simple page load...as illustrated below:

const categories = ['horror','drama','comedy']
let counterCallback = 0
let allShows = []
categories.map(category =>{
    Show.find({category: category},{limit: 15}, (err, shows)=>{
       if(shows){ allShows.push(shows)}
       allShows++
       if(allShows === categories.length){ return res.json(allShows) }
    })
})

I was thinking maybe of making an $or request, but I can't limit for the number for each "or"s ...

const categories = ['horror','drama','comedy']
Show.find({
    $or:categories.map(category=> {return {category: category} })
},{limit: 10})

How can I achieve a request that limits the number of results per "category"?

Thanks

Body:
You may use MongoDB Aggregation framework with $group operation.

I assume you have MongoDB v4.2. For earlier versions, instead of {$replaceWith:"$data"} use {$ReplaceRoot:{newRoot:"$data"}}

Show.aggregate([
  {
    $match: {
      category: {
        $in: [
          "horror",
          "comedy",
          "drama"
        ]
      }
    }
  },
  {
    $group: {
      _id: "$category",
      data: {
        $push: "$$ROOT"
      }
    }
  },
  {
    $addFields: {
      data: {
        $slice: [
          "$data",
          15
        ]
      }
    }
  },
  {
    $unwind: "$data"
  },
  {
    $replaceWith: "$data"
  }
]).exec((err, shows) => {
    if (err) throw err;
    console.log(shows);
})

MongoPlayground


问:
labelling factors and keeping numerical values
I am having some issues with creating factors that I can refer to by both, the numeric value and the "label".

Supposedly the lfactors package does this, however I have been unable to execute it as such. So, this is what I did:

```<code>library(lfactors)
cars <- mtcars

str(cars)

'data.frame':   32 obs. of  11 variables:
 $ mpg : num  21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
 $ cyl : num  6 6 4 6 8 6 8 4 4 6 ...
 $ disp: num  160 160 108 258 360 ...
 $ hp  : num  110 110 93 110 175 105 245 62 95 123 ...
 $ drat: num  3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ...
 $ wt  : num  2.62 2.88 2.32 3.21 3.44 ...
 $ qsec: num  16.5 17 18.6 19.4 17 ...
 $ vs  : num  0 0 1 1 0 1 0 1 1 1 ...
 $ am  : num  1 1 1 0 0 0 0 0 0 0 ...
 $ gear: num  4 4 4 3 3 3 3 4 4 4 ...
 $ carb: num  4 4 1 1 2 1 4 2 2 4 ...
</code>```

If we look at the "carb" column (probably reflecting carbon emissions), its a numerical

so using the lfactors package I transformed it:

```<code>cars$carb <- lfactor(c(1:4),
                     levels = c(1:4),
                     labels = c("low", "medium", "high", "extreme" ))
str(cars)

'data.frame':   32 obs. of  11 variables:
 $ mpg : num  21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
 $ cyl : num  6 6 4 6 8 6 8 4 4 6 ...
 $ disp: num  160 160 108 258 360 ...
 $ hp  : num  110 110 93 110 175 105 245 62 95 123 ...
 $ drat: num  3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ...
 $ wt  : num  2.62 2.88 2.32 3.21 3.44 ...
 $ qsec: num  16.5 17 18.6 19.4 17 ...
 $ vs  : num  0 0 1 1 0 1 0 1 1 1 ...
 $ am  : num  1 1 1 0 0 0 0 0 0 0 ...
 $ gear: num  4 4 4 3 3 3 3 4 4 4 ...
 $ carb: Factor w/ 4 levels "low","medium",..: 1 2 3 4 1 2 3 4 1 2 ..
</code>```

I noticed that it changed to a factor, as per the package description, so I did my checks

```<code>levels(cars$carb)
[1] "low"     "medium"  "high"    "extreme" # correct

cars$carb == "medium"
[1] FALSE  TRUE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE  TRUE
[23] FALSE FALSE FALSE  TRUE FALSE FALSE FALSE  TRUE FALSE FALSE # correct

cars$carb == 2
[1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
[23] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE # incorrect
</code>```

I still cant refer to the factor by levels and values, so I wondered if anyone has used this package before or has any suggestions for an alternative?

An close alternative, but not quite there

Even though it is not perfect, as I can not refer to the factors by value and label, I found an approach that at least allowed me to store both, which I thought might be useful for others in my position:

```<code>library(sjlabelled)
library(magrittr)
library(sjmisc)

cars <- mtcars
str(cars)

'data.frame':   32 obs. of  11 variables:
 $ mpg : num  21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
 $ cyl : num  6 6 4 6 8 6 8 4 4 6 ...
 $ disp: num  160 160 108 258 360 ...
 $ hp  : num  110 110 93 110 175 105 245 62 95 123 ...
 $ drat: num  3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ...
 $ wt  : num  2.62 2.88 2.32 3.21 3.44 ...
 $ qsec: num  16.5 17 18.6 19.4 17 ...
 $ vs  : num  0 0 1 1 0 1 0 1 1 1 ...
 $ am  : num  1 1 1 0 0 0 0 0 0 0 ...
 $ gear: num  4 4 4 3 3 3 3 4 4 4 ...
 $ carb: num  4 4 1 1 2 1 4 2 2 4 ...

frq(cars$carb)

x <numeric>
# total N=32  valid N=32  mean=2.81  sd=1.62
 val frq raw.prc valid.prc cum.prc
   1   7   21.88     21.88   21.88
   2  10   31.25     31.25   53.12
   3   3    9.38      9.38   62.50
   4  10   31.25     31.25   93.75
   6   1    3.12      3.12   96.88
   8   1    3.12      3.12  100.00
  NA   0    0.00        NA      NA
</code>```

So this is what we get in its numeric form, the transformation to a factor retains the expected form:

```<code>cars$carb <- as_factor(cars$carb)

str(cars$carb)

Factor w/ 6 levels "1","2","3","4",..: 4 4 1 1 2 1 4 2 2 4 ...

frq(cars$carb)

<categorical>
# total N=32  valid N=32  mean=2.81  sd=1.62

 val frq raw.prc valid.prc cum.prc
   1   7   21.88     21.88   21.88
   2  10   31.25     31.25   53.12
   3   3    9.38      9.38   62.50
   4  10   31.25     31.25   93.75
   6   1    3.12      3.12   96.88
   8   1    3.12      3.12  100.00
  NA   0    0.00        NA      NA
</code>```

Now we have it in categorical form, we can label the values (in this example i'll ignore 6 & 8)

```<code>cars$carb<- set_labels(
  cars$carb,
  labels = c(
    `1` = "low",
    `2` = "medium",
    `3` = "high",
    `4` = "extreme"
    ))

frq(cars$carb)

<categorical>
# total N=32  valid N=32  mean=2.81  sd=1.62

 val   label frq raw.prc valid.prc cum.prc
   1     low   7   21.88     21.88   21.88
   2  medium  10   31.25     31.25   53.12
   3    high   3    9.38      9.38   62.50
   4 extreme  10   31.25     31.25   93.75
   6       6   1    3.12      3.12   96.88
   8       8   1    3.12      3.12  100.00
  NA    <NA>   0    0.00        NA      NA

</code>```

Now we can see both, the label and the value, however, there is still an issue calling the data based on the labels

```<code>cars[cars$carb==1,]
                mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Datsun 710     22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive 21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
Valiant        18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
Fiat 128       32.4   4  78.7  66 4.08 2.200 19.47  1  1    4    1
Toyota Corolla 33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1
Toyota Corona  21.5   4 120.1  97 3.70 2.465 20.01  1  0    3    1
Fiat X1-9      27.3   4  79.0  66 4.08 1.935 18.90  1  1    4    1

cars[cars$carb=="low",]

 [1] mpg  cyl  disp hp   drat wt   qsec vs   am   gear carb
<0 rows> (or 0-length row.names)
</code>```

Any advice regarding factor labelling and a way to call on factors via both the labels and values would really be appreciated. And in the meantime, I hope my alternative helps.

答:
You made a little boo boo at the very beginning.

cars$carb <- lfactor(c(1:4), ...)

Should be

cars$carb <- lfactor(cars$carb, ...)

Check:

```<code>> mtcars$carb=="medium"
 [1] FALSE FALSE FALSE FALSE  TRUE FALSE FALSE  TRUE  TRUE FALSE FALSE FALSE
[13] FALSE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE  TRUE  TRUE FALSE
[25]  TRUE FALSE  TRUE  TRUE FALSE    NA    NA  TRUE

> mtcars$carb==2
 [1] FALSE FALSE FALSE FALSE  TRUE FALSE FALSE  TRUE  TRUE FALSE FALSE FALSE
[13] FALSE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE  TRUE  TRUE FALSE
[25]  TRUE FALSE  TRUE  TRUE FALSE    NA    NA  TRUE

> all((mtcars$carb=="medium")==(mtcars$carb==2), na.rm=TRUE)
[1] TRUE
</code>```

I was a little surprised that cars$carb <- lfactor(c(1:4), ...) didn't trigger an error, or at least a warning. So I experimented:

```<code>mtcars$carb <- lfactor(c(1:5),
                        levels = c(1:4),
                        labels = c("low", "medium", "high", "extreme" ))
</code>```

```<code>Error in `$<-.data.frame`(`*tmp*`, carb, value = c(1L, 2L, 3L, 4L, NA)) :
replacement has 5 rows, data has 32
</code>```

Which makes me think that R's recycling rules are being used, although one could argue that R should at least give a warning for the incorrect command. Something like: "Warning: recycling vector to match length of dim(cars)[1]"

Regardless of the error, and lack of warning, you (the OP) then went on to say:

"I noticed that it changed to a factor, as per the package
  description, so I did my checks"

I would have tabulated the new vector because I don't always trust my coding ability, and it's always good practice whenever you make any changes to the data. Something like:

```<code>> table(cars$carb)

    low  medium    high extreme
      8       8       8       8
</code>```

would probably have been enough. That would then have sent warning bells ringing since you would have been aware that the original carb variable contains 6 levels, not 4, as well as the levels having equal frequency counts. You may have then figured out what was wrong with your previous command.

I'm not familiar with the lfactor package. I don't understand why the lfactor function doesn't assign the numeric levels for your original incorrect command. If you run the llevels function, it returns NULL, which is why your comparison using a numeric value returns FALSE for every element.

```<code>llevels(cars$carb)
NULL
</code>```

Body:
I am having some issues with creating factors that I can refer to by both, the numeric value and the "label".

Supposedly the lfactors package does this, however I have been unable to execute it as such. So, this is what I did:

library(lfactors)
cars <- mtcars

str(cars)

'data.frame':   32 obs. of  11 variables:
 $ mpg : num  21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
 $ cyl : num  6 6 4 6 8 6 8 4 4 6 ...
 $ disp: num  160 160 108 258 360 ...
 $ hp  : num  110 110 93 110 175 105 245 62 95 123 ...
 $ drat: num  3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ...
 $ wt  : num  2.62 2.88 2.32 3.21 3.44 ...
 $ qsec: num  16.5 17 18.6 19.4 17 ...
 $ vs  : num  0 0 1 1 0 1 0 1 1 1 ...
 $ am  : num  1 1 1 0 0 0 0 0 0 0 ...
 $ gear: num  4 4 4 3 3 3 3 4 4 4 ...
 $ carb: num  4 4 1 1 2 1 4 2 2 4 ...

If we look at the "carb" column (probably reflecting carbon emissions), its a numerical

so using the lfactors package I transformed it:

cars$carb <- lfactor(c(1:4),
                     levels = c(1:4),
                     labels = c("low", "medium", "high", "extreme" ))
str(cars)

'data.frame':   32 obs. of  11 variables:
 $ mpg : num  21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
 $ cyl : num  6 6 4 6 8 6 8 4 4 6 ...
 $ disp: num  160 160 108 258 360 ...
 $ hp  : num  110 110 93 110 175 105 245 62 95 123 ...
 $ drat: num  3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ...
 $ wt  : num  2.62 2.88 2.32 3.21 3.44 ...
 $ qsec: num  16.5 17 18.6 19.4 17 ...
 $ vs  : num  0 0 1 1 0 1 0 1 1 1 ...
 $ am  : num  1 1 1 0 0 0 0 0 0 0 ...
 $ gear: num  4 4 4 3 3 3 3 4 4 4 ...
 $ carb: Factor w/ 4 levels "low","medium",..: 1 2 3 4 1 2 3 4 1 2 ..

I noticed that it changed to a factor, as per the package description, so I did my checks

levels(cars$carb)
[1] "low"     "medium"  "high"    "extreme" # correct

cars$carb == "medium"
[1] FALSE  TRUE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE  TRUE
[23] FALSE FALSE FALSE  TRUE FALSE FALSE FALSE  TRUE FALSE FALSE # correct

cars$carb == 2
[1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
[23] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE # incorrect

I still cant refer to the factor by levels and values, so I wondered if anyone has used this package before or has any suggestions for an alternative?

An close alternative, but not quite there

Even though it is not perfect, as I can not refer to the factors by value and label, I found an approach that at least allowed me to store both, which I thought might be useful for others in my position:

library(sjlabelled)
library(magrittr)
library(sjmisc)

cars <- mtcars
str(cars)

'data.frame':   32 obs. of  11 variables:
 $ mpg : num  21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
 $ cyl : num  6 6 4 6 8 6 8 4 4 6 ...
 $ disp: num  160 160 108 258 360 ...
 $ hp  : num  110 110 93 110 175 105 245 62 95 123 ...
 $ drat: num  3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ...
 $ wt  : num  2.62 2.88 2.32 3.21 3.44 ...
 $ qsec: num  16.5 17 18.6 19.4 17 ...
 $ vs  : num  0 0 1 1 0 1 0 1 1 1 ...
 $ am  : num  1 1 1 0 0 0 0 0 0 0 ...
 $ gear: num  4 4 4 3 3 3 3 4 4 4 ...
 $ carb: num  4 4 1 1 2 1 4 2 2 4 ...

frq(cars$carb)

x <numeric>
# total N=32  valid N=32  mean=2.81  sd=1.62
 val frq raw.prc valid.prc cum.prc
   1   7   21.88     21.88   21.88
   2  10   31.25     31.25   53.12
   3   3    9.38      9.38   62.50
   4  10   31.25     31.25   93.75
   6   1    3.12      3.12   96.88
   8   1    3.12      3.12  100.00
  NA   0    0.00        NA      NA

So this is what we get in its numeric form, the transformation to a factor retains the expected form:

cars$carb <- as_factor(cars$carb)

str(cars$carb)

Factor w/ 6 levels "1","2","3","4",..: 4 4 1 1 2 1 4 2 2 4 ...

frq(cars$carb)

<categorical>
# total N=32  valid N=32  mean=2.81  sd=1.62

 val frq raw.prc valid.prc cum.prc
   1   7   21.88     21.88   21.88
   2  10   31.25     31.25   53.12
   3   3    9.38      9.38   62.50
   4  10   31.25     31.25   93.75
   6   1    3.12      3.12   96.88
   8   1    3.12      3.12  100.00
  NA   0    0.00        NA      NA

Now we have it in categorical form, we can label the values (in this example i'll ignore 6 & 8)

cars$carb<- set_labels(
  cars$carb,
  labels = c(
    `1` = "low",
    `2` = "medium",
    `3` = "high",
    `4` = "extreme"
    ))

frq(cars$carb)

<categorical>
# total N=32  valid N=32  mean=2.81  sd=1.62

 val   label frq raw.prc valid.prc cum.prc
   1     low   7   21.88     21.88   21.88
   2  medium  10   31.25     31.25   53.12
   3    high   3    9.38      9.38   62.50
   4 extreme  10   31.25     31.25   93.75
   6       6   1    3.12      3.12   96.88
   8       8   1    3.12      3.12  100.00
  NA    <NA>   0    0.00        NA      NA

Now we can see both, the label and the value, however, there is still an issue calling the data based on the labels

cars[cars$carb==1,]
                mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Datsun 710     22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive 21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
Valiant        18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
Fiat 128       32.4   4  78.7  66 4.08 2.200 19.47  1  1    4    1
Toyota Corolla 33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1
Toyota Corona  21.5   4 120.1  97 3.70 2.465 20.01  1  0    3    1
Fiat X1-9      27.3   4  79.0  66 4.08 1.935 18.90  1  1    4    1

cars[cars$carb=="low",]

 [1] mpg  cyl  disp hp   drat wt   qsec vs   am   gear carb
<0 rows> (or 0-length row.names)

Any advice regarding factor labelling and a way to call on factors via both the labels and values would really be appreciated. And in the meantime, I hope my alternative helps.

Body:
You made a little boo boo at the very beginning.

cars$carb <- lfactor(c(1:4), ...)

Should be

cars$carb <- lfactor(cars$carb, ...)

Check:

> mtcars$carb=="medium"
 [1] FALSE FALSE FALSE FALSE  TRUE FALSE FALSE  TRUE  TRUE FALSE FALSE FALSE
[13] FALSE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE  TRUE  TRUE FALSE
[25]  TRUE FALSE  TRUE  TRUE FALSE    NA    NA  TRUE

> mtcars$carb==2
 [1] FALSE FALSE FALSE FALSE  TRUE FALSE FALSE  TRUE  TRUE FALSE FALSE FALSE
[13] FALSE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE  TRUE  TRUE FALSE
[25]  TRUE FALSE  TRUE  TRUE FALSE    NA    NA  TRUE

> all((mtcars$carb=="medium")==(mtcars$carb==2), na.rm=TRUE)
[1] TRUE

I was a little surprised that cars$carb <- lfactor(c(1:4), ...) didn't trigger an error, or at least a warning. So I experimented:

mtcars$carb <- lfactor(c(1:5),
                        levels = c(1:4),
                        labels = c("low", "medium", "high", "extreme" ))

Error in `$<-.data.frame`(`*tmp*`, carb, value = c(1L, 2L, 3L, 4L, NA)) :
replacement has 5 rows, data has 32

Which makes me think that R's recycling rules are being used, although one could argue that R should at least give a warning for the incorrect command. Something like: "Warning: recycling vector to match length of dim(cars)[1]"

Regardless of the error, and lack of warning, you (the OP) then went on to say:

"I noticed that it changed to a factor, as per the package
  description, so I did my checks"

I would have tabulated the new vector because I don't always trust my coding ability, and it's always good practice whenever you make any changes to the data. Something like:

> table(cars$carb)

    low  medium    high extreme
      8       8       8       8

would probably have been enough. That would then have sent warning bells ringing since you would have been aware that the original carb variable contains 6 levels, not 4, as well as the levels having equal frequency counts. You may have then figured out what was wrong with your previous command.

I'm not familiar with the lfactor package. I don't understand why the lfactor function doesn't assign the numeric levels for your original incorrect command. If you run the llevels function, it returns NULL, which is why your comparison using a numeric value returns FALSE for every element.

llevels(cars$carb)
NULL


问:
Visual Studio 2008 debugging: when I click on the play button, it flashes real quick
I am having a weird issue with VS 2008 when I go to debug my program. When I click on the play button to run the program it flashes real quick and goes back to the VB IDE. No matter how many times I click on the play button it continually flashes and then goes back without displaying my form window or anything.

What type of setting would I need to change in order to correct this issue? I've been through most settings in the "my project" section and i do not see anything that could be causing it to do something like this.

My older vb apps I've made seem to work just fine when I click the play button on them. Only noticed this problem whenever I go and make a new vb app.

update video of what's going on
http://tinypic.com/r/2eycaas/7

答:
Just check your output window.
Accessible from Menu-> Debug-> Windows -> Output. (Check image:1)

In output window select Show output from: Build combobox.  (Check image:2)

This will give you perfect idea what is happening.

Following are the guesses.

The VBC installer is not installed or corrupted.

Some addon is registered to run before compiling and is creating problem.

....Long list until you tell whats shown in output window.

Also check Show output from: Debug in output window and Final check would be Immediate window.

I feel this three would give you hint whats going wrong.


问:
Slicing of list impossible after modifying __getitem__
For a specific use case I want to define a list class that returns 0 if an index is either negative or out of range.

My current approach is already serving the specific purpose:

```<code>class mlist(list):
    def __getitem__(self, n):
        if (len(self)<=n) or (n<0):
            return 0
        return super(mlist, self).__getitem__(n)

l = mlist([1,2,3,4])
l[-2]
>>> 0
l[10]
>>> 0
</code>```

But unfortunately, it causes some bad behavior when slicing the list:

```<code>l[0:2]
>>> TypeError: '<=' not supported between instances of 'int' and 'slice'
</code>```

Is there a way to fix this problem?

答:
You want to suppress IndexError and return 0 instead. So, you could alternatively do:

class mlist(list):
    def __getitem__(self, n):
        try:
            return super().__getitem__(n)
        except IndexError:
            return 0
```

<p>This, however allows negative indexing (accessing from the end) as usual lists (because this does not raise an <code>IndexError</code>). If you want to suppress that as well, you might try:</p>

<pre class="lang-py prettyprint-override"><code>class mlist(list):
    def __getitem__(self, n):
        try:
            if n < 0 or n >= len(self):
                return 0
            return super().__getitem__(n)
        except TypeError:
            return super().__getitem__(n)
</code>```

This assumes n is an int and works accordingly, and if it was not, a TypeError will be raised on the comparison and the super method will be called. This, then, both handles slices and throws the appropriate error when passing an invalid type, like string for example.

Body:
For a specific use case I want to define a list class that returns 0 if an index is either negative or out of range.

My current approach is already serving the specific purpose:

class mlist(list):
    def __getitem__(self, n):
        if (len(self)<=n) or (n<0):
            return 0
        return super(mlist, self).__getitem__(n)

l = mlist([1,2,3,4])
l[-2]
>>> 0
l[10]
>>> 0

But unfortunately, it causes some bad behavior when slicing the list:

l[0:2]
>>> TypeError: '<=' not supported between instances of 'int' and 'slice'

Is there a way to fix this problem?

Body:
You want to suppress IndexError and return 0 instead. So, you could alternatively do:

class mlist(list):
    def __getitem__(self, n):
        try:
            return super().__getitem__(n)
        except IndexError:
            return 0

This, however allows negative indexing (accessing from the end) as usual lists (because this does not raise an IndexError). If you want to suppress that as well, you might try:

class mlist(list):
    def __getitem__(self, n):
        try:
            if n < 0 or n >= len(self):
                return 0
            return super().__getitem__(n)
        except TypeError:
            return super().__getitem__(n)

This assumes n is an int and works accordingly, and if it was not, a TypeError will be raised on the comparison and the super method will be called. This, then, both handles slices and throws the appropriate error when passing an invalid type, like string for example.


问:
Typescript array.map doesn't distribute intersection types properly
I have an array of type object[] & Tree[] but arr.map(child => ...) infers the type of the child as object rather than object & Tree.

Is there any way to avoid this without extra casting?

Notably Tree extends object but typescript doesn't seem to realise this and merge the two parts of the intersection type.

EDIT - Minimal reproducible example:

This is contrived, but based off my other recent question Transform a typescript object type to a mapped type that references itself

```<code>interface BasicInterface {
    name: string;
    children: object[];
}

function getBasic<T extends object>(input: T): BasicInterface {
    return input as BasicInterface;
}

export const basicTree = getBasic({
    name: 'parent',
    children: [{
        name: 'child',
        children: []
    }]
});
</code>```

The point is the code below has access to "basicTree" and its inferred type. For this example I have defined
BasicInterface, but in practice this is generated automatically and I haven't found a way to programatically
generate a recursive interface.

I would like to add the recursive type of children back as the original interface defines.

Rather than completely redefine BasicInterface in the code as this could be a lot of boilerplate, I am trying
to "enhance" the definition of the basicTree's type with the correct recursive definition.

But this falls down when getting the children's type. Perhaps there is a simpler solution?

```<code>type RestoredInterface = typeof basicTree & {
    children: RestoredInterface[]
};

function getTree(basic: BasicInterface): RestoredInterface {
    return basic as RestoredInterface;
}

const restoredTree = getTree(basicTree);

const names = restoredTree.children.map(child => child.name);
</code>```

答:
I found a weird solution. Just change the order in the declaration. That's weird, but it works:

```<code>type RestoredInterface = {
    children: RestoredInterface[]
} & typeof basicTree;
</code>```

Edit: Here is an explanation.

A better solution can be something like this:

```<code>type RestoredInterface = Omit<typeof basicTree, 'children'> & {
    children: RestoredInterface[]
};
</code>```

See Playground

Body:
I have an array of type object[] & Tree[] but arr.map(child => ...) infers the type of the child as object rather than object & Tree.

Is there any way to avoid this without extra casting?

Notably Tree extends object but typescript doesn't seem to realise this and merge the two parts of the intersection type.

EDIT - Minimal reproducible example:

This is contrived, but based off my other recent question Transform a typescript object type to a mapped type that references itself

interface BasicInterface {
    name: string;
    children: object[];
}

function getBasic<T extends object>(input: T): BasicInterface {
    return input as BasicInterface;
}

export const basicTree = getBasic({
    name: 'parent',
    children: [{
        name: 'child',
        children: []
    }]
});

The point is the code below has access to "basicTree" and its inferred type. For this example I have defined
BasicInterface, but in practice this is generated automatically and I haven't found a way to programatically
generate a recursive interface.

I would like to add the recursive type of children back as the original interface defines.

Rather than completely redefine BasicInterface in the code as this could be a lot of boilerplate, I am trying
to "enhance" the definition of the basicTree's type with the correct recursive definition.

But this falls down when getting the children's type. Perhaps there is a simpler solution?

type RestoredInterface = typeof basicTree & {
    children: RestoredInterface[]
};

function getTree(basic: BasicInterface): RestoredInterface {
    return basic as RestoredInterface;
}

const restoredTree = getTree(basicTree);

const names = restoredTree.children.map(child => child.name);

Body:
I found a weird solution. Just change the order in the declaration. That's weird, but it works:

type RestoredInterface = {
    children: RestoredInterface[]
} & typeof basicTree;

Edit: Here is an explanation.

A better solution can be something like this:

type RestoredInterface = Omit<typeof basicTree, 'children'> & {
    children: RestoredInterface[]
};

See <a href="https://www.typescriptlang.org/play/index.html?strictFunctionTypes=false#code/JYOwLgpgTgZghgYwgAgEJwM7AQSXNeJZAbwFgAoZK5EOAWwgC5kMwpQBzAbguuQQAWwADYATKBBDMA9gCMAVhARgA2gF0e5AL4UKMAK4hlwaSGQcIYdFgQAeACrIIAD0ghRGZHMXKAfAApQAAd9MGZ7AEpma2w8SFhEFDJKagkwfSgzYNDkTDRMWPwEpE0dcgoXIOkoMH5TVmRZAoR7CRQAXnNLGIR-ZL5aBmYAciC4CXBhgBpeakERcUlmFX6%20akGmZGH5sWnZtf4hMQnltX3kLTPtCM0KMABPIJQAJQhWaohROIJE5E6Hp7SGCNZqtCAoABkJHOO0WUmQr3eEi%20RUIEHUFC0t3IAJebzAHxR8TRAEY-sgAPJ0YBgWy4oEgmxgiBTLawibDXzIKGrKjspYI-GE77FdFXLG6HGPPFIz4itEAJnJvMOCxOgtlRJ%20SAx2m5yHpwKaTLa2IMRjAJjMFjAzP8xuw0Wa8sSUQ1BORLqIKrSGTMDoQuU8iI9ctRiVKkoQ9VqEk1zPJNrtAeZNwowksNHob3JcdDomZADp%20SBC3Q4EF-LC-lzYYWNmnyuRoyAGnnCcyyZ0k217aC2hEg%207heGkCTNBtPJ128jO8WjnCyxWqwua6qxPXs42KC220LZ20ld3LMn%20%20DB3kQyPiYkFRPs1PkDPPsyFfO1ZIl5Xq%201awvNwwjZAA" rel="nofollow noreferrer">Playground


问:
React Hooks and localStorage dont set correct value
Hello I had an idea to make a hook to increase the font size and save preferences in localStorage
basically I have a state that goes from 1 to 4, and then when I click the button add I add +1 to the state until I reach number 4
and on the remove button I remove 1 from the state until 1

But I have doubts on how to save this to my location
basically if i don't use my useState just with getInitialValue It works normally.

like this gif, If I add the value manually it works:

but if I try to use my setFont I have problems (as it is saved in localStorage):

and i got this on localStorage :

code:

```<code>export default function App() {
  const { fontSize, setSize } = useFontSize();
  console.log(fontSize);
  return (
    <div className="App">
      <button
        onClick={() => {
          setSize(fontSize + 1);
        }}
      >
        add
      </button>
      <button
        onClick={() => {
          setSize(fontSize + 1);
        }}
      >
        remove
      </button>
    </div>
  );
}
</code>```

hook:

```<code>export default function useFontSize(defaultSize = { size: 1 }) {
  const [fontSize, _setSize] = useState(getInitialSize);
  function getInitialSize() {
    const savedSize = localStorage.getItem('_size_acessibility_font');
    const parsedSize = JSON.parse(savedSize);
    if (parsedSize) {
      const { size } = parsedSize;
      if (size >= 1 && size <= 4) {
        return size;
      }
    } else {
      return defaultSize.size;
    }
  }

  useEffect(() => {
    console.log(fontSize, 'on useEffect to set on localStorage');
    localStorage.setItem(
      '_size_acessibility_font',
      JSON.stringify({ size: fontSize }),
    );
  }, [fontSize]);

  return {
    fontSize,
    setSize: ({ setSize, ...size }) => {
      console.log(size, 'on function set size');
      if (size > 4) {
        return _setSize(4);
      }
      if (size < 1) {
        return _setSize(1);
      }
      return _setSize(size);
    },
  };
}
</code>```

example:

https://codesandbox.io/s/focused-newton-x0mqd

I don't know if this is the best logic for this context, if someone can help me.

答:
In useFontSize, you return

return {
  fontSize,
  setSize: ({ setSize, ...size }) => {
    console.log(size, 'on function set size');
    if (size > 4) {
      return _setSize(4);
    }
    if (size < 1) {
      return _setSize(1);
    }
    return _setSize(size);
  },
};
```

<p>
However, in <code>App</code>, you call <code>setSize</code> with just a number <code>setSize(fontSize + 1);</code> when it is expecting an object.</p>

<p>If you change <code>useFontSize</code> to return </p>

<pre class="lang-js prettyprint-override"><code>return {
  fontSize,
  setSize: (size) => {
    console.log(size, 'on function set size');
    if (size > 4) {
      return _setSize(4);
    }
    if (size < 1) {
      return _setSize(1);
    }
    return _setSize(size);
  },
};
</code>```

It should work.

Note, you will want to clear your current local storage, or add some error checking.

Also note, although it is just an example, both add and remove use fontSize + 1

Body:
Hello I had an idea to make a hook to increase the font size and save preferences in localStorage
basically I have a state that goes from 1 to 4, and then when I click the button add I add +1 to the state until I reach number 4
and on the remove button I remove 1 from the state until 1

But I have doubts on how to save this to my location
basically if i don't use my useState just with getInitialValue It works normally.

like this gif, If I add the value manually it works:

but if I try to use my setFont I have problems (as it is saved in localStorage):

and i got this on localStorage :

code:

export default function App() {
  const { fontSize, setSize } = useFontSize();
  console.log(fontSize);
  return (

      <button
        onClick={() => {
          setSize(fontSize + 1);
        }}
      >
        add
      </button>
      <button
        onClick={() => {
          setSize(fontSize + 1);
        }}
      >
        remove
      </button>

  );
}

hook:

export default function useFontSize(defaultSize = { size: 1 }) {
  const [fontSize, _setSize] = useState(getInitialSize);
  function getInitialSize() {
    const savedSize = localStorage.getItem('_size_acessibility_font');
    const parsedSize = JSON.parse(savedSize);
    if (parsedSize) {
      const { size } = parsedSize;
      if (size >= 1 && size <= 4) {
        return size;
      }
    } else {
      return defaultSize.size;
    }
  }

  useEffect(() => {
    console.log(fontSize, 'on useEffect to set on localStorage');
    localStorage.setItem(
      '_size_acessibility_font',
      JSON.stringify({ size: fontSize }),
    );
  }, [fontSize]);

  return {
    fontSize,
    setSize: ({ setSize, ...size }) => {
      console.log(size, 'on function set size');
      if (size > 4) {
        return _setSize(4);
      }
      if (size < 1) {
        return _setSize(1);
      }
      return _setSize(size);
    },
  };
}

example:

https://codesandbox.io/s/focused-newton-x0mqd

I don't know if this is the best logic for this context, if someone can help me.

Body:
In useFontSize, you return

return {
  fontSize,
  setSize: ({ setSize, ...size }) => {
    console.log(size, 'on function set size');
    if (size > 4) {
      return _setSize(4);
    }
    if (size < 1) {
      return _setSize(1);
    }
    return _setSize(size);
  },
};

However, in App, you call setSize with just a number setSize(fontSize + 1); when it is expecting an object.

If you change useFontSize to return

return {
  fontSize,
  setSize: (size) => {
    console.log(size, 'on function set size');
    if (size > 4) {
      return _setSize(4);
    }
    if (size < 1) {
      return _setSize(1);
    }
    return _setSize(size);
  },
};

It should work.

Note, you will want to clear your current local storage, or add some error checking.

Also note, although it is just an example, both add and remove use fontSize + 1


问:
NGXS and compatibility with angular 9
I must upgrade my old application running in angular 6 to new version angular 9.

I used NGXS for my application.

Is NGXS compatible with Angular 9?

答:
Yes, NGXS is compatible with Angular 9 (and Ivy).

You'll need to check the version of NGXS you are running against the change log (suggest you move to at least v3.6.0)

https://github.com/ngxs/store/blob/master/CHANGELOG.md#breaking-changes-1

Title: NGXS and compatibility with angular 9