问:
Ionic 4 cordova is not available when updating via Code Push
I am using Code Push cordova plugin for updating an Ionic 4 Cordova app. It used to work with Ionic 3 but since Ionic 4, Code Push is broken. The update seems to work but then Cordova is no longer available and therefore all native plugins are no longer working.

This is the command I am using to release an update:

```<code>appcenter codepush release-cordova -a [app_name] -d Staging --description "new update"
</code>```

I am using the latest version of the cordova-plugin-code-push (1.12.0), ionic 4, angular 8, cordova-android 8.0.0.

What has changed and how can this plugin still be used? Are there any other alternatives?

答: Solved by using ionic cordova build android instead of ionic build before running the CLI command to release the update.

Body:
I am using Code Push cordova plugin for updating an Ionic 4 Cordova app. It used to work with Ionic 3 but since Ionic 4, Code Push is broken. The update seems to work but then Cordova is no longer available and therefore all native plugins are no longer working.

This is the command I am using to release an update:

appcenter codepush release-cordova -a [app_name] -d Staging --description "new update"

I am using the latest version of the cordova-plugin-code-push (1.12.0), ionic 4, angular 8, cordova-android 8.0.0.

What has changed and how can this plugin still be used? Are there any other alternatives?


来源: stackexchange

问:
CMake can't find protobuf when compiling Google's protobuf example
I am trying to solve this problem for 2 days now with no luck. I've read an endless number of threads allover the web and tried a lot of suggestions but so far with no luck.

I'm doing this on Windows 10 with VS2017 and most recent VS Code installed. I installed protobuf with vcpkg install protobuf:

The package protobuf:x64-windows provides CMake targets:

```<code>find_package(protobuf CONFIG REQUIRED)
target_link_libraries(main PRIVATE protobuf::libprotoc protobuf::libprotobuf protobuf::libprotobuf-lite)
</code>```

I downloaded Google's example code and extracted it on my drive. The .PROTO file compiles without a problem:

```<code>d:\protobuf-3.12.2\examples>protoc -I=d:\protobuf-3.12.2\examples --cpp_out=d:\protobuf-3.12.2\examples d:\protobuf-3.12.2\examples\addressbook.proto
</code>```

and creates the two files "addressbook.pb.cc" and "addressbook.pb.h" as expected.

Now when I try to compile the project in Visual Studio Code it constantly fails no matter how I modify the CMakeLists.txt file. As mentioned I went through dozens of threads regarding this problem and tried a lot with no luck.

Update 29.05.2020

I checked that protobuf is installed just once and indeed the demo package also included a full protobuf installation. I removed this extra demo package and un-/installed protobuf with vcpgk. I then compiled the .proto file with protoc (which is in my path) and got the two files "addressbook.pb.cc" and "addressbook.pb.h".

Then I tried to compile the project again, this time using the CMakeLists.txt that came with the demo.

The relevant part seems to be right in the beginning:

```<code># Minimum CMake required
cmake_minimum_required(VERSION 2.8.12)
# Project
project(protobuf-examples)
# Find required protobuf package
find_package(protobuf CONFIG REQUIRED)
if(protobuf_VERBOSE)
  message(STATUS "Using Protocol Buffers ${Protobuf_VERSION}")
endif()
set(CMAKE_INCLUDE_CURRENT_DIR TRUE)
</code>```

Compiling this gives me:

```<code>[main] Building folder: examples
[main] Configuring folder: examples
[cms-client] Configuring using the "Visual Studio 15 2017" CMake generator with platform "x64" and toolset "host=x64"
[cmake] Selecting Windows SDK version 10.0.17763.0 to target Windows
...
[cmake] CMake Error at CMakeLists.txt:8 (find_package):
[cmake]   Could not find a package configuration file provided by "protobuf" with any
[cmake]   of the following names:
[cmake]
[cmake]     protobufConfig.cmake
[cmake]     protobuf-config.cmake
[cmake]
[cmake]   Add the installation prefix of "protobuf" to CMAKE_PREFIX_PATH or set
[cmake]   "protobuf_DIR" to a directory containing one of the above files.  If
[cmake]   "protobuf" provides a separate development package or SDK, be sure it has
[cmake]   been installed.
[cmake]
[cmake]
[cmake] Configuring incomplete, errors occurred!
[cmake] See also "d:/vcpkg/buildtrees/protobuf/src/v3.12.0-8ba83cbbdb/examples/build/CMakeFiles/CMakeOutput.log".
[cms-driver] Error during CMake configure: [cmake-server] Configuration failed.
</code>```

The file protobuf-config.cmake can be found multiple times in the protobuf folder:

D:\vcpkg\buildtrees\protobuf\<BUILDCFG>\share\protobuf\protobuf-config.cmake

D:\vcpkg\installed\<BUILDCFG>\share\protobuf\protobuf-config.cmake

D:\vcpkg\packages\<BUILDCFG>\share\protobuf\protobuf-config.cmake

What could be the cause that CMake can't locate these files?

答:
If the problem is in finding the protobuf installation then your protobuf path isn't on the Environment Variables try adding that to your path and let me know in case if it is there.
Will glad to help you more in case this doesn't work</p>

ContentLicense: CC BY-SA 4.0

Body:
I am trying to solve this problem for 2 days now with no luck. I've read an endless number of threads allover the web and tried a lot of suggestions but so far with no luck.

I'm doing this on Windows 10 with VS2017 and most recent VS Code installed. I installed protobuf with vcpkg install protobuf:

The package protobuf:x64-windows provides CMake targets:

find_package(protobuf CONFIG REQUIRED)
target_link_libraries(main PRIVATE protobuf::libprotoc protobuf::libprotobuf protobuf::libprotobuf-lite)

I downloaded Google's example code and extracted it on my drive. The .PROTO file compiles without a problem:

d:\protobuf-3.12.2\examples>protoc -I=d:\protobuf-3.12.2\examples --cpp_out=d:\protobuf-3.12.2\examples d:\protobuf-3.12.2\examples\addressbook.proto

and creates the two files "addressbook.pb.cc" and "addressbook.pb.h" as expected.

Now when I try to compile the project in Visual Studio Code it constantly fails no matter how I modify the CMakeLists.txt file. As mentioned I went through dozens of threads regarding this problem and tried a lot with no luck.

Update 29.05.2020

I checked that protobuf is installed just once and indeed the demo package also included a full protobuf installation. I removed this extra demo package and un-/installed protobuf with vcpgk. I then compiled the .proto file with protoc (which is in my path) and got the two files "addressbook.pb.cc" and "addressbook.pb.h".

Then I tried to compile the project again, this time using the CMakeLists.txt that came with the demo.

The relevant part seems to be right in the beginning:

# Minimum CMake required
cmake_minimum_required(VERSION 2.8.12)
# Project
project(protobuf-examples)
# Find required protobuf package
find_package(protobuf CONFIG REQUIRED)
if(protobuf_VERBOSE)
  message(STATUS "Using Protocol Buffers ${Protobuf_VERSION}")
endif()
set(CMAKE_INCLUDE_CURRENT_DIR TRUE)

Compiling this gives me:

[main] Building folder: examples
[main] Configuring folder: examples
[cms-client] Configuring using the "Visual Studio 15 2017" CMake generator with platform "x64" and toolset "host=x64"
[cmake] Selecting Windows SDK version 10.0.17763.0 to target Windows
...
[cmake] CMake Error at CMakeLists.txt:8 (find_package):
[cmake]   Could not find a package configuration file provided by "protobuf" with any
[cmake]   of the following names:
[cmake]
[cmake]     protobufConfig.cmake
[cmake]     protobuf-config.cmake
[cmake]
[cmake]   Add the installation prefix of "protobuf" to CMAKE_PREFIX_PATH or set
[cmake]   "protobuf_DIR" to a directory containing one of the above files.  If
[cmake]   "protobuf" provides a separate development package or SDK, be sure it has
[cmake]   been installed.
[cmake]
[cmake]
[cmake] Configuring incomplete, errors occurred!
[cmake] See also "d:/vcpkg/buildtrees/protobuf/src/v3.12.0-8ba83cbbdb/examples/build/CMakeFiles/CMakeOutput.log".
[cms-driver] Error during CMake configure: [cmake-server] Configuration failed.

The file protobuf-config.cmake can be found multiple times in the protobuf folder:

D:\vcpkg\buildtrees\protobuf\<BUILDCFG>\share\protobuf\protobuf-config.cmake

D:\vcpkg\installed\<BUILDCFG>\share\protobuf\protobuf-config.cmake

D:\vcpkg\packages\<BUILDCFG>\share\protobuf\protobuf-config.cmake

What could be the cause that CMake can't locate these files?


问:
google drive api for android delay retrieve created file
What I'm trying to do here - is to create a file in my drive via Google Drive Api and retrieve/restore when the file is ready

I use this function bellow to create file :

```<code>    private void sendToDrive(File file,String nameFile){
     getDriveResourceClient()
            .createContents()
            .continueWithTask(task -> {
                DriveContents contents = task.getResult();
                OutputStream outputStream = contents.getOutputStream();
                FileInputStream fis = new FileInputStream(file);
                byte[] buffer = new byte[1024];
                int length;
                while ((length = fis.read(buffer)) > 0) {
                    outputStream.write(buffer, 0, length);
                }

                MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
                        .setTitle(nameFile)
                        .setStarred(true)
                        .build();

                return getDriveResourceClient().createFile(AppFolder, changeSet, contents);
            }).addOnSuccessListener(new OnSuccessListener<DriveFile>() {
                @Override
                public void onSuccess(DriveFile driveFile) {

                   Log.e("sendFile","onSuccess");
                }
            }).addOnCompleteListener(new OnCompleteListener<DriveFile>() {
                @Override
                public void onComplete(@NonNull Task<DriveFile> task) {
                    Log.e("sendFile", "OnComplete");
                }
            });

}
</code>```

When I call this function for a file I can see both log OnComplete and OnSuccess.

But just after that if I list the files in the folder - I cannot find the file ( especially if it is a big file )

I use this method to get the list of all files in a the drive folder in question:

```<code>protected void getAllFileFromDrive(){
    DriveApi.MetadataBufferResult metadataBufferResult = AppFolder.listChildren(getDriveClient().asGoogleApiClient()).await();

    if (!metadataBufferResult.getStatus().isSuccess()) {
        metadataBufferResult.release();
    }else
    {

        MetadataBuffer metadataBuffer = metadataBufferResult.getMetadataBuffer();
        if (metadataBuffer.getCount() == 0) {
            metadataBuffer.release();
        }else{

            for (int i = 0 ; i < metadataBuffer.getCount(); i++)
            {
                Metadata item = metadataBuffer.get(i);
               if (item==null || item.getOriginalFilename()== null)
                    continue;
                Log.e("File",item.getOriginalFilename());
            }
            metadataBuffer.release();
            metadataBufferResult.release();
        }

    }

}
</code>```

But I don't find the file in the log, so I need wait some time so I can see it.
I tried to call syncRequest, and nothing changed, I need to wait like 1 minutes or more ( if the file is more big ).
I can understand that drive is doing some stuff with my file in the background , but I'll like to know when he is done or wait until he done all the process.

All my code is for Android using Drive API with implementation 'com.google.android.gms:play-services-drive:17.0.0'
 in my gradle ( and it deprecated ).

Thanks.

答:
You know that GDAA has be deprecated.

Drive updates the server according to its own schedule. It's been a while, but I don't think that there is much you can do to influence that schedule. My thought is that the delay is due to Drive uploading your file and not any real significant processing on the backend.

You can be informed of completion of the upload by monitoring completion events if I recall correctly.

Body:
What I'm trying to do here - is to create a file in my drive via Google Drive Api and retrieve/restore when the file is ready

I use this function bellow to create file :

    private void sendToDrive(File file,String nameFile){
     getDriveResourceClient()
            .createContents()
            .continueWithTask(task -> {
                DriveContents contents = task.getResult();
                OutputStream outputStream = contents.getOutputStream();
                FileInputStream fis = new FileInputStream(file);
                byte[] buffer = new byte[1024];
                int length;
                while ((length = fis.read(buffer)) > 0) {
                    outputStream.write(buffer, 0, length);
                }

                MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
                        .setTitle(nameFile)
                        .setStarred(true)
                        .build();

                return getDriveResourceClient().createFile(AppFolder, changeSet, contents);
            }).addOnSuccessListener(new OnSuccessListener<DriveFile>() {
                @Override
                public void onSuccess(DriveFile driveFile) {

                   Log.e("sendFile","onSuccess");
                }
            }).addOnCompleteListener(new OnCompleteListener<DriveFile>() {
                @Override
                public void onComplete(@NonNull Task<DriveFile> task) {
                    Log.e("sendFile", "OnComplete");
                }
            });

}

When I call this function for a file I can see both log OnComplete and OnSuccess.

But just after that if I list the files in the folder - I cannot find the file ( especially if it is a big file )

I use this method to get the list of all files in a the drive folder in question:

protected void getAllFileFromDrive(){
    DriveApi.MetadataBufferResult metadataBufferResult = AppFolder.listChildren(getDriveClient().asGoogleApiClient()).await();

    if (!metadataBufferResult.getStatus().isSuccess()) {
        metadataBufferResult.release();
    }else
    {

        MetadataBuffer metadataBuffer = metadataBufferResult.getMetadataBuffer();
        if (metadataBuffer.getCount() == 0) {
            metadataBuffer.release();
        }else{

            for (int i = 0 ; i < metadataBuffer.getCount(); i++)
            {
                Metadata item = metadataBuffer.get(i);
               if (item==null || item.getOriginalFilename()== null)
                    continue;
                Log.e("File",item.getOriginalFilename());
            }
            metadataBuffer.release();
            metadataBufferResult.release();
        }

    }

}

But I don't find the file in the log, so I need wait some time so I can see it.
I tried to call syncRequest, and nothing changed, I need to wait like 1 minutes or more ( if the file is more big ).
I can understand that drive is doing some stuff with my file in the background , but I'll like to know when he is done or wait until he done all the process.

All my code is for Android using Drive API with implementation 'com.google.android.gms:play-services-drive:17.0.0'
 in my gradle ( and it deprecated ).

Thanks.


问:
How to remove unnecessary single quotation marks (') from column names in a R data frame?
unfortunately I have got colnames, which all have additional single quotation marks like here:

```<code>x <- data.frame(c(11,21,31),c(12,22,32),c(13,23,33))
colnames(x) <- c("'A'","'B'","'C'")
</code>```

So my question is, if I can get rid of those "'" for my entire data frame?
Preferably not retyping the colnames, and using tidyR code?
Thanks!

Body:
unfortunately I have got colnames, which all have additional single quotation marks like here:

x <- data.frame(c(11,21,31),c(12,22,32),c(13,23,33))
colnames(x) <- c("'A'","'B'","'C'")

So my question is, if I can get rid of those "'" for my entire data frame?
Preferably not retyping the colnames, and using tidyR code?
Thanks!

Body:
In base R:

names(x) <- gsub("'", "", names(x))

x
   A  B  C
1 11 12 13
2 21 22 23
3 31 32 33


问:
Populate HTML card dynamically by fetching details from an overlay
I am trying to make an HTML card that gets populated with the values and images that are input from an overlay.

I need help in getting the data from an overlay to the card
2.Populating the data and image in the card like the below card sample.

An example of a single section would be very helpful.

```<code>        <!-- Overlay -->
          <div class="ibm-common-overlay ibm-overlay-alt-two" data-widget="overlay" data-type="alert" id="overlayExampleAlert">

            <form id="overlay" class="ibm-row-form" method="post" action="__REPLACE_ME__">

              <h1 class="ibm-bold">Usecase 1</h1>

              <div class="ibm-fluid">
                <div class="ibm-col-12-12">

                  <label for="uc-title">Use case title<span class="ibm-required">*</span></label></br>
                  <span>
                    <input type="text" value="" size="40" id="uc-title" name="uc-title">
                  </span>
                </div>
              </div>

              <div class="ibm-fluid">
                <div class="ibm-col-12-12">
                  <label for="uc-desc">Use case description<span class="ibm-required">*</span></label></br>
                  <span>
                    <input type="text" value="" size="40" id="uc-desc" name="uc-desc">
                </div>
              </div>

              <div class="ibm-fluid">
                <div class="ibm-col-12-12">
                  <p class="ibm-form-elem-grp">
                    <label>No of scene(s)<span class="ibm-required">*</span></label></br>
                    <span>
                      <select id="scenes">
                        <option value="" selected>Select one</option>
                        <option value="A">1</option>
                        <option value="B">2</option>
                        <option value="C">3</option>
                        <option value="D">4</option>
                        <option value="E">5</option>
                        <option value="F">6</option>
                      </select>
                    </span>
                  </p>
                </div>
              </div>

              <div class="ibm-fluid">
                <div class="ibm-col-12-12">
                  <label for="myInputField1">Usecase Image<span class="ibm-required">*</span></a></label>
                  <span>
                    <input id="myInputField1" type="file" data-widget="fileinput" data-multiple="false" />
                  </span>
                </div>
              </div>

              <div class="ibm-fluid">
                <div class="ibm-col-12-12">
                  <p class="ibm-btn-row"><button class="ibm-btn-pri ibm-btn-blue-50" style="float:right;" onclick="IBMCore.common.widget.overlay.hide('overlayExampleAlert',true);">Save</button> <button
                      class="ibm-btn-sec ibm-btn-transparent ibm-btn-blue-50" style="float:right" ; onclick="IBMCore.common.widget.overlay.hide('overlayExampleAlert',true);">Cancel</button></p>
                </div>
</code>```

答:
In this example the function to generate the card is bound to an additional button labeled "Get" as it's not possible to use the "Save" button which has a CMS-function bound to it that won't work outside of the CMS.

$("#get").on("click", function() {
  let title = $("#uc-title").val();
  let desc = $("#uc-desc").val();
  let scene = $("#scenes option:selected").html();
  let image = $("#myInputField1").next("span").text().replace("(", "").replace(")", "");
  let card = "

" + title + "

" + desc + "

No of scene(s): " + scene + "

";
  document.body.insertAdjacentHTML("beforeend", card);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
 <h1 class="ibm-bold">Usecase 1</h1>

              <div class="ibm-fluid">
                <div class="ibm-col-12-12">

                  <label for="uc-title">Use case title<span class="ibm-required">*</span></label></br>
                  <span>
                    <input type="text" value="" size="40" id="uc-title" name="uc-title">
                  </span>
                </div>
              </div>

              <div class="ibm-fluid">
                <div class="ibm-col-12-12">
                  <label for="uc-desc">Use case description<span class="ibm-required">*</span></label></br>
                  <span>
                    <input type="text" value="" size="40" id="uc-desc" name="uc-desc">
                </div>
              </div>

              <div class="ibm-fluid">
                <div class="ibm-col-12-12">
                  <p class="ibm-form-elem-grp">
                    <label>No of scene(s)<span class="ibm-required">*</span></label></br>
                    <span>
                      <select id="scenes">
                        <option value="" selected>Select one</option>
                        <option value="A">1</option>
                        <option value="B">2</option>
                        <option value="C">3</option>
                        <option value="D">4</option>
                        <option value="E">5</option>
                        <option value="F">6</option>
                      </select>
                    </span>
                  </p>
                </div>
              </div>

              <div class="ibm-fluid">
                <div class="ibm-col-12-12">
                  <label for="myInputField1">Usecase Image<span class="ibm-required">*</span></a></label>
                  <span>
                    <input id="myInputField1" type="file" data-widget="fileinput" data-multiple="false" />
                    <span>(IMG_3861.jpg)</span>
                  </span>
                </div>
              </div>

              <div class="ibm-fluid">
                <div class="ibm-col-12-12">
                  <p class="ibm-btn-row"><button class="ibm-btn-pri ibm-btn-blue-50" style="float:right;" onclick="IBMCore.common.widget.overlay.hide('overlayExampleAlert',true);">Save</button> <button
                      class="ibm-btn-sec ibm-btn-transparent ibm-btn-blue-50" style="float:right" ; onclick="IBMCore.common.widget.overlay.hide('overlayExampleAlert',true);">Cancel</button></p>
                </div>
                <button id="get">
                Get
                </button></code>```

Body:
I am trying to make an HTML card that gets populated with the values and images that are input from an overlay.

I need help in getting the data from an overlay to the card
2.Populating the data and image in the card like the below card sample.

An example of a single section would be very helpful.

            <form id="overlay" class="ibm-row-form" method="post" action="__REPLACE_ME__">

Usecase 1

                  Use case title*

                    <input type="text" value="" size="40" id="uc-title" name="uc-title">

                  Use case description*

                    <input type="text" value="" size="40" id="uc-desc" name="uc-desc">

                    No of scene(s)*

                      <select id="scenes">
                        <option value="" selected>Select one</option>
                        <option value="A">1</option>
                        <option value="B">2</option>
                        <option value="C">3</option>
                        <option value="D">4</option>
                        <option value="E">5</option>
                        <option value="F">6</option>
                      </select>

                  Usecase Image*

                    <input id="myInputField1" type="file" data-widget="fileinput" data-multiple="false" />

<button class="ibm-btn-pri ibm-btn-blue-50" style="float:right;" onclick="IBMCore.common.widget.overlay.hide('overlayExampleAlert',true);">Save</button> <button
                      class="ibm-btn-sec ibm-btn-transparent ibm-btn-blue-50" style="float:right" ; onclick="IBMCore.common.widget.overlay.hide('overlayExampleAlert',true);">Cancel</button>

Body:
In this example the function to generate the card is bound to an additional button labeled "Get" as it's not possible to use the "Save" button which has a CMS-function bound to it that won't work outside of the CMS.

$("#get").on("click", function() {
  let title = $("#uc-title").val();
  let desc = $("#uc-desc").val();
  let scene = $("#scenes option:selected").html();
  let image = $("#myInputField1").next("span").text().replace("(", "").replace(")", "");
  let card = "<div class='card'><div class='card-image'><img src='/images/" + image + "'/></div><div class='title'>" + title + "</div><div class='desc'>" + desc + "</div><div class='scene'>No of scene(s): " + scene + "</div></div>";
  document.body.insertAdjacentHTML("beforeend", card);
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
 <h1 class="ibm-bold">Usecase 1</h1>

              <div class="ibm-fluid">
                <div class="ibm-col-12-12">

                  <label for="uc-title">Use case title<span class="ibm-required">*</span></label></br>
                  <span>
                    <input type="text" value="" size="40" id="uc-title" name="uc-title">
                  </span>
                </div>
              </div>

              <div class="ibm-fluid">
                <div class="ibm-col-12-12">
                  <label for="uc-desc">Use case description<span class="ibm-required">*</span></label></br>
                  <span>
                    <input type="text" value="" size="40" id="uc-desc" name="uc-desc">
                </div>
              </div>

              <div class="ibm-fluid">
                <div class="ibm-col-12-12">
                  <p class="ibm-form-elem-grp">
                    <label>No of scene(s)<span class="ibm-required">*</span></label></br>
                    <span>
                      <select id="scenes">
                        <option value="" selected>Select one</option>
                        <option value="A">1</option>
                        <option value="B">2</option>
                        <option value="C">3</option>
                        <option value="D">4</option>
                        <option value="E">5</option>
                        <option value="F">6</option>
                      </select>
                    </span>
                  </p>
                </div>
              </div>

              <div class="ibm-fluid">
                <div class="ibm-col-12-12">
                  <label for="myInputField1">Usecase Image<span class="ibm-required">*</span></a></label>
                  <span>
                    <input id="myInputField1" type="file" data-widget="fileinput" data-multiple="false" />
                    <span>(IMG_3861.jpg)</span>
                  </span>
                </div>
              </div>

              <div class="ibm-fluid">
                <div class="ibm-col-12-12">
                  <p class="ibm-btn-row"><button class="ibm-btn-pri ibm-btn-blue-50" style="float:right;" onclick="IBMCore.common.widget.overlay.hide('overlayExampleAlert',true);">Save</button> <button
                      class="ibm-btn-sec ibm-btn-transparent ibm-btn-blue-50" style="float:right" ; onclick="IBMCore.common.widget.overlay.hide('overlayExampleAlert',true);">Cancel</button></p>
                </div>
                <button id="get">
                Get
                </button>


问:
Sharepoint List - create item in with lookup values
https://learn.microsoft.com/de-de/graph/api/listitem-create?view=graph-rest-1.0&tabs=http

explains how to create a JSON POST for a "create item" in a simple list.

I am looking for an example with lookup columns -- as cut and past of "get response" fails for list fields definition.

e.g.

```<code>{
    "fields": {
        "Title": "2020-of-003",
        "F8_LOOKUP": [
            {
                "LookupId": 6,
                "LookupValue": "Alfred Anders"
            }
        ]
    }
}
</code>```

答:
just concat LookupId to your field-name and add odata.type for multi lookup
https://github.com/microsoftgraph/microsoft-graph-docs/issues/2991#issuecomment-443347657

```<code>POST
https://graph.microsoft.com/v1.0/sites/{site-id}/lists/{list-id}/items
</code>```

multi lookup:

```<code>{
  "fields": {
    "Title": "From graph",
    "fieldnameLookupId@odata.type": "Collection(Edm.Int32)",
    "fieldnameLookupId": [1,2]
  }
}
</code>```

lookup:

```<code>{
  "fields": {
    "Title": "From graph",
    "fieldnameLookupId": 1
  }
}
</code>```

Body:
https://learn.microsoft.com/de-de/graph/api/listitem-create?view=graph-rest-1.0&tabs=http

explains how to create a JSON POST for a "create item" in a simple list.

I am looking for an example with lookup columns -- as cut and past of "get response" fails for list fields definition.

e.g.

{
    "fields": {
        "Title": "2020-of-003",
        "F8_LOOKUP": [
            {
                "LookupId": 6,
                "LookupValue": "Alfred Anders"
            }
        ]
    }
}

Body:
just concat LookupId to your field-name and add odata.type for multi lookup
https://github.com/microsoftgraph/microsoft-graph-docs/issues/2991#issuecomment-443347657

POST
https://graph.microsoft.com/v1.0/sites/{site-id}/lists/{list-id}/items

multi lookup:

{
  "fields": {
    "Title": "From graph",
    "fieldnameLookupId@odata.type": "Collection(Edm.Int32)",
    "fieldnameLookupId": [1,2]
  }
}

lookup:

{
  "fields": {
    "Title": "From graph",
    "fieldnameLookupId": 1
  }
}


问:
CS50 Pset4 Sepia Filter, where is the bug? The code doesn't pass the CS50 tests
So this is the code I have for Pset4 for the Sepia filter...it's heading in the right direction but I've been trying to figure out why it isn't passing the tests. Cannot filter a simple 3 x 3 image or complex 3 x 3 image or the 4 x 4 image. Trying to figure out where the bug is, any tips would be wonderful!

```<code>void grayscale(int height, int width, RGBTRIPLE image[height][width])
{
for (int i = 0; i < height; i++)
{
    for (int j = 0; j < width; j++)
    {

        // get values of each colour in the image
        int red = image[i][j].rgbtRed;
        int blue = image[i][j].rgbtBlue;
        int green = image[i][j].rgbtGreen;

        // find average of the pixel RBG colors
        float average = (round(red) + round(blue) + round(green)) / 3;
        average = round(average);

        //puts the value average into the pixel colors
        image[i][j].rgbtRed = average;
        image[i][j].rgbtBlue = average;
        image[i][j].rgbtGreen = average;
    }
}
return;
</code>```

}

```<code>void sepia(int height, int width, RGBTRIPLE image[height][width])
{
    for (int i = 0; i < height; i++)
    {
        for (int j = 0; j < width; j++)
      {
        //gets the values of each color in the image
        int red = image[i][j].rgbtRed;
        int blue = image[i][j].rgbtBlue;
        int green = image[i][j].rgbtGreen;

        // gets the sepia value of the pixels
        int sepiaRed = round(0.393 * red + 0.769 * green + 0.189 * blue);

        int sepiaGreen = round(0.349 * red + 0.686 * green + 0.168 * blue);

        int sepiaBlue = round(0.272 * red + 0.534 * green + 0.131 * blue);

        if (sepiaRed >= 256)
        {
            sepiaRed = 255;

        }

        if (sepiaGreen  >= 256)
        {
            sepiaGreen = 255;

        }

        if (sepiaBlue  >= 256)
        {
            sepiaBlue= 255;

        }
            image[i][j].rgbtRed = sepiaRed;
            image[i][j].rgbtBlue = sepiaBlue;
            image[i][j].rgbtGreen = sepiaGreen;

    }
    return;
}
</code>```

}

答:
I'm not sure, without seeing more of the code. But shouldn't these three ifs at the end be placed before you save their values to the image? Like this:

```<code>...
        if (sepiaRed >= 256)
        {
            sepiaRed = 255;

        }

        if (sepiaGreen  >= 256)
        {
            sepiaGreen  = 255;

        }

        if (sepiaBlue  >= 256)
        {
            sepiaBlue  = 255;

        }

        image[i][j].rgbtRed = sepiaRed;
        image[i][j].rgbtBlue = sepiaBlue;
        image[i][j].rgbtGreen = sepiaGreen;
...
</code>```

First You check if calculated values are not higher than 255. Then save these values to the image.
Also you should replace 'else if' with 'if' to check all 3 values not up to one. And then edit value of sepiaRed, sepiaBlue, sepiaGreen not red, blue, green.
I'm not sure if I get right what that function suppose to do.

Body:
So this is the code I have for Pset4 for the Sepia filter...it's heading in the right direction but I've been trying to figure out why it isn't passing the tests. Cannot filter a simple 3 x 3 image or complex 3 x 3 image or the 4 x 4 image. Trying to figure out where the bug is, any tips would be wonderful!

void grayscale(int height, int width, RGBTRIPLE image[height][width])
{
for (int i = 0; i < height; i++)
{
    for (int j = 0; j < width; j++)
    {

        // get values of each colour in the image
        int red = image[i][j].rgbtRed;
        int blue = image[i][j].rgbtBlue;
        int green = image[i][j].rgbtGreen;

        // find average of the pixel RBG colors
        float average = (round(red) + round(blue) + round(green)) / 3;
        average = round(average);

        //puts the value average into the pixel colors
        image[i][j].rgbtRed = average;
        image[i][j].rgbtBlue = average;
        image[i][j].rgbtGreen = average;
    }
}
return;

}

void sepia(int height, int width, RGBTRIPLE image[height][width])
{
    for (int i = 0; i < height; i++)
    {
        for (int j = 0; j < width; j++)
      {
        //gets the values of each color in the image
        int red = image[i][j].rgbtRed;
        int blue = image[i][j].rgbtBlue;
        int green = image[i][j].rgbtGreen;

        // gets the sepia value of the pixels
        int sepiaRed = round(0.393 * red + 0.769 * green + 0.189 * blue);

        int sepiaGreen = round(0.349 * red + 0.686 * green + 0.168 * blue);

        int sepiaBlue = round(0.272 * red + 0.534 * green + 0.131 * blue);

        if (sepiaRed >= 256)
        {
            sepiaRed = 255;

        }

        if (sepiaGreen  >= 256)
        {
            sepiaGreen = 255;

        }

        if (sepiaBlue  >= 256)
        {
            sepiaBlue= 255;

        }
            image[i][j].rgbtRed = sepiaRed;
            image[i][j].rgbtBlue = sepiaBlue;
            image[i][j].rgbtGreen = sepiaGreen;

    }
    return;
}

}

Body:
I'm not sure, without seeing more of the code. But shouldn't these three ifs at the end be placed before you save their values to the image? Like this:

...
        if (sepiaRed >= 256)
        {
            sepiaRed = 255;

        }

        if (sepiaGreen  >= 256)
        {
            sepiaGreen  = 255;

        }

        if (sepiaBlue  >= 256)
        {
            sepiaBlue  = 255;

        }

        image[i][j].rgbtRed = sepiaRed;
        image[i][j].rgbtBlue = sepiaBlue;
        image[i][j].rgbtGreen = sepiaGreen;
...

First You check if calculated values are not higher than 255. Then save these values to the image.
Also you should replace 'else if' with 'if' to check all 3 values not up to one. And then edit value of sepiaRed, sepiaBlue, sepiaGreen not red, blue, green.
I'm not sure if I get right what that function suppose to do.


问:
DataFrame split by index condition. Split DataFrame into Bars
I need to split Python DataFrame with datetime index column into Bars with specific "Length". I.e. one dataframe should be splitted into 30min bars, 60min bars, 240 min bars and etc.
Currently I'm trying to split it with loop like this:

```<code>class Bar:
    def __init__(self, o, h, l, c, v):
        self.Open = o
        self.High = h
        self.Low = l
        self.Close = c
        self.Volume = v
def GenerateBar(smallBars):
    o = smallBars["Open"][0]
    h = smallBars["High"].max()
    l = smallBars["Low"].min()
    c = smallBars["Close"][-1]
    vol = smallBars["Volume"].sum()
    return Bar(o, h, l, c, vol)
def GenerateBars(df, duration):
    while cur_time <= last_date:
        next_time = cur_time + timedelta(minutes = duration)
        cur_bar = GenerateBar(df[(df.index >= cur_time)&(df.index < next_time)])
</code>```

But this way takes a way too long to split DataFrame into bars.

答:
If you have a dataframe with a datetimeIndex, you can use resample. Also check out this guide.

Assuming df is your dataframe you want to convert, a resample for 30 minutes (30T) would look like this:

```<code>df = df.resample('30T').sum()
</code>```

With this simple solution you have a problem if you need the mean of one column (e.g. price) and the sum of another column (e.g. volume). You can do this by using df.agg.

```<code>df = df.resample('30T').agg(['mean', 'sum'])
</code>```

Body:
I need to split Python DataFrame with datetime index column into Bars with specific "Length". I.e. one dataframe should be splitted into 30min bars, 60min bars, 240 min bars and etc.
Currently I'm trying to split it with loop like this:

class Bar:
    def __init__(self, o, h, l, c, v):
        self.Open = o
        self.High = h
        self.Low = l
        self.Close = c
        self.Volume = v
def GenerateBar(smallBars):
    o = smallBars["Open"][0]
    h = smallBars["High"].max()
    l = smallBars["Low"].min()
    c = smallBars["Close"][-1]
    vol = smallBars["Volume"].sum()
    return Bar(o, h, l, c, vol)
def GenerateBars(df, duration):
    while cur_time <= last_date:
        next_time = cur_time + timedelta(minutes = duration)
        cur_bar = GenerateBar(df[(df.index >= cur_time)&(df.index < next_time)])

But this way takes a way too long to split DataFrame into bars.

Body:
If you have a dataframe with a datetimeIndex, you can use resample. Also check out this guide.

Assuming df is your dataframe you want to convert, a resample for 30 minutes (30T) would look like this:

df = df.resample('30T').sum()

With this simple solution you have a problem if you need the mean of one column (e.g. price) and the sum of another column (e.g. volume). You can do this by using df.agg.

df = df.resample('30T').agg(['mean', 'sum'])


问:
Getting OpenCV headers to work correctly on install in Linux
I have an OpenCV installation on Ubuntu Linux. From any example the headers are:

```<code>#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>
</code>```

When I compile with these includes I get the error :

```<code>fatal error: opencv2/imgcodecs.hpp: No such file or directory

#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>
</code>```

I can find out where OpenCV is located with

```<code>pkg-config --cflags --libs opencv
</code>```

which outputs as follow:

```<code> "Package opencv was not found"
</code>```

When I try pkg-config --cflags --libs opencv2

I get:

```<code>"Package opencv2 was not found"
</code>```

Only when I use pkg-config --cflags --libs opencv4  do I get the path:

```<code>-I/usr/local/include/opencv4/opencv2
</code>```

so I thought that by changing the includes to:

```<code>#include <opencv4/imgcodecs.hpp>
#include <opencv4/highgui.hpp>
</code>```

it would work. But I get:

```<code>fatal error: opencv4/imgcodecs.hpp: No such file or directory

#include <opencv4/imgcodecs.hpp>
</code>```

so when I try the full path:

```<code>#include <opencv4/opencv2/imgcodecs.hpp>
</code>```

I get:

```<code>imgcodecs.hpp:46:10: fatal error: opencv2/core.hpp: No such file or directory

#include "opencv2/core.hpp"
</code>```

and of course in the hpp file in question it is:

```<code>#include "opencv2/core.hpp"
</code>```

Is there a simple way to fix all this?

答:
I actually ran into this issue recently. The issue is that when you build OpenCV it places the header files in /usr/local/include/opencv4/ then underneath that you will see opencv2/opencv.hpp and all the other files you're referencing. To fix your issue you will need to run in bash:

sudo ln -s /usr/local/include/opencv4/opencv2 /usr/local/include/opencv2

This resolved the issue for me, if it works for you please be sure to mark this as the answer.

Body:
I have an OpenCV installation on Ubuntu Linux. From any example the headers are:

#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>

When I compile with these includes I get the error :

fatal error: opencv2/imgcodecs.hpp: No such file or directory

#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>

I can find out where OpenCV is located with

pkg-config --cflags --libs opencv

which outputs as follow:

 "Package opencv was not found"

When I try pkg-config --cflags --libs opencv2

I get:

"Package opencv2 was not found"

Only when I use pkg-config --cflags --libs opencv4  do I get the path:

-I/usr/local/include/opencv4/opencv2

so I thought that by changing the includes to:

#include <opencv4/imgcodecs.hpp>
#include <opencv4/highgui.hpp>

it would work. But I get:

fatal error: opencv4/imgcodecs.hpp: No such file or directory

#include <opencv4/imgcodecs.hpp>

so when I try the full path:

#include <opencv4/opencv2/imgcodecs.hpp>

I get:

imgcodecs.hpp:46:10: fatal error: opencv2/core.hpp: No such file or directory

#include "opencv2/core.hpp"

and of course in the hpp file in question it is:

#include "opencv2/core.hpp"

Is there a simple way to fix all this?


问:
Can Windows and Linux developers work together on the same project using C# and ASP.net?
If a group of developers are working on a project written using ASP.net and C# in a Windows environment with Visual Studio, is there any way a developer can join their team and work with them on the project in a Linux environment? I know about the open source, cross-platform development framework Mono, could this be an option or would the Windows developers have to use this as well for that to work? Is the best option for a Linux developer to just install a Windows partition or can he join them without doing so?</p>

答: Yes!  Use MonoDevelop and a source management solution like Mercurial.</p>

ContentLicense: CC BY-SA 3.0


问:
Python Flask_SQLAlchemy query.order_by(time)
I am trying to sort data in a database by the time.  I am utilizing the flask_sqlalchemy tool.

The database that I'm trying to order by the time is initialized with this class:

```<code>class Weather(db.Model):
    __bind_key__ = 'weather'
    id = db.Column(db.Integer, primary_key=True)
    time = db.Column(db.DateTime, unique=True, nullable=False)
    weather = db.Column(db.String(200), nullable=False)

    def __repr__(self):
        return '<Weather %r>' % self.id
</code>```

In this class, I'm gettin data from the open source http://api.openweathermap.org/.  I know that the code to retrieve the data works because I can visualize it on my Flask app.  However, when I query it with weather = Weather.query.order_by(Weather.time).all() I want the data to be ordered by the time of the DateTime object, instead it's just stuck ordering it by the date.  If anyone can help I'd appreciate it.

答:
This should work:</p>

```<code>weather = Weather.query.order_by(extract('hour', Weather.time)).all()
</code>```

Body:
I am trying to sort data in a database by the time.  I am utilizing the flask_sqlalchemy tool.

The database that I'm trying to order by the time is initialized with this class:

class Weather(db.Model):
    __bind_key__ = 'weather'
    id = db.Column(db.Integer, primary_key=True)
    time = db.Column(db.DateTime, unique=True, nullable=False)
    weather = db.Column(db.String(200), nullable=False)

    def __repr__(self):
        return '<Weather %r>' % self.id

In this class, I'm gettin data from the open source http://api.openweathermap.org/.  I know that the code to retrieve the data works because I can visualize it on my Flask app.  However, when I query it with weather = Weather.query.order_by(Weather.time).all() I want the data to be ordered by the time of the DateTime object, instead it's just stuck ordering it by the date.  If anyone can help I'd appreciate it.

Body:
This should work:

weather = Weather.query.order_by(extract('hour', Weather.time)).all()


问:
How to test ngx-toastr with protractor in Angular 2
I'm using ngx-toastr with my angular 2 application and i've started running some e2e tests against it. I'm having difficulties testing the toastr as it pops up and dissapears after 5 seconds.

I've tried adding several different selection methods as suggested on Stackoverflow, without luck.

What i've tried:

```<code>getToastr() {
    var EC = protractor.ExpectedConditions;
    var targetEle = element(by.css(".toast-message"));

    browser.wait(EC.visibilityOf(targetEle), 10000, 'NOT VISIBLE'); //wait until
    //ele visible
    browser.wait(EC.presenceOf(targetEle), 10000, 'NOT PRESENT');
}
</code>```

which makes it hit the not visible code, eventhough i see the toastr present in the window - it is not able to find it in the dom. I've taken a screenshot of the dom to show you the position as i think it may have something to do with this.

Here's a screenshot of the dom Screenshot of DOM, i'm trying to toast within the start-signup section. Note that the router-outlet named Default does not wrap start-signup, even though it's declared in the router to use this outlet - i don't know if this is by design or not.

```<code>{
    path: 'signup',
    children: [
        { path: '', component: StartSignupComponent, outlet: 'default' }
    ]
},
</code>```

It appears as though the toastr div is not inside the start-signup tag. I haven't been able to move it inside, even with the ngx-toastr's own method to move the toastr message inside a div "of your choosing". Currently i placed it in app.component, and placed the toastr "holder" div next to the router outlet - i also tried placing the holder div within the router-outlet without luck as well.

The error i get from protractor is:

```<code>    1) Create account page should have a toastr message
  - Failed: NOT VISIBLE
Wait timed out after 10334ms

Executed 28 of 28 specs (1 FAILED) in 18 secs.
[14:01:29] I/launcher - 0 instance(s) of WebDriver still running
[14:01:29] I/launcher - chrome #01 failed 1 test(s)
[14:01:29] I/launcher - overall: 1 failed spec(s)
[14:01:29] E/launcher - Process exited with error code 1
npm ERR! Test failed.  See above for more details.
</code>```

I can provide more information if need be. This was the initial information that i could think of.

Kind regards Chris

答:
I think I found the root cause of this issue.

It turns out Protractor waits for Angular to finish the pending work before continuing, and Toastr schedules a timer to automatically close the message after a few seconds.

So your element finder will only execute after toast removes a message from the page.

To fix this you need to use the browser.driver.findElements method directly (from Selenium WebDriver) instead of using Protractor locators.

That way you can access any element even if Angular has some work left to do in the page.

Body:
I'm using ngx-toastr with my angular 2 application and i've started running some e2e tests against it. I'm having difficulties testing the toastr as it pops up and dissapears after 5 seconds.

I've tried adding several different selection methods as suggested on Stackoverflow, without luck.

What i've tried:

getToastr() {
    var EC = protractor.ExpectedConditions;
    var targetEle = element(by.css(".toast-message"));

    browser.wait(EC.visibilityOf(targetEle), 10000, 'NOT VISIBLE'); //wait until
    //ele visible
    browser.wait(EC.presenceOf(targetEle), 10000, 'NOT PRESENT');
}

which makes it hit the not visible code, eventhough i see the toastr present in the window - it is not able to find it in the dom. I've taken a screenshot of the dom to show you the position as i think it may have something to do with this.

Here's a screenshot of the dom Screenshot of DOM, i'm trying to toast within the start-signup section. Note that the router-outlet named Default does not wrap start-signup, even though it's declared in the router to use this outlet - i don't know if this is by design or not.

{
    path: 'signup',
    children: [
        { path: '', component: StartSignupComponent, outlet: 'default' }
    ]
},

It appears as though the toastr div is not inside the start-signup tag. I haven't been able to move it inside, even with the ngx-toastr's own method to move the toastr message inside a div "of your choosing". Currently i placed it in app.component, and placed the toastr "holder" div next to the router outlet - i also tried placing the holder div within the router-outlet without luck as well.

The error i get from protractor is:

    1) Create account page should have a toastr message
  - Failed: NOT VISIBLE
Wait timed out after 10334ms

Executed 28 of 28 specs (1 FAILED) in 18 secs.
[14:01:29] I/launcher - 0 instance(s) of WebDriver still running
[14:01:29] I/launcher - chrome #01 failed 1 test(s)
[14:01:29] I/launcher - overall: 1 failed spec(s)
[14:01:29] E/launcher - Process exited with error code 1
npm ERR! Test failed.  See above for more details.

I can provide more information if need be. This was the initial information that i could think of.

Kind regards Chris


问:
how to extract the contents of a strong tag using beautiful soup?
```<code> <li class="bg-blue">
 <img alt="Active Status" src="assets/images/icon-infected.png"/>
 <strong>83004</strong>
 <span>Active Cases</span>
</code>```

I need to extract the values inside the strong tag , how should I do that?

答:
With beautifulsoup you can use contents to get that, just like this.

```<code>html_doc = """
<li class="bg-blue">
<img alt="Active Status" src="assets/images/icon-infected.png"/>
<strong>83004</strong>
<span>Active Cases</span>
"""

from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc, 'html.parser')

soup.strong.contents
# 83004
</code>```

Body:
 83004
 Active Cases

I need to extract the values inside the strong tag , how should I do that?

Body:
With beautifulsoup you can use contents to get that, just like this.

html_doc = """
<li class="bg-blue">
<img alt="Active Status" src="assets/images/icon-infected.png"/>
<strong>83004</strong>
<span>Active Cases</span>
"""

from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc, 'html.parser')

soup.strong.contents
# 83004


问:
XMLHttpRequest: Double TCP SYN within a millisecond in Internet Explorer 9
the XMLHttpRequest object causes two TCP SYN Packets when I try to send some POST data.
This happens in less than a millisecond.
I cannot reproduce this behavior in any other browser (tested with the latest Firefox and Google Chrome browser).

Even the 'asynch' Flag or timeout setting does not seem to change the situation.

The Problem is that when IE9 sends two SYN, they will be automatically ackowledged by the Server's TCP/IP Stack. But unfortunately IE9 then sends the Post data in the second stream, which means that the web server is already waiting for bytes on the first socket (causes a timeout).
This happens because we are talking about a single threaded web server that can handle one socket at once.

Any suggestions or ideas?

I would like to prevent IE9 from establishing two sockets at once.

This happens no matter if I use the Jquery ajax function or implement it by myself in java script.

Best Regards

Matthias

答: Just an idea, you could try adding a Connection: close header in all server responses to make sure the browser is starting a new tcp connection for every request.


问:
Caliburn micro Binding Combobox in a listbox
I have this close to what I want to achieve but not quite. I would like to the combobox to display all departments, but only display the department that is bound to the employee. Hopefully someone can see where my error lies. New to WPF and Caliburn.

Here is my models:

```<code>public class Department
{
    public int IdDept { get; set; }
  public string NameDept { get; set; }
}
  public class Employee
{
    public int IdEmployee { get; set; }
    public string NameEmployee { get; set; }
    public int DeptId { get; set; }
}
</code>```

ViewModel:

```<code> public class ShellViewModel : PropertyChangedBase
{
    private BindableCollection<Employee> _employees = new BindableCollection<Employee>();
    private BindableCollection<Department> _departments= new BindableCollection<Department>();
    public BindableCollection<Employee> Employees
    {
        get{return _employees;}
        set
        { _employees = value; NotifyOfPropertyChange(() => Employees);}
    }
    public BindableCollection<Department> Departments
    {
        get{return _departments;}
        set{_departments = value;
            NotifyOfPropertyChange(() => Departments);}
    }

    public ShellViewModel()
    {// simulated data from DB
        Employees.Add(new Employee { IdEmployee = 1, NameEmployee = "Jim", DeptId = 1 });
        Employees.Add(new Employee { IdEmployee = 2, NameEmployee = "Mike", DeptId = 3 });

        Departments.Add(new Department { IdDept = 1, NameDept = "Accounting" });
        Departments.Add(new Department { IdDept = 2, NameDept = "Human Resource" });
        Departments.Add(new Department { IdDept = 2, NameDept = "IT" });
    }
}
</code>```

}

View:

```<code><Grid>
    <ListBox x:Name="Employees" HorizontalAlignment="Left" Height="260" Margin="83,52,0,0" VerticalAlignment="Top" Width="612">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="50"/>
                            <ColumnDefinition Width="50"/>
                            <ColumnDefinition Width="50"/>
                            <ColumnDefinition Width="50"/>
                        </Grid.ColumnDefinitions>
                        <TextBox Text="{Binding NameEmployee}" Grid.Column="1" />
                    <TextBlock Text="{Binding IdEmployee}" Grid.Column="0"/>
                    <ComboBox Grid.Column="2"
                              ItemsSource="{Binding DataContext.Departments,
                        RelativeSource={RelativeSource Mode=FindAncestor,
                        AncestorType={x:Type Window}}}"
                              SelectedValuePath="DeptId"
                              DisplayMemberPath="NameDept"
                              SelectedValue="{Binding IdDept}"/>
                    </Grid>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

</Grid>
</code>```

答:
switch property names in SelectedValuePath and SelectedValue binding:

```<code>SelectedValuePath="IdDept"
SelectedValue="{Binding DeptId}"
</code>```

SelectedValuePath should be a property which exists in ComboBox.ItemsSource elements - thus Department.IdDept

SelectedValue should be a property which exists in ComboBox DataContext (Employee object) - thus Employee.DeptId

Body:
I have this close to what I want to achieve but not quite. I would like to the combobox to display all departments, but only display the department that is bound to the employee. Hopefully someone can see where my error lies. New to WPF and Caliburn.

Here is my models:

public class Department
{
    public int IdDept { get; set; }
  public string NameDept { get; set; }
}
  public class Employee
{
    public int IdEmployee { get; set; }
    public string NameEmployee { get; set; }
    public int DeptId { get; set; }
}

ViewModel:

 public class ShellViewModel : PropertyChangedBase
{
    private BindableCollection<Employee> _employees = new BindableCollection<Employee>();
    private BindableCollection<Department> _departments= new BindableCollection<Department>();
    public BindableCollection<Employee> Employees
    {
        get{return _employees;}
        set
        { _employees = value; NotifyOfPropertyChange(() => Employees);}
    }
    public BindableCollection<Department> Departments
    {
        get{return _departments;}
        set{_departments = value;
            NotifyOfPropertyChange(() => Departments);}
    }

    public ShellViewModel()
    {// simulated data from DB
        Employees.Add(new Employee { IdEmployee = 1, NameEmployee = "Jim", DeptId = 1 });
        Employees.Add(new Employee { IdEmployee = 2, NameEmployee = "Mike", DeptId = 3 });

        Departments.Add(new Department { IdDept = 1, NameDept = "Accounting" });
        Departments.Add(new Department { IdDept = 2, NameDept = "Human Resource" });
        Departments.Add(new Department { IdDept = 2, NameDept = "IT" });
    }
}

}

View:

<Grid>
    <ListBox x:Name="Employees" HorizontalAlignment="Left" Height="260" Margin="83,52,0,0" VerticalAlignment="Top" Width="612">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="50"/>
                            <ColumnDefinition Width="50"/>
                            <ColumnDefinition Width="50"/>
                            <ColumnDefinition Width="50"/>
                        </Grid.ColumnDefinitions>
                        <TextBox Text="{Binding NameEmployee}" Grid.Column="1" />
                    <TextBlock Text="{Binding IdEmployee}" Grid.Column="0"/>
                    <ComboBox Grid.Column="2"
                              ItemsSource="{Binding DataContext.Departments,
                        RelativeSource={RelativeSource Mode=FindAncestor,
                        AncestorType={x:Type Window}}}"
                              SelectedValuePath="DeptId"
                              DisplayMemberPath="NameDept"
                              SelectedValue="{Binding IdDept}"/>
                    </Grid>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

</Grid>

Body:
switch property names in SelectedValuePath and SelectedValue binding:

SelectedValuePath="IdDept"
SelectedValue="{Binding DeptId}"

SelectedValuePath should be a property which exists in ComboBox.ItemsSource elements - thus Department.IdDept

SelectedValue should be a property which exists in ComboBox DataContext (Employee object) - thus Employee.DeptId


问:
Replace method is not working even after reassigning the value to the string in Python
I am trying to replace the values in saopaulo_venues['Venue Category'] for better clustering result but it is not replacing the values in that column.

The code below is the example but there are longer lists of them since there are so many different venues.

I would like to know why this isn't replacing the values.

Thank you in advance.

```<code>for venue in saopaulo_venues.loc[:, 'Venue Category']:
    if venue == 'Gym / Fitness Center':
        venue = venue.replace('Gym / Fitness Center', 'Gym')
        continue
    elif venue == 'Gymnastics Gym':
        venue = venue.replace('Gymnastics Gym', 'Gym')
        continue
    elif venue == 'College Gym':
        venue = venue.replace('College Gym', 'Gym')
        continue
</code>```

答:
How about replace:

```<code>lst = ['Gym / Fitness Center', 'Gymnastics Gym', 'College Gym']
saopaulo_venues['Venue Category'] = saopaulo_venues['Venue Category'].replace(lst, 'Gym')
</code>```

Body:
I am trying to replace the values in saopaulo_venues['Venue Category'] for better clustering result but it is not replacing the values in that column.

The code below is the example but there are longer lists of them since there are so many different venues.

I would like to know why this isn't replacing the values.

Thank you in advance.

for venue in saopaulo_venues.loc[:, 'Venue Category']:
    if venue == 'Gym / Fitness Center':
        venue = venue.replace('Gym / Fitness Center', 'Gym')
        continue
    elif venue == 'Gymnastics Gym':
        venue = venue.replace('Gymnastics Gym', 'Gym')
        continue
    elif venue == 'College Gym':
        venue = venue.replace('College Gym', 'Gym')
        continue

Body:
How about replace:

lst = ['Gym / Fitness Center', 'Gymnastics Gym', 'College Gym']
saopaulo_venues['Venue Category'] = saopaulo_venues['Venue Category'].replace(lst, 'Gym')


问:
Issue regarding resolution of incoming intents by intent filter
Ran into an issue regarding resolution of incoming intents by intent filters & wants to know the exact reason for this behaviour.

I have an activity that has an intent filter as below

```<code> <activity android:name=".deeplink.DeeplinkActivity">
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />

            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />

            <data
                android:host="*"
                android:scheme="dltest" />

        </intent-filter>
    </activity>
</code>```

All was working as expected, that is it did resolve URIs of the format dltest://test1

Then I had to support URL of the format https://www.mine.com/
for which I added a new data tag to same intent filter resulting in

```<code>  <activity android:name=".deeplink.DeeplinkActivity">
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />

            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />

            <data
                android:host="www.mine.com"
                android:scheme="https" />

            <data
                android:host="*"
                android:scheme="dltest" />

        </intent-filter>
    </activity>
</code>```

Now it does handle URIs of both types, but it also handle all intents with scheme as https and host as anything (wild card) that is of the unspecified format for eg: https://developer.android.com

```<code><data
     android:host="*"
     android:scheme="https" />
</code>```

I know that it can be solved by separating two data tags into two different intent filters inside same activity, but I couldn't figure out how the above resolution strategy works from anywhere. Can anyone help me with the reason

答:
Google in one of its official android documentation said that

Although it's possible to include multiple  elements in the same
  filter, it's important that you create separate filters when your
  intention is to declare unique URLs (such as a specific combination of
  scheme and host), because multiple  elements in the same intent
  filter are actually merged together to account for all variations of
  their combined attributes. For example, consider the following:

```<code><intent-filter>
  <data android:scheme="https" android:host="www.example.com" />
  <data android:scheme="app" android:host="open.my.app" />
</intent-filter>
</code>```

It might seem as though this supports only https://www.example.com and app://open.my.app. However, it actually supports those two, plus these: app://www.example.com and https://open.my.app.

So basically as @commonsware said it performs kinda logical OR behind the scenes ...and thus ensures that all combinations are met

Source : Create Deep Links to App Content

Body:
Ran into an issue regarding resolution of incoming intents by intent filters & wants to know the exact reason for this behaviour.

I have an activity that has an intent filter as below

 <activity android:name=".deeplink.DeeplinkActivity">
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />

            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />

            <data
                android:host="*"
                android:scheme="dltest" />

        </intent-filter>
    </activity>

All was working as expected, that is it did resolve URIs of the format dltest://test1

Then I had to support URL of the format https://www.mine.com/
for which I added a new data tag to same intent filter resulting in

  <activity android:name=".deeplink.DeeplinkActivity">
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />

            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />

            <data
                android:host="www.mine.com"
                android:scheme="https" />

            <data
                android:host="*"
                android:scheme="dltest" />

        </intent-filter>
    </activity>

Now it does handle URIs of both types, but it also handle all intents with scheme as https and host as anything (wild card) that is of the unspecified format for eg: https://developer.android.com

<data
     android:host="*"
     android:scheme="https" />

I know that it can be solved by separating two data tags into two different intent filters inside same activity, but I couldn't figure out how the above resolution strategy works from anywhere. Can anyone help me with the reason

Body:
Google in one of its official android documentation said that

Although it's possible to include multiple  elements in the same
  filter, it's important that you create separate filters when your
  intention is to declare unique URLs (such as a specific combination of
  scheme and host), because multiple  elements in the same intent
  filter are actually merged together to account for all variations of
  their combined attributes. For example, consider the following:

<intent-filter>
  <data android:scheme="https" android:host="www.example.com" />
  <data android:scheme="app" android:host="open.my.app" />
</intent-filter>

It might seem as though this supports only https://www.example.com and app://open.my.app. However, it actually supports those two, plus these: app://www.example.com and https://open.my.app.

So basically as @commonsware said it performs kinda logical OR behind the scenes ...and thus ensures that all combinations are met

Source : Create Deep Links to App Content


问:
Find objects in list that match elements in array
Starter code: https://dotnetfiddle.net/lJhMyo

```<code>    string[] names = { "Burke", "Laptop", "Computer",
                       "Mobile", "Ahemed", "Sania",
                       "Kungada", "David","United","Sinshia" };

     var empList =  new List<Employee> {
         new Employee {Name = "Burke", ID = "IHED123"},
         new Employee {Name = "David", ID = "QIUHD454"},
         new Employee {Name = "Batman", ID = "OIWQE565"},
     };

</code>```

How do I construct a linq query (method syntax) that gets all Employee objects where employee name is in the "names" array?

If there is a string in "names" that is not in empList, throw exception.

EDIT: What if empList is large and I want case-insensitive match for Name?

答:
For large lists and case-insensitive comparison you can use HashSet with provided IEqualityComparer<string> :

```<code>var hashSet = new HashSet<string>(names, StringComparer.OrdinalIgnoreCase);
empList.Where(e => hashSet.Contains(e.Name));
</code>```

And possibly moving from LINQ to for loop.

Body:
Starter code: https://dotnetfiddle.net/lJhMyo

    string[] names = { "Burke", "Laptop", "Computer",
                       "Mobile", "Ahemed", "Sania",
                       "Kungada", "David","United","Sinshia" };

     var empList =  new List<Employee> {
         new Employee {Name = "Burke", ID = "IHED123"},
         new Employee {Name = "David", ID = "QIUHD454"},
         new Employee {Name = "Batman", ID = "OIWQE565"},
     };

How do I construct a linq query (method syntax) that gets all Employee objects where employee name is in the "names" array?

If there is a string in "names" that is not in empList, throw exception.

EDIT: What if empList is large and I want case-insensitive match for Name?

Body:
For large lists and case-insensitive comparison you can use HashSet with provided IEqualityComparer<string> :

var hashSet = new HashSet<string>(names, StringComparer.OrdinalIgnoreCase);
empList.Where(e => hashSet.Contains(e.Name));

And possibly moving from LINQ to for loop.


问:
Nestjs / Jestjs : Received: undefined, expected: 1
The project use nestjs and the testing integrated with jestjs.

I try to test the function "getUserByID", which is on my "user.repository.js"

```<code>import { Test } from '@nestjs/testing';
import { UserService } from './user.service';
import { UserRepository } from './user.repository';
import { UserModifyDto } from './dto/user-modify.dto';
import { ConflictException, InternalServerErrorException, NotFoundException, Logger, BadRequestException } from "@nestjs/common";

const mockUser = { id: 1, email: "email@email.com", password: "pass", salt: "XCVBxcf", isAdmin: false, isActive: true, activated: true };

const mockUserRepository = () => ({
    modifyUser: jest.fn(),
    remove: jest.fn(),
    getUserById: jest.fn(),
});

describe('User service', () => {
    let userService;
    let userRepository;

    beforeEach(async () => {
        const module = await Test.createTestingModule({
            providers: [
                UserService,
                { provide: UserRepository, useFactory: mockUserRepository }
            ],
        }).compile();

        userService = await module.get<UserService>(UserService);
        userRepository = await module.get<UserRepository>(UserRepository);
    });

    describe('modifyUser', () => {
        it('modify email', async () => {
            userRepository.modifyUser.mockResolvedValue({ email: "newEmail@email.com" });
            expect(userRepository.modifyUser).not.toHaveBeenCalled();

            const myModifyUser: UserModifyDto = { email: "newEmail@email.com", password: "pass", oldPassword: "pass", isActive: true, activated: true };

            const result = await userService.modifyUser(mockUser, myModifyUser);
            expect(userRepository.modifyUser).toHaveBeenCalled();

            expect(result.email).toEqual(myModifyUser.email);
        });

        it('modify password', async () => {
            userRepository.modifyUser.mockResolvedValue({ password: "newpass" });
            expect(userRepository.modifyUser).not.toHaveBeenCalled();

            const myModifyUser: UserModifyDto = { email: "email@email.com", password: "newpass", oldPassword: "pass", isActive: true, activated: true };

            const result = await userService.modifyUser(mockUser, myModifyUser);
            expect(userRepository.modifyUser).toHaveBeenCalled();

            expect(result.password).toEqual(myModifyUser.password);
        });

        it('modify active', async () => {
            userRepository.modifyUser.mockResolvedValue({ isActive: false });
            expect(userRepository.modifyUser).not.toHaveBeenCalled();

            const myModifyUser: UserModifyDto = { email: "email@email.com", password: "pass", oldPassword: "pass", isActive: false, activated: true };

            const result = await userService.modifyUser(mockUser, myModifyUser);
            expect(userRepository.modifyUser).toHaveBeenCalled();

            expect(result.isActive).toEqual(myModifyUser.isActive);
        });

        it('modify activated', async () => {
            userRepository.modifyUser.mockResolvedValue({ activated: false });
            expect(userRepository.modifyUser).not.toHaveBeenCalled();

            const myModifyUser: UserModifyDto = { email: "email@email.com", password: "pass", oldPassword: "pass", isActive: true, activated: false };

            const result = await userService.modifyUser(mockUser, myModifyUser);
            expect(userRepository.modifyUser).toHaveBeenCalled();

            expect(result.activated).toEqual(myModifyUser.activated);
        });

        it('modify but wrong old password', async () => {
            userRepository.modifyUser.mockImplementation(() => {
                throw new BadRequestException;
            });
        });

        it('modify but save impossible', async () => {
            userRepository.modifyUser.mockImplementation(() => {
                throw new InternalServerErrorException;
            });
        });
    });

    describe('getUserById', () => {
        it ('get a user', async () => {
            //userRepository.findOne.mockResolvedValue(mockUser.id);
            userRepository.getUserById.mockResolvedValue(mockUser.id);
            const result = await userRepository.getUserById(mockUser.id);
            expect(result.id).toEqual(mockUser.id);

        })
    })

    describe('Delete User', () => {
        it('Delete user without error', async () => {
            userRepository.remove.mockResolvedValue({ affected: 1});
            expect(userRepository.remove).not.toHaveBeenCalled();
            await userService.deleteUser(mockUser);
            expect(userRepository.remove).toHaveBeenCalledWith({mockUser})
        })
    })
});
</code>```

setup of my testing file :

```<code>const mockUser = { id: 1, email: "email@email.com", password: "pass", salt: "XCVBxcf", isAdmin: false, isActive: true, activated: true };

const mockUserRepository = () => ({
    modifyUser: jest.fn(),
    remove: jest.fn(),
    getUserById: jest.fn(),
});

describe('User service', () => {
    let userService;
    let userRepository;

    beforeEach(async () => {
        const module = await Test.createTestingModule({
            providers: [
                UserService,
                { provide: UserRepository, useFactory: mockUserRepository }
            ],
        }).compile();

        userService = await module.get<UserService>(UserService);
        userRepository = await module.get<UserRepository>(UserRepository);
    });
</code>```

and this is my test :

```<code>describe('getUserById', () => {
        it ('get a user', async () => {
            const mockUserForGet = {id : 1, email: "mock@email.com"};
            userRepository.getUserById.mockResolvedValue(mockUserForGet.id);
            const result = await userRepository.getUserById(mockUserForGet.id);

            expect(result.id).toEqual(mockUserForGet.id);

        })
    })
</code>```

So my problem is the following, when i run the test, i've got the following result :

expect(received).toEqual(expected)

Expected: 1
  Received: undefined

I don't know why. The function don't throw and the function is mock is the beginning of my testing file.

Thanks for your help !

答:
Finally figured it out. You're mocking the return value as mockUserForGet.id which is a single value, not an object,. Then you are checking that result (a primitive) .id (undefined) is equal to mockUserForGet (an object) .id (a primitive), which makes sense that expect(undefined).toEqual(primitive) returns false and fails the test.

I do want to point out that this test doesn't do anything useful. You are mocking a function's return, calling that function, and asserting that the mock return is what you told the mock to be. It's like you're testing the jest library and not your actual code.

Body:
The project use nestjs and the testing integrated with jestjs.

I try to test the function "getUserByID", which is on my "user.repository.js"

import { Test } from '@nestjs/testing';
import { UserService } from './user.service';
import { UserRepository } from './user.repository';
import { UserModifyDto } from './dto/user-modify.dto';
import { ConflictException, InternalServerErrorException, NotFoundException, Logger, BadRequestException } from "@nestjs/common";

const mockUser = { id: 1, email: "email@email.com", password: "pass", salt: "XCVBxcf", isAdmin: false, isActive: true, activated: true };

const mockUserRepository = () => ({
    modifyUser: jest.fn(),
    remove: jest.fn(),
    getUserById: jest.fn(),
});

describe('User service', () => {
    let userService;
    let userRepository;

    beforeEach(async () => {
        const module = await Test.createTestingModule({
            providers: [
                UserService,
                { provide: UserRepository, useFactory: mockUserRepository }
            ],
        }).compile();

        userService = await module.get<UserService>(UserService);
        userRepository = await module.get<UserRepository>(UserRepository);
    });

    describe('modifyUser', () => {
        it('modify email', async () => {
            userRepository.modifyUser.mockResolvedValue({ email: "newEmail@email.com" });
            expect(userRepository.modifyUser).not.toHaveBeenCalled();

            const myModifyUser: UserModifyDto = { email: "newEmail@email.com", password: "pass", oldPassword: "pass", isActive: true, activated: true };

            const result = await userService.modifyUser(mockUser, myModifyUser);
            expect(userRepository.modifyUser).toHaveBeenCalled();

            expect(result.email).toEqual(myModifyUser.email);
        });

        it('modify password', async () => {
            userRepository.modifyUser.mockResolvedValue({ password: "newpass" });
            expect(userRepository.modifyUser).not.toHaveBeenCalled();

            const myModifyUser: UserModifyDto = { email: "email@email.com", password: "newpass", oldPassword: "pass", isActive: true, activated: true };

            const result = await userService.modifyUser(mockUser, myModifyUser);
            expect(userRepository.modifyUser).toHaveBeenCalled();

            expect(result.password).toEqual(myModifyUser.password);
        });

        it('modify active', async () => {
            userRepository.modifyUser.mockResolvedValue({ isActive: false });
            expect(userRepository.modifyUser).not.toHaveBeenCalled();

            const myModifyUser: UserModifyDto = { email: "email@email.com", password: "pass", oldPassword: "pass", isActive: false, activated: true };

            const result = await userService.modifyUser(mockUser, myModifyUser);
            expect(userRepository.modifyUser).toHaveBeenCalled();

            expect(result.isActive).toEqual(myModifyUser.isActive);
        });

        it('modify activated', async () => {
            userRepository.modifyUser.mockResolvedValue({ activated: false });
            expect(userRepository.modifyUser).not.toHaveBeenCalled();

            const myModifyUser: UserModifyDto = { email: "email@email.com", password: "pass", oldPassword: "pass", isActive: true, activated: false };

            const result = await userService.modifyUser(mockUser, myModifyUser);
            expect(userRepository.modifyUser).toHaveBeenCalled();

            expect(result.activated).toEqual(myModifyUser.activated);
        });

        it('modify but wrong old password', async () => {
            userRepository.modifyUser.mockImplementation(() => {
                throw new BadRequestException;
            });
        });

        it('modify but save impossible', async () => {
            userRepository.modifyUser.mockImplementation(() => {
                throw new InternalServerErrorException;
            });
        });
    });

    describe('getUserById', () => {
        it ('get a user', async () => {
            //userRepository.findOne.mockResolvedValue(mockUser.id);
            userRepository.getUserById.mockResolvedValue(mockUser.id);
            const result = await userRepository.getUserById(mockUser.id);
            expect(result.id).toEqual(mockUser.id);

        })
    })

    describe('Delete User', () => {
        it('Delete user without error', async () => {
            userRepository.remove.mockResolvedValue({ affected: 1});
            expect(userRepository.remove).not.toHaveBeenCalled();
            await userService.deleteUser(mockUser);
            expect(userRepository.remove).toHaveBeenCalledWith({mockUser})
        })
    })
});

setup of my testing file :

const mockUser = { id: 1, email: "email@email.com", password: "pass", salt: "XCVBxcf", isAdmin: false, isActive: true, activated: true };

const mockUserRepository = () => ({
    modifyUser: jest.fn(),
    remove: jest.fn(),
    getUserById: jest.fn(),
});

describe('User service', () => {
    let userService;
    let userRepository;

    beforeEach(async () => {
        const module = await Test.createTestingModule({
            providers: [
                UserService,
                { provide: UserRepository, useFactory: mockUserRepository }
            ],
        }).compile();

        userService = await module.get<UserService>(UserService);
        userRepository = await module.get<UserRepository>(UserRepository);
    });

and this is my test :

describe('getUserById', () => {
        it ('get a user', async () => {
            const mockUserForGet = {id : 1, email: "mock@email.com"};
            userRepository.getUserById.mockResolvedValue(mockUserForGet.id);
            const result = await userRepository.getUserById(mockUserForGet.id);

            expect(result.id).toEqual(mockUserForGet.id);

        })
    })

So my problem is the following, when i run the test, i've got the following result :

expect(received).toEqual(expected)

Expected: 1
  Received: undefined

I don't know why. The function don't throw and the function is mock is the beginning of my testing file.

Thanks for your help !


问:
Is it safe to turn on Delayed Durability on a transaction replication subscriber?
In a transaction replication environment with a publisher SQL Server that receives frequent inserts and updates from an application and a subscriber SQL Server with pull replication jobs, is it safe to enable delayed durability on the subscriber?

Microsoft says that delayed durability is not supported for transaction replication, but was unclear if this was in regards to any server involved in the replication, or just the publisher.

While there is always risk in turning on delayed durability, is there any added risk in turning it on for a replication subscriber? If it is unsupported or there are added risks, is there a way to reduce the WRITELOG waits on the subscriber? The subscriber is a reporting server and its number one wait is always WRITELOG due to the frequent inserts and updates occurring on the publisher from the application (45.3 hours of WRITELOG wait in 345.1 hours of uptime).

答:
First off who cares?  The WRITELOG waits are suffered by the Distribution Agent, not the users.

Second, have you considered the normal performance optimizations for replication, ie Enhance Transactional Replication Performance, in particular Subscription Streams?

The –SubscriptionStreams parameter can greatly improve aggregate
  replication throughput. It allows multiple connections to a Subscriber
  to apply batches of changes in parallel, while maintaining many of the
  transactional characteristics present when using a single thread. If
  one of the connections fails to execute or commit, all connections
  will abort the current batch, and the agent will use a single stream
  to retry the failed batches. Before this retry phase completes, there
  can be temporary transactional inconsistencies at the Subscriber.
  After the failed batches are successfully committed, the Subscriber is
  brought back to a state of transactional consistency.

Writing to the subscriber in parallel will improve replication throughput and should reduce the aggregate WRITELOG waits as concurrent transactions can caravan on the each log file IO.

It's certainly unsupported, as the Distributer would not know the correct state of the Subscriber after a failure.  So after an unplanned shutdown, you'd have missing data, and you wouldn't have any other indication.  You'd basically have to reinitialize the subscriber after any failure.


问:
How to create a calculated column in access 2013 to detect duplicates
I'm recreating a tool I made in Excel as it's getting bigger and performance is getting out of hand.

The issue is that I only have MS Access 2013 on my work laptop and I'm fairly new to the Expression Builder in Access 2013, which has a very limited function base to be honest.

My data has duplicates on the [Location] column, meaning that, I have multiple SKUs on that warehouse location. However, some of my calculations need to be done only once per [Location]. My solution to that, in Excel, was to make a formula (see below) putting 1 only on the first appearance of that location, putting 0 on next appearances. Doing that works like a charm because summing over that [Duplicate] column while imposing multiple criteria returns the number of occurrences of the multiple criteria counting locations only once.

Now, MS Access 2013 Expression Builder has no SUM nor COUNT functions to create a calculated column emulating my [Duplicate] column from Excel. Preferably, I would just input the raw data and let Access populate the calculated fields vs also inputting the calculated fields as well, since that would defeat my original purpose of reducing the computational cost of creating my dashboard.

The question is, how would you create a calculated column, in MS Access 2013 Expression Builder to recreate the below Excel function:

= IF($D$2:$D3=$D4,0,1)

In the sake of reducing the file size (over 100K rows) I even replace the 0 by a blank character "".

Thanks in advance for your help

Y

答:
First and foremost, understand MS Access' Expression Builder is a convenience tool to build an SQL expression. Everything in Query Design ultimately is to build an SQL query. For this reason, you have to use a set-based mentality to see data in whole sets of related tables and not cell-by-cell mindset.

Specifically, to achieve:

putting 1 only on the first appearance of that location, putting 0 on next appearances

Consider a whole set-based approach by joining on a separate, aggregate query to identify the first value of your needed grouping, then calculate needed IIF expression. Below assumes you have an autonumber or primary key field in table (a standard in relational databases):

Aggregate Query (save as a separate query, adjust columns as needed)

SELECT ColumnD, MIN(AutoNumberID) As MinID
FROM myTable
GROUP BY ColumnD
```

<p>Final Query <em>(join to original table and build final <code>IIF</code> expression)</em></p>

<pre class="lang-sql prettyprint-override"><code>SELECT m.*, IIF(agg.MinID = AutoNumberID, 1, 0) As Dup_Indicator
FROM myTable m
INNER JOIN myAggregateQuery agg
   ON m.[ColumnD] = agg.ColumnD
</code>```

To demonstrate with random data:

Original

```<code>| ID | GROUP  | INT | NUM          | CHAR | BOOL  | DATE       |
|----|--------|-----|--------------|------|-------|------------|
| 1  | r      | 9   | 1.424490258  | B6z  | TRUE  | 7/4/1994   |
| 2  | stata  | 10  | 2.591235683  | h7J  | FALSE | 10/5/1971  |
| 3  | spss   | 6   | 0.560461966  | Hrn  | TRUE  | 11/27/1990 |
| 4  | stata  | 10  | -1.499272175 | eXL  | FALSE | 4/17/2010  |
| 5  | stata  | 15  | 1.470269177  | Vas  | TRUE  | 6/13/2010  |
| 6  | r      | 14  | -0.072238898 | puP  | TRUE  | 4/1/1994   |
| 7  | julia  | 2   | -1.370405263 | S2l  | FALSE | 12/11/1999 |
| 8  | spss   | 6   | -0.153684675 | mAw  | FALSE | 7/28/1977  |
| 9  | spss   | 10  | -0.861482674 | cxC  | FALSE | 7/17/1994  |
| 10 | spss   | 2   | -0.817222582 | GRn  | FALSE | 10/19/2012 |
| 11 | stata  | 2   | 0.949287754  | xgc  | TRUE  | 1/18/2003  |
| 12 | stata  | 5   | -1.580841322 | Y1D  | TRUE  | 6/3/2011   |
| 13 | r      | 14  | -1.671303816 | JCP  | FALSE | 5/15/1981  |
| 14 | r      | 7   | 0.904181025  | Rct  | TRUE  | 7/24/1977  |
| 15 | stata  | 10  | -1.198211174 | qJY  | FALSE | 5/6/1982   |
| 16 | julia  | 10  | -0.265808162 | 10s  | FALSE | 3/18/1975  |
| 17 | r      | 13  | -0.264955027 | 8Md  | TRUE  | 6/11/1974  |
| 18 | r      | 4   | 0.518302149  | 4KW  | FALSE | 9/12/1980  |
| 19 | r      | 5   | -0.053620183 | 8An  | FALSE | 4/17/2004  |
| 20 | r      | 14  | -0.359197116 | F8Q  | TRUE  | 6/14/2005  |
| 21 | spss   | 11  | -2.211875193 | AgS  | TRUE  | 4/11/1973  |
| 22 | stata  | 4   | -1.718749471 | Zqr  | FALSE | 2/20/1999  |
| 23 | python | 10  | 1.207878576  | tcC  | FALSE | 4/18/2008  |
| 24 | stata  | 11  | 0.548902226  | PFJ  | TRUE  | 9/20/1994  |
| 25 | stata  | 6   | 1.479125922  | 7a7  | FALSE | 3/2/1989   |
| 26 | python | 10  | -0.437245299 | r32  | TRUE  | 6/7/1997   |
| 27 | sas    | 14  | 0.404746106  | 6NJ  | TRUE  | 9/23/2013  |
| 28 | stata  | 8   | 2.206741458  | Ive  | TRUE  | 5/26/2008  |
| 29 | spss   | 12  | -0.470694096 | dPS  | TRUE  | 5/4/1983   |
| 30 | sas    | 15  | -0.57169507  | yle  | TRUE  | 6/20/1979  |
</code>```

SQL (uses aggregate in subquery but can be a stored query)

SELECT r.*, IIF(sub.MinID = r.ID,1, 0) AS Dup
FROM Random_Data r
LEFT JOIN
   (
      SELECT r.GROUP, MIN(r.ID) As MinID
      FROM Random_Data r
      GROUP BY r.Group
   )  sub

ON r.[Group] = sub.[GROUP]
```

<p><strong>Output</strong> <em>(notice the first <code>GROUP</code> value is tagged 1, all else 0)</em></p>

```| ID | GROUP  | INT | NUM          | CHAR | BOOL  | DATE       | Dup |
|----|--------|-----|--------------|------|-------|------------|-----|
| 1  | r      | 9   | 1.424490258  | B6z  | TRUE  | 7/4/1994   | 1   |
| 2  | stata  | 10  | 2.591235683  | h7J  | FALSE | 10/5/1971  | 1   |
| 3  | spss   | 6   | 0.560461966  | Hrn  | TRUE  | 11/27/1990 | 1   |
| 4  | stata  | 10  | -1.499272175 | eXL  | FALSE | 4/17/2010  | 0   |
| 5  | stata  | 15  | 1.470269177  | Vas  | TRUE  | 6/13/2010  | 0   |
| 6  | r      | 14  | -0.072238898 | puP  | TRUE  | 4/1/1994   | 0   |
| 7  | julia  | 2   | -1.370405263 | S2l  | FALSE | 12/11/1999 | 1   |
| 8  | spss   | 6   | -0.153684675 | mAw  | FALSE | 7/28/1977  | 0   |
| 9  | spss   | 10  | -0.861482674 | cxC  | FALSE | 7/17/1994  | 0   |
| 10 | spss   | 2   | -0.817222582 | GRn  | FALSE | 10/19/2012 | 0   |
| 11 | stata  | 2   | 0.949287754  | xgc  | TRUE  | 1/18/2003  | 0   |
| 12 | stata  | 5   | -1.580841322 | Y1D  | TRUE  | 6/3/2011   | 0   |
| 13 | r      | 14  | -1.671303816 | JCP  | FALSE | 5/15/1981  | 0   |
| 14 | r      | 7   | 0.904181025  | Rct  | TRUE  | 7/24/1977  | 0   |
| 15 | stata  | 10  | -1.198211174 | qJY  | FALSE | 5/6/1982   | 0   |
| 16 | julia  | 10  | -0.265808162 | 10s  | FALSE | 3/18/1975  | 0   |
| 17 | r      | 13  | -0.264955027 | 8Md  | TRUE  | 6/11/1974  | 0   |
| 18 | r      | 4   | 0.518302149  | 4KW  | FALSE | 9/12/1980  | 0   |
| 19 | r      | 5   | -0.053620183 | 8An  | FALSE | 4/17/2004  | 0   |
| 20 | r      | 14  | -0.359197116 | F8Q  | TRUE  | 6/14/2005  | 0   |
| 21 | spss   | 11  | -2.211875193 | AgS  | TRUE  | 4/11/1973  | 0   |
| 22 | stata  | 4   | -1.718749471 | Zqr  | FALSE | 2/20/1999  | 0   |
| 23 | python | 10  | 1.207878576  | tcC  | FALSE | 4/18/2008  | 1   |
| 24 | stata  | 11  | 0.548902226  | PFJ  | TRUE  | 9/20/1994  | 0   |
| 25 | stata  | 6   | 1.479125922  | 7a7  | FALSE | 3/2/1989   | 0   |
| 26 | python | 10  | -0.437245299 | r32  | TRUE  | 6/7/1997   | 0   |
| 27 | sas    | 14  | 0.404746106  | 6NJ  | TRUE  | 9/23/2013  | 1   |
| 28 | stata  | 8   | 2.206741458  | Ive  | TRUE  | 5/26/2008  | 0   |
| 29 | spss   | 12  | -0.470694096 | dPS  | TRUE  | 5/4/1983   | 0   |
| 30 | sas    | 15  | -0.57169507  | yle  | TRUE  | 6/20/1979  | 0   |
```

Body:
First and foremost, understand MS Access' Expression Builder is a convenience tool to build an SQL expression. Everything in Query Design ultimately is to build an SQL query. For this reason, you have to use a set-based mentality to see data in whole sets of related tables and not cell-by-cell mindset.

Specifically, to achieve:

putting 1 only on the first appearance of that location, putting 0 on next appearances

Consider a whole set-based approach by joining on a separate, aggregate query to identify the first value of your needed grouping, then calculate needed IIF expression. Below assumes you have an autonumber or primary key field in table (a standard in relational databases):

Aggregate Query (save as a separate query, adjust columns as needed)

SELECT ColumnD, MIN(AutoNumberID) As MinID
FROM myTable
GROUP BY ColumnD

Final Query (join to original table and build final IIF expression)

SELECT m.*, IIF(agg.MinID = AutoNumberID, 1, 0) As Dup_Indicator
FROM myTable m
INNER JOIN myAggregateQuery agg
   ON m.[ColumnD] = agg.ColumnD

To demonstrate with random data:

Original

| ID | GROUP  | INT | NUM          | CHAR | BOOL  | DATE       |
|----|--------|-----|--------------|------|-------|------------|
| 1  | r      | 9   | 1.424490258  | B6z  | TRUE  | 7/4/1994   |
| 2  | stata  | 10  | 2.591235683  | h7J  | FALSE | 10/5/1971  |
| 3  | spss   | 6   | 0.560461966  | Hrn  | TRUE  | 11/27/1990 |
| 4  | stata  | 10  | -1.499272175 | eXL  | FALSE | 4/17/2010  |
| 5  | stata  | 15  | 1.470269177  | Vas  | TRUE  | 6/13/2010  |
| 6  | r      | 14  | -0.072238898 | puP  | TRUE  | 4/1/1994   |
| 7  | julia  | 2   | -1.370405263 | S2l  | FALSE | 12/11/1999 |
| 8  | spss   | 6   | -0.153684675 | mAw  | FALSE | 7/28/1977  |
| 9  | spss   | 10  | -0.861482674 | cxC  | FALSE | 7/17/1994  |
| 10 | spss   | 2   | -0.817222582 | GRn  | FALSE | 10/19/2012 |
| 11 | stata  | 2   | 0.949287754  | xgc  | TRUE  | 1/18/2003  |
| 12 | stata  | 5   | -1.580841322 | Y1D  | TRUE  | 6/3/2011   |
| 13 | r      | 14  | -1.671303816 | JCP  | FALSE | 5/15/1981  |
| 14 | r      | 7   | 0.904181025  | Rct  | TRUE  | 7/24/1977  |
| 15 | stata  | 10  | -1.198211174 | qJY  | FALSE | 5/6/1982   |
| 16 | julia  | 10  | -0.265808162 | 10s  | FALSE | 3/18/1975  |
| 17 | r      | 13  | -0.264955027 | 8Md  | TRUE  | 6/11/1974  |
| 18 | r      | 4   | 0.518302149  | 4KW  | FALSE | 9/12/1980  |
| 19 | r      | 5   | -0.053620183 | 8An  | FALSE | 4/17/2004  |
| 20 | r      | 14  | -0.359197116 | F8Q  | TRUE  | 6/14/2005  |
| 21 | spss   | 11  | -2.211875193 | AgS  | TRUE  | 4/11/1973  |
| 22 | stata  | 4   | -1.718749471 | Zqr  | FALSE | 2/20/1999  |
| 23 | python | 10  | 1.207878576  | tcC  | FALSE | 4/18/2008  |
| 24 | stata  | 11  | 0.548902226  | PFJ  | TRUE  | 9/20/1994  |
| 25 | stata  | 6   | 1.479125922  | 7a7  | FALSE | 3/2/1989   |
| 26 | python | 10  | -0.437245299 | r32  | TRUE  | 6/7/1997   |
| 27 | sas    | 14  | 0.404746106  | 6NJ  | TRUE  | 9/23/2013  |
| 28 | stata  | 8   | 2.206741458  | Ive  | TRUE  | 5/26/2008  |
| 29 | spss   | 12  | -0.470694096 | dPS  | TRUE  | 5/4/1983   |
| 30 | sas    | 15  | -0.57169507  | yle  | TRUE  | 6/20/1979  |

SQL (uses aggregate in subquery but can be a stored query)

SELECT r.*, IIF(sub.MinID = r.ID,1, 0) AS Dup
FROM Random_Data r
LEFT JOIN
   (
      SELECT r.GROUP, MIN(r.ID) As MinID
      FROM Random_Data r
      GROUP BY r.Group
   )  sub

ON r.[Group] = sub.[GROUP]

Output (notice the first GROUP value is tagged 1, all else 0)

| ID | GROUP  | INT | NUM          | CHAR | BOOL  | DATE       | Dup |
|----|--------|-----|--------------|------|-------|------------|-----|
| 1  | r      | 9   | 1.424490258  | B6z  | TRUE  | 7/4/1994   | 1   |
| 2  | stata  | 10  | 2.591235683  | h7J  | FALSE | 10/5/1971  | 1   |
| 3  | spss   | 6   | 0.560461966  | Hrn  | TRUE  | 11/27/1990 | 1   |
| 4  | stata  | 10  | -1.499272175 | eXL  | FALSE | 4/17/2010  | 0   |
| 5  | stata  | 15  | 1.470269177  | Vas  | TRUE  | 6/13/2010  | 0   |
| 6  | r      | 14  | -0.072238898 | puP  | TRUE  | 4/1/1994   | 0   |
| 7  | julia  | 2   | -1.370405263 | S2l  | FALSE | 12/11/1999 | 1   |
| 8  | spss   | 6   | -0.153684675 | mAw  | FALSE | 7/28/1977  | 0   |
| 9  | spss   | 10  | -0.861482674 | cxC  | FALSE | 7/17/1994  | 0   |
| 10 | spss   | 2   | -0.817222582 | GRn  | FALSE | 10/19/2012 | 0   |
| 11 | stata  | 2   | 0.949287754  | xgc  | TRUE  | 1/18/2003  | 0   |
| 12 | stata  | 5   | -1.580841322 | Y1D  | TRUE  | 6/3/2011   | 0   |
| 13 | r      | 14  | -1.671303816 | JCP  | FALSE | 5/15/1981  | 0   |
| 14 | r      | 7   | 0.904181025  | Rct  | TRUE  | 7/24/1977  | 0   |
| 15 | stata  | 10  | -1.198211174 | qJY  | FALSE | 5/6/1982   | 0   |
| 16 | julia  | 10  | -0.265808162 | 10s  | FALSE | 3/18/1975  | 0   |
| 17 | r      | 13  | -0.264955027 | 8Md  | TRUE  | 6/11/1974  | 0   |
| 18 | r      | 4   | 0.518302149  | 4KW  | FALSE | 9/12/1980  | 0   |
| 19 | r      | 5   | -0.053620183 | 8An  | FALSE | 4/17/2004  | 0   |
| 20 | r      | 14  | -0.359197116 | F8Q  | TRUE  | 6/14/2005  | 0   |
| 21 | spss   | 11  | -2.211875193 | AgS  | TRUE  | 4/11/1973  | 0   |
| 22 | stata  | 4   | -1.718749471 | Zqr  | FALSE | 2/20/1999  | 0   |
| 23 | python | 10  | 1.207878576  | tcC  | FALSE | 4/18/2008  | 1   |
| 24 | stata  | 11  | 0.548902226  | PFJ  | TRUE  | 9/20/1994  | 0   |
| 25 | stata  | 6   | 1.479125922  | 7a7  | FALSE | 3/2/1989   | 0   |
| 26 | python | 10  | -0.437245299 | r32  | TRUE  | 6/7/1997   | 0   |
| 27 | sas    | 14  | 0.404746106  | 6NJ  | TRUE  | 9/23/2013  | 1   |
| 28 | stata  | 8   | 2.206741458  | Ive  | TRUE  | 5/26/2008  | 0   |
| 29 | spss   | 12  | -0.470694096 | dPS  | TRUE  | 5/4/1983   | 0   |
| 30 | sas    | 15  | -0.57169507  | yle  | TRUE  | 6/20/1979  | 0   |