问:
Jetpack Compose: Keyboard input doesn't seem to work on physical Wear OS device
I'm working on a Baybayin (it's an ancient Filipino writing script) keyboard for our app and it's developed in Wear OS using Jetpack Compose. I tried the code here: https://stackoverflow.com/a/70294785/16028653. It works perfectly as intended on my virtual device and I was able to output Baybayin characters using a special font style for it. However, when I tried using it on my Samsung Galaxy Watch 4, it crashes after I input the text on the keyboard.

The error says android.text.SpannableString cannot be cast to java.lang.String, caused by this code:

```<code>rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) {
it.data?.let { data -\>
val results: Bundle = RemoteInput.getResultsFromIntent(data)
val ipAddress: CharSequence? = results.getCharSequence("ip_address")
label.value = ipAddress as String
}
</code>```

Here's the whole code:

```<code>@Composable
fun Keyboard(){
    val contentModifier = Modifier
        .padding(top = 17.dp)
        .fillMaxWidth()
        .wrapContentSize(align = Alignment.Center)
    val label = remember { mutableStateOf("Start")}
    val launcher =
        rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            it.data?.let { data ->
                val results: Bundle = RemoteInput.getResultsFromIntent(data)
                val ipAddress: CharSequence? = results.getCharSequence("ip_address")
                label.value = ipAddress as String
            }
        }
    Column() {
        Spacer(modifier = Modifier.height(20.dp))
        Chip(
            label = { Text(label.value, style = MaterialTheme.typography.body2)}, //baybayin font style
            onClick = {}
        )
        Chip(
            label = { Text("Search with specific IP") },
            onClick = {
                val intent: Intent = RemoteInputIntentHelper.createActionRemoteInputIntent();
                val remoteInputs: List<RemoteInput> = listOf(
                    RemoteInput.Builder("ip_address")
                        .setLabel("Manual IP Entry")
                        .wearableExtender {
                            setEmojisAllowed(false)
                            setInputActionType(EditorInfo.IME_ACTION_DONE)
                        }.build()
                )

                RemoteInputIntentHelper.putRemoteInputsExtra(intent, remoteInputs)

                launcher.launch(intent)
            }
        )
    }
}
</code>```

I'm sure that the chip's label accepts string. I'm not sure where it became a spannable string. label.value expects it to be a string and I can't convert it to spannable. I also tried using Gboard with no success.

And here's the stack trace:

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.twentytwoitten.ibaybay, PID: 16539
    java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=788413898, result=-1, data=Intent { clip={text/vnd.android.intent {...}} (has extras) }} to activity {com.twentytwoitten.ibaybay/modules.MainActivity}: java.lang.ClassCastException: android.text.SpannableString cannot be cast to java.lang.String
        at android.app.ActivityThread.deliverResults(ActivityThread.java:5051)
        at android.app.ActivityThread.handleSendResult(ActivityThread.java:5092)
        at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2073)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:246)
        at android.app.ActivityThread.main(ActivityThread.java:7690)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:593)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:995)
     Caused by: java.lang.ClassCastException: android.text.SpannableString cannot be cast to java.lang.String
        at com.twentytwoitten.ibaybay.modules.KeebKt$Keyboard$launcher$1$1.invoke(keeb.kt:47)
        at com.twentytwoitten.ibaybay.modules.KeebKt$Keyboard$launcher$1$1.invoke(keeb.kt:43)
        at androidx.activity.compose.ActivityResultRegistryKt$rememberLauncherForActivityResult$1$1.onActivityResult(ActivityResultRegistry.kt:105)
        at androidx.activity.result.ActivityResultRegistry.doDispatch(ActivityResultRegistry.java:392)
        at androidx.activity.result.ActivityResultRegistry.dispatchResult(ActivityResultRegistry.java:351)
        at androidx.activity.ComponentActivity.onActivityResult(ComponentActivity.java:638)
        at android.app.Activity.dispatchActivityResult(Activity.java:8364)
        at android.app.ActivityThread.deliverResults(ActivityThread.java:5044)
        at android.app.ActivityThread.handleSendResult(ActivityThread.java:5092)
        at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2073)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:246)
        at android.app.ActivityThread.main(ActivityThread.java:7690)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:593)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:995)
I/Process: Sending signal. PID: 16539 SIG: 9
</code>```

I hope somebody can help me on this. I'm very close on to making this work. I'm also fairly new in using Jetpack Compose. I appreciate your help. Thanks.

Body:
I'm working on a Baybayin (it's an ancient Filipino writing script) keyboard for our app and it's developed in Wear OS using Jetpack Compose. I tried the code here: https://stackoverflow.com/a/70294785/16028653. It works perfectly as intended on my virtual device and I was able to output Baybayin characters using a special font style for it. However, when I tried using it on my Samsung Galaxy Watch 4, it crashes after I input the text on the keyboard.

The error says android.text.SpannableString cannot be cast to java.lang.String, caused by this code:

rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) {
it.data?.let { data -\>
val results: Bundle = RemoteInput.getResultsFromIntent(data)
val ipAddress: CharSequence? = results.getCharSequence("ip_address")
label.value = ipAddress as String
}

Here's the whole code:

@Composable
fun Keyboard(){
    val contentModifier = Modifier
        .padding(top = 17.dp)
        .fillMaxWidth()
        .wrapContentSize(align = Alignment.Center)
    val label = remember { mutableStateOf("Start")}
    val launcher =
        rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            it.data?.let { data ->
                val results: Bundle = RemoteInput.getResultsFromIntent(data)
                val ipAddress: CharSequence? = results.getCharSequence("ip_address")
                label.value = ipAddress as String
            }
        }
    Column() {
        Spacer(modifier = Modifier.height(20.dp))
        Chip(
            label = { Text(label.value, style = MaterialTheme.typography.body2)}, //baybayin font style
            onClick = {}
        )
        Chip(
            label = { Text("Search with specific IP") },
            onClick = {
                val intent: Intent = RemoteInputIntentHelper.createActionRemoteInputIntent();
                val remoteInputs: List<RemoteInput> = listOf(
                    RemoteInput.Builder("ip_address")
                        .setLabel("Manual IP Entry")
                        .wearableExtender {
                            setEmojisAllowed(false)
                            setInputActionType(EditorInfo.IME_ACTION_DONE)
                        }.build()
                )

                RemoteInputIntentHelper.putRemoteInputsExtra(intent, remoteInputs)

                launcher.launch(intent)
            }
        )
    }
}

I'm sure that the chip's label accepts string. I'm not sure where it became a spannable string. label.value expects it to be a string and I can't convert it to spannable. I also tried using Gboard with no success.

And here's the stack trace:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.twentytwoitten.ibaybay, PID: 16539
    java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=788413898, result=-1, data=Intent { clip={text/vnd.android.intent {...}} (has extras) }} to activity {com.twentytwoitten.ibaybay/modules.MainActivity}: java.lang.ClassCastException: android.text.SpannableString cannot be cast to java.lang.String
        at android.app.ActivityThread.deliverResults(ActivityThread.java:5051)
        at android.app.ActivityThread.handleSendResult(ActivityThread.java:5092)
        at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2073)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:246)
        at android.app.ActivityThread.main(ActivityThread.java:7690)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:593)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:995)
     Caused by: java.lang.ClassCastException: android.text.SpannableString cannot be cast to java.lang.String
        at com.twentytwoitten.ibaybay.modules.KeebKt$Keyboard$launcher$1$1.invoke(keeb.kt:47)
        at com.twentytwoitten.ibaybay.modules.KeebKt$Keyboard$launcher$1$1.invoke(keeb.kt:43)
        at androidx.activity.compose.ActivityResultRegistryKt$rememberLauncherForActivityResult$1$1.onActivityResult(ActivityResultRegistry.kt:105)
        at androidx.activity.result.ActivityResultRegistry.doDispatch(ActivityResultRegistry.java:392)
        at androidx.activity.result.ActivityResultRegistry.dispatchResult(ActivityResultRegistry.java:351)
        at androidx.activity.ComponentActivity.onActivityResult(ComponentActivity.java:638)
        at android.app.Activity.dispatchActivityResult(Activity.java:8364)
        at android.app.ActivityThread.deliverResults(ActivityThread.java:5044)
        at android.app.ActivityThread.handleSendResult(ActivityThread.java:5092)
        at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2073)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:246)
        at android.app.ActivityThread.main(ActivityThread.java:7690)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:593)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:995)
I/Process: Sending signal. PID: 16539 SIG: 9

I hope somebody can help me on this. I'm very close on to making this work. I'm also fairly new in using Jetpack Compose. I appreciate your help. Thanks.


来源: stackexchange

问:
OAuth, Scraping data - How to calculate device_id & device_token?
I'm trying to scrape olx.pl website. I want to get a phone number from advert. Example advert is here: https://www.olx.pl/d/oferta/mieszkanie-pokoj-do-wynajecia-CID3-IDG2hIu.html

You need to click: Zadzwoń / SMS to check phone number.

As you can see, the phone number is generate in two steps.

First is making request to: https://www.olx.pl/api/open/oauth/token/

This is POST request. Post params which is needed to make this request:

client_id - this is into HTML source (CTRL+U in your browser)

client_secret - this is into HTML source (CTRL+U in your browser)

grant_type => 'device' (always the same value)

scope => 'i2 read write v2' (always the same value)

device_id - this param I need to calculate, but I don't know how

device_token - this param I need to calculate, but I don't know how

Second step is making POST request for: https://www.olx.pl/api/v1/offers/621150874/limited-phones/

Here is using everything from FIRST STEP.

My question is: How I can calculate device_id and device_token for first request? Into HTML source these params not exist.

ContentLicense: CC BY-SA 4.0


问:
VBA Runtime Error 1004 "Application-defined or Object-defined error" when using Range method
```<code>Option Explicit
Sub CopyNPaste()

Dim Columncount_s1 As Long
Dim Columncount As Long
Dim i As Long, j As Long, K As Long
Dim Sheetcount As Long
Dim LastRow_s1 As Long, LastRow As Long

Columncount_s1 = Sheets(1).Cells(1, Columns.Count).End(xlToLeft).Column
Sheetcount = ActiveWorkbook.Sheets.Count
For i = 2 To Sheetcount
    Columncount = Sheets(i).Cells(1, Columns.Count).End(xlToLeft).Column
    For j = 1 To Columncount_s1
        For K = 1 To Columncount
            If Sheets(1).Cells(1, j) = Sheets(i).Cells(1, K) Then
                LastRow_s1 = Sheets(1).Cells(Rows.Count, j).End(3)(2).Row
                LastRow = Sheets(i).Cells(Rows.Count, K).End(3)(2).Row
                Sheets(i).Range(Cells(2, K), Cells(LastRow, K)).Copy
                Sheets(1).Cells(LastRow, j).PasteSpecial xlPasteValues
            End If
        Next K
    Next j
Next i

End Sub

</code>```

I tried to make a code to copy and paste to the right column in vba. But the Sheets(i).Range(Cells(2,K... this line keep causing error. Is that because I used too many of variables to the parameter of method Range?

The purpose of the code was to consolidate the data by copying and pasting columns that have the same header from a different sheet.

Body:
Option Explicit
Sub CopyNPaste()

Dim Columncount_s1 As Long
Dim Columncount As Long
Dim i As Long, j As Long, K As Long
Dim Sheetcount As Long
Dim LastRow_s1 As Long, LastRow As Long

Columncount_s1 = Sheets(1).Cells(1, Columns.Count).End(xlToLeft).Column
Sheetcount = ActiveWorkbook.Sheets.Count
For i = 2 To Sheetcount
    Columncount = Sheets(i).Cells(1, Columns.Count).End(xlToLeft).Column
    For j = 1 To Columncount_s1
        For K = 1 To Columncount
            If Sheets(1).Cells(1, j) = Sheets(i).Cells(1, K) Then
                LastRow_s1 = Sheets(1).Cells(Rows.Count, j).End(3)(2).Row
                LastRow = Sheets(i).Cells(Rows.Count, K).End(3)(2).Row
                Sheets(i).Range(Cells(2, K), Cells(LastRow, K)).Copy
                Sheets(1).Cells(LastRow, j).PasteSpecial xlPasteValues
            End If
        Next K
    Next j
Next i

End Sub

I tried to make a code to copy and paste to the right column in vba. But the Sheets(i).Range(Cells(2,K... this line keep causing error. Is that because I used too many of variables to the parameter of method Range?

The purpose of the code was to consolidate the data by copying and pasting columns that have the same header from a different sheet.


问:
How can i link a custom library with Cmake?
im new in Cmake, im trying to link a library to a project using Cmake, the following code is this:

code of the header:

my_library.h

```<code>    #ifndef MY_LIBRARY
    #define MY_LIBRARY

    int get_random_number();

    #endif
</code>```

implementation of the header:
my_library.cpp

```<code>    #include "my_library.h"

    int get_random_number(){

            return 46;
    }

</code>```

Configuration of Cmake

CmakeLists.txt

```<code>    cmake_minimum_required(VERSION 3.8)

    file(GLOB_RECURSE SOURCES LIST_DIRECTORIES true *.h *.cpp)

    set(SOURCES ${SOURCES})

    add_library(my_library SHARED ${SOURCES})

    target_include_directories(my_library PUBLIC ${CMAKE_CURRENT_LIST_DIR})
</code>```

outside the folder i have this:

main.cpp

```<code>#include <iostream>
#include "my_library.h"
</code>```
```<code>    int main(){

            std::cout<<"Hello, jairo"<<std::endl;
            std::cout<<"A random number is: "<<get_random_number()<<std::endl;

            return 0;

    }

</code>```

CmakeListst.txt

```<code>    cmake_minimum_required(VERSION 3.20)

    project(Hello CXX)

    add_subdirectory(my_library)

    add_executable(${PROJECT_NAME} main.cpp)

    target_link_libraries(${PROJECT_NAME} PUBLIC my_library)
</code>```

the structure of the whole project is this:

all goes well until y try to execute the Hello.exe file that is generated, windows gives an error saying "Code execution cannot continue because libmy_library.dll was not found" which i undestand as CMake is not linking correctly the library

the structure of the project is this

main.cpp

CmakeLists.txt

-my_library(folder)

---my_library.h(inside the folder)

---my_library.cpp(inside the folder)

---CmakeLists.txt(inside the folder)

im using mingw as compiler and executing all comands with cmd of windows

i have tryed everything, uninstall and install again cmake, adding the target_include_directories but it doesnt work

Body:
im new in Cmake, im trying to link a library to a project using Cmake, the following code is this:

code of the header:

my_library.h

    #ifndef MY_LIBRARY
    #define MY_LIBRARY

    int get_random_number();

    #endif

implementation of the header:
my_library.cpp

    #include "my_library.h"

    int get_random_number(){

            return 46;
    }

Configuration of Cmake

CmakeLists.txt

    cmake_minimum_required(VERSION 3.8)

    file(GLOB_RECURSE SOURCES LIST_DIRECTORIES true *.h *.cpp)

    set(SOURCES ${SOURCES})

    add_library(my_library SHARED ${SOURCES})

    target_include_directories(my_library PUBLIC ${CMAKE_CURRENT_LIST_DIR})

outside the folder i have this:

main.cpp

#include <iostream>
#include "my_library.h"

    int main(){

            std::cout<<"Hello, jairo"<<std::endl;
            std::cout<<"A random number is: "<<get_random_number()<<std::endl;

            return 0;

    }

CmakeListst.txt

    cmake_minimum_required(VERSION 3.20)

    project(Hello CXX)

    add_subdirectory(my_library)

    add_executable(${PROJECT_NAME} main.cpp)

    target_link_libraries(${PROJECT_NAME} PUBLIC my_library)

the structure of the whole project is this:

all goes well until y try to execute the Hello.exe file that is generated, windows gives an error saying "Code execution cannot continue because libmy_library.dll was not found" which i undestand as CMake is not linking correctly the library

the structure of the project is this

main.cpp

CmakeLists.txt

-my_library(folder)

---my_library.h(inside the folder)

---my_library.cpp(inside the folder)

---CmakeLists.txt(inside the folder)

im using mingw as compiler and executing all comands with cmd of windows

i have tryed everything, uninstall and install again cmake, adding the target_include_directories but it doesnt work


问:
How to overcome 'User activation is required' restriction?
In this application I try to access the local fonts of a browser using the following API: https://wicg.github.io/local-font-access

The app should ask the user for permission to access the fonts, however my problem is that because of security reasons the prompt for asking permission is not shown unless the user has some displayed some activity (e.g. user clicked before 5s passed). That rule is defined here.

I need to request font access at when the application starts and when user hasn't conducted any activity yet. Adding a button like Load fonts will fix the problem but I am trying to avoid this.

Is it possible to overcome this restriction and prompt the user or permission at startup without initial user interaction?

<!DOCTYPE html>

```


问:
How to avoid splitting float numbers while using Wordninja?
I am working on cleaning textual data. I have a column that shows description of products. Some words are adjacent. I used wordninja for splitting words.

It worked well but it split the float numbers. I want to use these numbers as it is.

Is there a way to avoid split floats while using wordninja?

```<code>import wordninja
def split_adjacent_words(description):
    words = wordninja.split(description)
    return" ".join(words)

df['description_clean'] = df[df['description'].isna()==False]['description'].apply(lambda x : split_adjacent_words(x))
</code>```

Body:
I am working on cleaning textual data. I have a column that shows description of products. Some words are adjacent. I used wordninja for splitting words.

It worked well but it split the float numbers. I want to use these numbers as it is.

Is there a way to avoid split floats while using wordninja?

import wordninja
def split_adjacent_words(description):
    words = wordninja.split(description)
    return" ".join(words)

df['description_clean'] = df[df['description'].isna()==False]['description'].apply(lambda x : split_adjacent_words(x))


问:
How can I install Poppler on Heroku for my Rails app?
I wanted to enable previews on PDFs in Active Storage:
https://api.rubyonrails.org/classes/ActiveStorage/Preview.html

In order to do this I installed Poppler on my Mac using brew install poppler. I also installed the Poppler gem in my gemfile. The preview functionality works as I want on my local machine.

When I go to deploy to Heroku the build fails and I get the following error:

```<code>An error occurred while installing gobject-introspection (4.0.5), and Bundler
       cannot continue.

       In Gemfile:
         poppler was resolved to 4.0.5, which depends on
           gio2 was resolved to 4.0.5, which depends on
             gobject-introspection
</code>```

I've attempted using the following buildpack, but with no luck:
https://github.com/amitree/heroku-buildpack-poppler.git

Has anyone had any success installing Poppler on Heroku? Ideally on more recent Heroku stacks, and not an older stack.

Body:
I wanted to enable previews on PDFs in Active Storage:
https://api.rubyonrails.org/classes/ActiveStorage/Preview.html

In order to do this I installed Poppler on my Mac using brew install poppler. I also installed the Poppler gem in my gemfile. The preview functionality works as I want on my local machine.

When I go to deploy to Heroku the build fails and I get the following error:

An error occurred while installing gobject-introspection (4.0.5), and Bundler
       cannot continue.

       In Gemfile:
         poppler was resolved to 4.0.5, which depends on
           gio2 was resolved to 4.0.5, which depends on
             gobject-introspection

I've attempted using the following buildpack, but with no luck:
https://github.com/amitree/heroku-buildpack-poppler.git

Has anyone had any success installing Poppler on Heroku? Ideally on more recent Heroku stacks, and not an older stack.


问:
Google chart horizontal date bars too wide
My issue is that the each bar spans a few days either side of the date instead of just the one day on the hAxis (x axis).  How do I make each hAxis bar be just 1 day wide?

```<code>google.charts.safeLoad({'packages':['corechart']});
google.charts.setOnLoadCallback(function(){
        chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
    });
</code>```

...

```<code>var rows = [[new Date("2022-12-14 00:00:00"),2,"14/12/2022","color:blue"],[new Date("2022-12-01 00:00:00"),1,"01/12/2022","color:blue"],[new Date("2022-09-21 00:00:00"),1,"21/09/2022","color:blue"],[new Date("2022-03-16 00:00:00"),1,"16/03/2022","color:blue"]];

var data = new google.visualization.DataTable();
data.addColumn('date', "Date");
data.addColumn('number', "Quantity");
data.addColumn({type:"string", role:"tooltip"});
data.addColumn({type:"string", role:"style"});
data.addRows(rows);
var options = {
    hAxis:{
        title: "Date",
        textStyle : { fontSize:10 },
        titleTextStyle: { fontSize:12, bold:true, italic:false },
        viewWindow: { min:new Date("2021-12-14"), max:new Date("2022-12-14") }
    },
    vAxis:{
        title: "Quantity",
        textStyle : { fontSize:10 },
        titleTextStyle: { fontSize:12, bold:true, italic:false },
        format:"0"
    },
    isStacked: "absolute",
    animation: {
        duration: 750,
        easing: "out",
        startup: true
    },
    chartArea: {
        width: "92%",
        height: "160",
        top: "4"
    },
    explorer: { actions: ["dragToZoom", "rightClickToReset"] },
    legend: {position: 'none'},
    width: "100%",
    height: "100%",
    bar: {
        gap:2,
        groupWidth: "95%"
    }
};

chart.draw(data, options);
</code>```

Body:
My issue is that the each bar spans a few days either side of the date instead of just the one day on the hAxis (x axis).  How do I make each hAxis bar be just 1 day wide?

google.charts.safeLoad({'packages':['corechart']});
google.charts.setOnLoadCallback(function(){
        chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
    });

...

var rows = [[new Date("2022-12-14 00:00:00"),2,"14/12/2022","color:blue"],[new Date("2022-12-01 00:00:00"),1,"01/12/2022","color:blue"],[new Date("2022-09-21 00:00:00"),1,"21/09/2022","color:blue"],[new Date("2022-03-16 00:00:00"),1,"16/03/2022","color:blue"]];

var data = new google.visualization.DataTable();
data.addColumn('date', "Date");
data.addColumn('number', "Quantity");
data.addColumn({type:"string", role:"tooltip"});
data.addColumn({type:"string", role:"style"});
data.addRows(rows);
var options = {
    hAxis:{
        title: "Date",
        textStyle : { fontSize:10 },
        titleTextStyle: { fontSize:12, bold:true, italic:false },
        viewWindow: { min:new Date("2021-12-14"), max:new Date("2022-12-14") }
    },
    vAxis:{
        title: "Quantity",
        textStyle : { fontSize:10 },
        titleTextStyle: { fontSize:12, bold:true, italic:false },
        format:"0"
    },
    isStacked: "absolute",
    animation: {
        duration: 750,
        easing: "out",
        startup: true
    },
    chartArea: {
        width: "92%",
        height: "160",
        top: "4"
    },
    explorer: { actions: ["dragToZoom", "rightClickToReset"] },
    legend: {position: 'none'},
    width: "100%",
    height: "100%",
    bar: {
        gap:2,
        groupWidth: "95%"
    }
};

chart.draw(data, options);


问:
NextJS rewriting url even tho I deleted the config
I was trying to fix a course issue with my http graphql endpoint on local host and tried rewrites and redirects on next.config.js, neither worked so I deleted them but now the browser always goes to the url I tried to redirect to, and it's breaking the webpage. Does anyone know how to resolve this?</p>


问:
Why does passing a jQuery object to .replaceWith() replace the element with "[object Object]"?
I've got a page with several li elements. I'm trying to replace one of those li elements with an array of elements using jQuery. When I pass either a jQuery object or array of jQuery objects to replaceWith(), however, the element is replaced with the string "[object Object]" for each item in the array.

let newElement = $("

");
$("#myListItem").replaceWith(newElement);```
<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>
<div class="container">
  <ul>
    <li id="myListItem"></li>
  </ul>
</div></code>```

I expect to see:

```<code><div class="container">
<ul>
<li class='myClass'></li>
</ul>
</div>
</code>```

Instead, I get:

```<code><div class="container">
<ul>
[object Object]
</ul>
</div>
</code>```

EDIT:

@Barmar and @Bergi were correct in the comments below. Something is causing .replaceWith() invoked on jQuery objects to trigger the native .replaceWith() method. The output in the snippet below demonstrates exactly what I'm seeing when I run my code (except my code is ostensibly using the jQuery method).

let newElement = $("
New li
");
let newElement1 = $("
New li
");
let newElement2 = $("
New li
");

let elementArray = [newElement, newElement1, newElement2]

document.getElementById('myListItem').replaceWith(elementArray);```
<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>
<div class="container">
  <ul>
    <li id="myListItem"></li>
  </ul>
</div></code>```

Body:
I've got a page with several li elements. I'm trying to replace one of those li elements with an array of elements using jQuery. When I pass either a jQuery object or array of jQuery objects to replaceWith(), however, the element is replaced with the string "[object Object]" for each item in the array.

let newElement = $("

");
$("#myListItem").replaceWith(newElement);

I expect to see:

Instead, I get:

[object Object]

EDIT:

@Barmar and @Bergi were correct in the comments below. Something is causing .replaceWith() invoked on jQuery objects to trigger the native .replaceWith() method. The output in the snippet below demonstrates exactly what I'm seeing when I run my code (except my code is ostensibly using the jQuery method).

let newElement = $("
New li
");
let newElement1 = $("
New li
");
let newElement2 = $("
New li
");

let elementArray = [newElement, newElement1, newElement2]

document.getElementById('myListItem').replaceWith(elementArray);


问:
Angular 14 cannot match routes with XSS script in the URL
I'm making an angular app with routing. Everything works fine, even the error 404 wildcard, but if I add any script code as a url parameter in the browser address bar (like http://localhost/page/) it throws the following error:

ERROR Error: Uncaught (in promise): Error: NG04002: Cannot match any routes. URL Segment: '123'

I've seen a couple of old answers on this site for the same issue on angular 4, I'm working with angular 14, but none have any good answers:

Angular 4 throwing Cannot match any routes error with XSS script in URL

Got Error: Cannot match any routes. URL Segment:

To finish I should add that If instead of  I use something like 123 or even  it correctly redirects the user to the 404 page.

Thanks in advance.


问:
how can i do something if user didnt input anything in console in dart?
I am new in dart and creating a console game.
we have:
int score = 0;
i should give every time a number from user in console environment.
if user input a number than score plus one...
and if user did not input anything and he did not touch his keyboard after 5 seconds the score should be minus one.

please help!

I tried this page sulotion:
How to get keyboard user input within a timeframe
but when use that code in a loop to run the other round of game
as you see below:

```<code>import 'dart:convert';
import 'dart:io';

Future<void> main() async {
  for(var i = 0; i < 10; i++) {
    print('You have 5 seconds! WHAT IS YOUR NAME!!!!');
    final name = await stdin
        .transform(const Utf8Decoder())
        .transform(const LineSplitter())
        .timeout(const Duration(seconds: 5), onTimeout: (sink) =>
sink.add('2'))
        .first;

    if (name == null) {
      print('LOL WUT DO YOUR NOT EVEN KNOW YOUR NAME!!!!');
    } else {
      print('I knew it. Your name is $name!');
    }
  }
}
</code>```

that give me this error:

```<code>Unhandled exception:
Bad state: Stream has already been listened to.
#0      _StreamController._subscribe (dart:async/stream_controller.dart:676:7)
#1      _ControllerStream._createSubscription (dart:async/stream_controller.dart:827:19)
#2      _StreamImpl.listen (dart:async/stream_impl.dart:471:9)
#3      _Socket.listen (dart:io-patch/socket_patch.dart:2184:31)
#4      _StdStream.listen (dart:io/stdio.dart:22:20)
#5      new _SinkTransformerStreamSubscription (dart:async/stream_transformers.dart:49:16)
#6      _BoundSinkStream.listen (dart:async/stream_transformers.dart:171:9)
#7      new _SinkTransformerStreamSubscription (dart:async/stream_transformers.dart:49:16)
</code>```

Body:
I am new in dart and creating a console game.
we have:
int score = 0;
i should give every time a number from user in console environment.
if user input a number than score plus one...
and if user did not input anything and he did not touch his keyboard after 5 seconds the score should be minus one.

please help!

I tried this page sulotion:
How to get keyboard user input within a timeframe
but when use that code in a loop to run the other round of game
as you see below:

import 'dart:convert';
import 'dart:io';

Future<void> main() async {
  for(var i = 0; i < 10; i++) {
    print('You have 5 seconds! WHAT IS YOUR NAME!!!!');
    final name = await stdin
        .transform(const Utf8Decoder())
        .transform(const LineSplitter())
        .timeout(const Duration(seconds: 5), onTimeout: (sink) =>
sink.add('2'))
        .first;

    if (name == null) {
      print('LOL WUT DO YOUR NOT EVEN KNOW YOUR NAME!!!!');
    } else {
      print('I knew it. Your name is $name!');
    }
  }
}

that give me this error:

Unhandled exception:
Bad state: Stream has already been listened to.
#0      _StreamController._subscribe (dart:async/stream_controller.dart:676:7)
#1      _ControllerStream._createSubscription (dart:async/stream_controller.dart:827:19)
#2      _StreamImpl.listen (dart:async/stream_impl.dart:471:9)
#3      _Socket.listen (dart:io-patch/socket_patch.dart:2184:31)
#4      _StdStream.listen (dart:io/stdio.dart:22:20)
#5      new _SinkTransformerStreamSubscription (dart:async/stream_transformers.dart:49:16)
#6      _BoundSinkStream.listen (dart:async/stream_transformers.dart:171:9)
#7      new _SinkTransformerStreamSubscription (dart:async/stream_transformers.dart:49:16)


问:
I can not get the name of the server in subscribers and subscription databases
enter image description here

I CAN NOT GET THE NAME OF THE SERVER IN SUBSCRIBERS AND SUBSCRIPTION DATABASES
I can enter into the Sql explorer with ALIAS and IP of another SERVER 2, but when i search in Subscribers of Replication i can get NODE2\SQL2016.
I tried with IP but i have this error
You must enter a subscription database name for Subscriber 'NODE1\SQL2016' and i can't pass to the next step
Please, help me!
I am doing this 3 weeks!!!!

I need to get NODE2\SQL2016 without put the IP
enter image description here


问:
Vue TypeError: Cannot read properties of undefined (reading 'error')
Function here:

```<code>  if (this.mode === 'upload') {
    label = `${this.localizer('label.attachments')}`;
  }
  else if (this.mode === 'view' && !this.error) {
    label = `${this.localizer('label.attachments')} (${this.files.length})`;
  }
  else if (this.error) {
    label = `${this.localizer('label.attachments')}`;
  }

  return label;
},
</code>```

Test file:

beforeEach:

```<code>Constructor = Vue.extend(Attachments);

store = new Vuex.Store({
  propsData,
});

vm = new Constructor({
  store,
  methods: {
    localizer: key => key,
  },
});
vm.$mount();
</code>```

afterEach

```<code>  vm.$destroy();
</code>```

Test here:

```<code>describe('label', () => {
  it('should display attachments label with files length', async () => {
    propsData.error = false;
    propsData.mode = 'view';
    expect(vm.label).to.equal(('1.attachments (2)'));
  });
  it('should display only attachments label when error', async () => {
    propsData.error = true;
    expect(vm.label).to.equal(vm.localizer('1.attachments'));
  });
  it('should display attachments label with files length', async () => {
    propsData.mode = 'upload';
    expect(vm.label).to.equal(vm.localizer('label.attachments'));
  });
});
</code>```

Has error:

AssertionError: expected undefined to equal '1.attachments (2)'
AssertionError: expected undefined to equal '1.attachments'
AssertionError: expected undefined to equal 'label.attachments'

Body:
Function here:

  if (this.mode === 'upload') {
    label = `${this.localizer('label.attachments')}`;
  }
  else if (this.mode === 'view' && !this.error) {
    label = `${this.localizer('label.attachments')} (${this.files.length})`;
  }
  else if (this.error) {
    label = `${this.localizer('label.attachments')}`;
  }

  return label;
},

Test file:

beforeEach:

Constructor = Vue.extend(Attachments);

store = new Vuex.Store({
  propsData,
});

vm = new Constructor({
  store,
  methods: {
    localizer: key => key,
  },
});
vm.$mount();

afterEach

  vm.$destroy();

Test here:

describe('label', () => {
  it('should display attachments label with files length', async () => {
    propsData.error = false;
    propsData.mode = 'view';
    expect(vm.label).to.equal(('1.attachments (2)'));
  });
  it('should display only attachments label when error', async () => {
    propsData.error = true;
    expect(vm.label).to.equal(vm.localizer('1.attachments'));
  });
  it('should display attachments label with files length', async () => {
    propsData.mode = 'upload';
    expect(vm.label).to.equal(vm.localizer('label.attachments'));
  });
});

Has error:

AssertionError: expected undefined to equal '1.attachments (2)'
AssertionError: expected undefined to equal '1.attachments'
AssertionError: expected undefined to equal 'label.attachments'


问:
How do I convert a jSON file to bifxml/bif in python?
I have a bayesian network in a Json file but need in in bifxml. How is this possible?

I searched online for information how to convert it but did not find anything


问:
Run Script as new content loaded , how can i listen to DOM change?
Hi im working on a Chrome extension that adds badges to users, now the problem is i have to refresh the page everytime so the badges can load because there are  client-side changes . How can i watch events change so i run the function on first time page load ?

I read something about input event listener or MutationObserver but im not sure how can i implement that , Any help would be much appreciated .
CODE:

```<code>function Foreground() {
  let users = null;
  let queries = [];
  let userIds = [];

  document.addEventListener("DOMContentLoaded", function(event) {});
  window.addEventListener('load', () => {
    fetchUsersAndQueries();
    chrome.runtime.onMessage.addListener(async(message, sender, res) => {
      if (message.users) {
        fetchUsersAndQueries();

        if (users) {
          return res(users);
        } else {
          return res([]);
        }
      }

      if (message.refresh) {
        try {
          assignBadges();
        } catch (error) {
          console.log(error.message);
        }
      }

      return true;
    });

    let done = false;
    setInterval(() => {
      if (done) {
        return;
      }
      if (users) {
        done = true;

        try {
          assignBadges();
        } catch (error) {
          console.log(error.message);
        }

      }
    }, 500);
  });

  async function fetchUsersAndQueries() {
    userIds = await getAPIUserIds();

    let isStop = false;

    setInterval(() => {
          if (isStop) {
            return;
          }

          const parasiteContainer = document.querySelector('#parasite-container');
          if (parasiteContainer) {
            if (parasiteContainer.shadowRoot) {
              try {
                const roster1 = parasiteContainer.shadowRoot.querySelector(`[name="roster1"]`);
                const roster2 = parasiteContainer.shadowRoot.querySelector(`[name="roster2"]`);

                if (!roster1) {
                  return
                };

                if ([...roster1.children].length === 1) {
                  if (roster1.firstElementChild.children.length === 1) {
                    if (roster1.firstElementChild.firstElementChild.length === 1) {
                      const fTeam = [...roster1.firstElementChild.firstElementChild.firstElementChild.children].map(item => getUsername(item));
                      const sTeam = [...roster2.firstElementChild.firstElementChild.firstElementChild.children].map(item => getUsername(item));
                      users = fTeam.concat(sTeam).flat();
                      queries.push([...roster1.firstElementChild.firstElementChild.firstElementChild.children]);
                      queries.push([...roster2.firstElementChild.firstElementChild.firstElementChild.children]);
                      isStop = true;
                    } else {
                      const fTeam = [...roster1.firstElementChild.firstElementChild.children].map(item => getUsername(item));
                      const sTeam = [...roster2.firstElementChild.firstElementChild.children].map(item => getUsername(item));
                      users = fTeam.concat(sTeam).flat();
                      queries.push([...roster1.firstElementChild.firstElementChild.children]);
                      queries.push([...roster2.firstElementChild.firstElementChild.children]);
                      isStop = true;
                    }
                  } else {
                    const fTeam = [...roster1.firstElementChild.children].map(item => getUsername(item));
                    const sTeam = [...roster2.firstElementChild.children].map(item => getUsername(item));
                    users = fTeam.concat(sTeam).flat();
                    queries.push([...roster1.firstElementChild.children]);
                    queries.push([...roster2.firstElementChild.children]);
                    isStop = true;
                  }
                }

                queries.forEach(query => {
                  query.map(item => {
                    if (item.children.length > 1) {
                      [...item.children].map(child => {
                        // const container = child.querySelector('.sc-hCQDas'); // Classname might change in the future.
                        const container = child.firstElementChild ? .firstElementChild ? .firstElementChild ? .firstElementChild ? .children[2];
                        if (container) {
                          container.insertAdjacentHTML(
                            'beforeend',
                            createBadge(badgesResponse.data.exists, child.dataset.userId)
                          );
                        }
                      });
                    } else {
                      // const container = item.querySelector('.sc-hCQDas'); // Classname might change in the future.
                      const container = item.firstElementChild ? .firstElementChild ? .firstElementChild ? .children[0];
                      if (container) {
                        container.insertAdjacentHTML(
                          'beforeend',
                          createBadge(badgesResponse.data.exists, item.dataset.userId)
                        );
                      }
                    }

                  });
                });
              }
</code>```

Body:
Hi im working on a Chrome extension that adds badges to users, now the problem is i have to refresh the page everytime so the badges can load because there are  client-side changes . How can i watch events change so i run the function on first time page load ?

I read something about input event listener or MutationObserver but im not sure how can i implement that , Any help would be much appreciated .
CODE:

function Foreground() {
  let users = null;
  let queries = [];
  let userIds = [];

  document.addEventListener("DOMContentLoaded", function(event) {});
  window.addEventListener('load', () => {
    fetchUsersAndQueries();
    chrome.runtime.onMessage.addListener(async(message, sender, res) => {
      if (message.users) {
        fetchUsersAndQueries();

        if (users) {
          return res(users);
        } else {
          return res([]);
        }
      }

      if (message.refresh) {
        try {
          assignBadges();
        } catch (error) {
          console.log(error.message);
        }
      }

      return true;
    });

    let done = false;
    setInterval(() => {
      if (done) {
        return;
      }
      if (users) {
        done = true;

        try {
          assignBadges();
        } catch (error) {
          console.log(error.message);
        }

      }
    }, 500);
  });

  async function fetchUsersAndQueries() {
    userIds = await getAPIUserIds();

    let isStop = false;

    setInterval(() => {
          if (isStop) {
            return;
          }

          const parasiteContainer = document.querySelector('#parasite-container');
          if (parasiteContainer) {
            if (parasiteContainer.shadowRoot) {
              try {
                const roster1 = parasiteContainer.shadowRoot.querySelector(`[name="roster1"]`);
                const roster2 = parasiteContainer.shadowRoot.querySelector(`[name="roster2"]`);

                if (!roster1) {
                  return
                };

                if ([...roster1.children].length === 1) {
                  if (roster1.firstElementChild.children.length === 1) {
                    if (roster1.firstElementChild.firstElementChild.length === 1) {
                      const fTeam = [...roster1.firstElementChild.firstElementChild.firstElementChild.children].map(item => getUsername(item));
                      const sTeam = [...roster2.firstElementChild.firstElementChild.firstElementChild.children].map(item => getUsername(item));
                      users = fTeam.concat(sTeam).flat();
                      queries.push([...roster1.firstElementChild.firstElementChild.firstElementChild.children]);
                      queries.push([...roster2.firstElementChild.firstElementChild.firstElementChild.children]);
                      isStop = true;
                    } else {
                      const fTeam = [...roster1.firstElementChild.firstElementChild.children].map(item => getUsername(item));
                      const sTeam = [...roster2.firstElementChild.firstElementChild.children].map(item => getUsername(item));
                      users = fTeam.concat(sTeam).flat();
                      queries.push([...roster1.firstElementChild.firstElementChild.children]);
                      queries.push([...roster2.firstElementChild.firstElementChild.children]);
                      isStop = true;
                    }
                  } else {
                    const fTeam = [...roster1.firstElementChild.children].map(item => getUsername(item));
                    const sTeam = [...roster2.firstElementChild.children].map(item => getUsername(item));
                    users = fTeam.concat(sTeam).flat();
                    queries.push([...roster1.firstElementChild.children]);
                    queries.push([...roster2.firstElementChild.children]);
                    isStop = true;
                  }
                }

                queries.forEach(query => {
                  query.map(item => {
                    if (item.children.length > 1) {
                      [...item.children].map(child => {
                        // const container = child.querySelector('.sc-hCQDas'); // Classname might change in the future.
                        const container = child.firstElementChild ? .firstElementChild ? .firstElementChild ? .firstElementChild ? .children[2];
                        if (container) {
                          container.insertAdjacentHTML(
                            'beforeend',
                            createBadge(badgesResponse.data.exists, child.dataset.userId)
                          );
                        }
                      });
                    } else {
                      // const container = item.querySelector('.sc-hCQDas'); // Classname might change in the future.
                      const container = item.firstElementChild ? .firstElementChild ? .firstElementChild ? .children[0];
                      if (container) {
                        container.insertAdjacentHTML(
                          'beforeend',
                          createBadge(badgesResponse.data.exists, item.dataset.userId)
                        );
                      }
                    }

                  });
                });
              }


问:
How to load a custom model from disk
I did a fine tunning on whisper model with custom data and pushed to huggingFace, I clone it and cant make inferences from disk, how I could load from disk and make inference, this is the model link, thanks a lot

https://huggingface.co/kirah/fcv_s2t_2/tree/main

Title: How to load a custom model from disk


问:
MDX. Mixing measures with dimensions
Have multiple departments, which have monthly sales' measure and "Inception to Date" (ITD) and "Year to Date" (YTD) sales' data measures.

```<code>SELECT {[Dep1], [Dep1ITD], [Dep1YTD], [Dep2], [Dep2ITD], [Dep2YTD]} ON ROWS,
    {[Calendar Date].[Calendar yyyy-MMM].[Calendar yyyy-MMM].ALLMEMBERS} ON COLUMNS
FROM (
    SELECT ( { [Calendar Date].[Calendar yyyy-MMM].&[202206]:[Calendar Date].[Calendar yyyy-MMM].&[202209]}
) ON COLUMNS
FROM [MyCube])
</code>```

Code above produces following result:

I do not have a need to show all YTD & ITD data, I need to show it only once - before the beginning of the period. Like this:

YTD & ITD are calculated from the May-2022 numbers minus May's sales.
In this example:

```<code>"Dep1 ITD": 538 = 543 - 5
"Dep2 ITD": 288 = 292 - 4
"Dep1 YTD": 23 = 28 - 5
"Dep2 YTD": 14 = 18 - 4
</code>```

Is it possible to do with MDX?
If so, how complicated it would be?
Will it be faster than extract two separate data sets and link them in a front-end application?

Title: MDX. Mixing measures with dimensions

Body:
Have multiple departments, which have monthly sales' measure and "Inception to Date" (ITD) and "Year to Date" (YTD) sales' data measures.

SELECT {[Dep1], [Dep1ITD], [Dep1YTD], [Dep2], [Dep2ITD], [Dep2YTD]} ON ROWS,
    {[Calendar Date].[Calendar yyyy-MMM].[Calendar yyyy-MMM].ALLMEMBERS} ON COLUMNS
FROM (
    SELECT ( { [Calendar Date].[Calendar yyyy-MMM].&[202206]:[Calendar Date].[Calendar yyyy-MMM].&[202209]}
) ON COLUMNS
FROM [MyCube])

Code above produces following result:

I do not have a need to show all YTD & ITD data, I need to show it only once - before the beginning of the period. Like this:

YTD & ITD are calculated from the May-2022 numbers minus May's sales.
In this example:

"Dep1 ITD": 538 = 543 - 5
"Dep2 ITD": 288 = 292 - 4
"Dep1 YTD": 23 = 28 - 5
"Dep2 YTD": 14 = 18 - 4

Is it possible to do with MDX?
If so, how complicated it would be?
Will it be faster than extract two separate data sets and link them in a front-end application?


问:
Telegram Bots -- proper way to have the user to wait for an external API response?
My Telegram Bot will make 1-2 Http API requests to external API. I guess, it may take up to 1-2 minutes to receive an replies.

What's a proper way in Telegram Bots to let the user to wait in such cases? Should I simply send him a text "working.... wait...it may take 1 or several minutes" thus letting him wait and this will be it? Or is there a special way to handle this in Telegram Bots?


问:
What could be the issue in the following R code. The tuning parameter grid should have columns C
Error: The tuning parameter grid should have columns C

When run the code below I get

Error: The tuning parameter grid should have columns C

```<code>library(caret)
library(e1071)
library(tree)
library(curl)
library(kernlab)

data <- read.csv("WineQuality_Training.csv")
head(data)
# Split the dataset into predictor variables and target variable
X <- data[,1:11]
y <- data[,12]

# Create the grid
grid <- expand.grid(cost = c(0.1, 1, 10, 100, 1000))
# Fit the model using a linear kernel
model <- train(x = X, y = y, method = "svmLinear", tuneGrid = grid, trControl = trainControl(method = "cv", number = 5))

# Print the best cost parameter
print(model$bestTune)
</code>```

Pass without the

Error: The tuning parameter grid should have columns C

Here I share the sample data datafile

Body:
Error: The tuning parameter grid should have columns C

When run the code below I get

Error: The tuning parameter grid should have columns C

library(caret)
library(e1071)
library(tree)
library(curl)
library(kernlab)

data <- read.csv("WineQuality_Training.csv")
head(data)
# Split the dataset into predictor variables and target variable
X <- data[,1:11]
y <- data[,12]

# Create the grid
grid <- expand.grid(cost = c(0.1, 1, 10, 100, 1000))
# Fit the model using a linear kernel
model <- train(x = X, y = y, method = "svmLinear", tuneGrid = grid, trControl = trainControl(method = "cv", number = 5))

# Print the best cost parameter
print(model$bestTune)

Pass without the

Error: The tuning parameter grid should have columns C

Here I share the sample data datafile


问:
Why am I getting a KeyError despite the key being in the dictionary?
I am making a turtle dungeon escape game in python. The coordinates of the turtle are locked to be within the area of the dungeon walls. The coordinates of the turtle are used in order to write the correct description for the room the user is in. Some coordinates that are listed within the dictionaries used to translate the coordinates into the description of the room are returning KeyErrors despite the keys being in the dictionaries.

```<code>import turtle
from inspect import getframeinfo, stack

class Story:

    def __init__(self, location, qdescription):
        self.location = location
        self.qdescription = qdescription

        self.wn = turtle.Screen()  # Get a reference to the window
        self.turt = turtle.Turtle()  # Create our favorite turtle
        self.turtwrite = turtle.Turtle()  # Creates another turtle specifically for writing

        # These lines "wire up" keypresses to the handlers we've defined.
        self.wn.onkey(self.h1, "Up")
        self.wn.onkey(self.h2, "Left")
        self.wn.onkey(self.h3, "Right")
        self.wn.onkey(self.h4, "Down")
        self.wn.onkey(self.h5, "q")

        # Now we need to tell the window to start listening for events,
        # If any of the keys that we're monitoring is pressed, its
        # handler will be called.
        self.wn.listen()
        self.wn.mainloop()

    def h1(self):
        up = [(-37, 62), (-62, 62), (-37, 87), (-37, 112), (-37, 137), (-37, 162), (-37, 187), (-37, 212), (-37, 237), (-12, 62), (13, 62), (-12, 37), (13, 87), (38, 62), (13, 112), (38, 37), (88, 62), (63, 37)]

        roomdict = {(13, 87): 'maze5'}

        roomdesc = {'maze5': 'You see a tunnel that is lit with a single torch burning a green flame. There are 2 ways to go: [North and South].'}

        if self.turt.pos() in up:
            self.turt.setheading(90)
            self.turt.forward(25)

            self.location = roomdict[self.turt.pos()]
            self.qdescription = roomdesc[self.location]

</code>```

The error that is returning is:

```<code>Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\M\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 1921, in __call__
    return self.func(*args)
  File "C:\Users\M\AppData\Local\Programs\Python\Python310\lib\turtle.py", line 685, in eventfun
    fun()
  h1
    self.location = roomdict[self.turt.pos()]
KeyError: (13.00,87.00)
</code>```

Body:
I am making a turtle dungeon escape game in python. The coordinates of the turtle are locked to be within the area of the dungeon walls. The coordinates of the turtle are used in order to write the correct description for the room the user is in. Some coordinates that are listed within the dictionaries used to translate the coordinates into the description of the room are returning KeyErrors despite the keys being in the dictionaries.

import turtle
from inspect import getframeinfo, stack

class Story:

    def __init__(self, location, qdescription):
        self.location = location
        self.qdescription = qdescription

        self.wn = turtle.Screen()  # Get a reference to the window
        self.turt = turtle.Turtle()  # Create our favorite turtle
        self.turtwrite = turtle.Turtle()  # Creates another turtle specifically for writing

        # These lines "wire up" keypresses to the handlers we've defined.
        self.wn.onkey(self.h1, "Up")
        self.wn.onkey(self.h2, "Left")
        self.wn.onkey(self.h3, "Right")
        self.wn.onkey(self.h4, "Down")
        self.wn.onkey(self.h5, "q")

        # Now we need to tell the window to start listening for events,
        # If any of the keys that we're monitoring is pressed, its
        # handler will be called.
        self.wn.listen()
        self.wn.mainloop()

    def h1(self):
        up = [(-37, 62), (-62, 62), (-37, 87), (-37, 112), (-37, 137), (-37, 162), (-37, 187), (-37, 212), (-37, 237), (-12, 62), (13, 62), (-12, 37), (13, 87), (38, 62), (13, 112), (38, 37), (88, 62), (63, 37)]

        roomdict = {(13, 87): 'maze5'}

        roomdesc = {'maze5': 'You see a tunnel that is lit with a single torch burning a green flame. There are 2 ways to go: [North and South].'}

        if self.turt.pos() in up:
            self.turt.setheading(90)
            self.turt.forward(25)

            self.location = roomdict[self.turt.pos()]
            self.qdescription = roomdesc[self.location]

The error that is returning is:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\M\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 1921, in __call__
    return self.func(*args)
  File "C:\Users\M\AppData\Local\Programs\Python\Python310\lib\turtle.py", line 685, in eventfun
    fun()
  h1
    self.location = roomdict[self.turt.pos()]
KeyError: (13.00,87.00)


问:
How do I perform a Spring JPA @OneToMany/@ManyToOne join using composite non-primary keys?
I need to implement a join starting from the (destinationFsac, destinationCity, destinationRoad) non-unique tuple in AuditAttributes and returning an OperatingStation with the unique non-primary key of (fsac, city19, operatingRoad).

AuditAttributes.java:

```<code>    @Column(name="AAT_DEST_FSAC", nullable = false)
    private String destinationFsac;

    @Column(name="AAT_DEST_CITY_19", nullable = false)
    private String destinationCity;

    @Column(name="AAT_DEST_RD", nullable = false)
    private String destinationRoad;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "AAT_DEST_FSAC", referencedColumnName = "FSAC", insertable = false, updatable = false)
    @JoinColumn(name = "AAT_DEST_CITY_19", referencedColumnName = "OP_STA_CITY_19", insertable = false, updatable = false)
    @JoinColumn(name = "AAT_DEST_RD", referencedColumnName = "OP_RD", insertable = false, updatable = false)
    @Where(clause = "deletePending <> 'Y'")
    private OperatingStation destOperatingStation;
</code>```

OperatingStation.java:

```<code>    @NaturalId
    @Column(name = "FSAC")
    private String fsac;

    @NaturalId
    @Column(name = "OP_STA_CITY_19")
    private String city19;

    @Id
    @NaturalId
    @Column(name = "OP_RD")
    private String operatingRoad;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "destOperatingStation")
    private Set<AuditAttributes> destAuditAttributesSet;
</code>```

AuditRepository.java:

```<code>    @EntityGraph(type = EntityGraph.EntityGraphType.FETCH,
            attributePaths = {
                    "auditAttributes",
                    "auditAttributes.destOperatingStation",
                    "auditAttributes.onOperatingStation",
                    "auditAttributes.offOperatingStation"
            })
    Optional<Audit> findClassificationHistoryRouteBySa(
            @Param("sa") Integer sa);
</code>```

However, when I start up Spring Boot, I get an exception:

```<code>org.springframework.boot.SpringApplication - Application run failed org.hibernate.AnnotationException: referencedColumnNames(FSAC, OP_STA_CITY_19, OP_RD) of com.classification.data.entity.AuditAttributes.destOperatingStation referencing com.classification.data.entity.OperatingStation not mapped to a single property
</code>```

How do I resolve this error and get the join working correctly?

Body:
I need to implement a join starting from the (destinationFsac, destinationCity, destinationRoad) non-unique tuple in AuditAttributes and returning an OperatingStation with the unique non-primary key of (fsac, city19, operatingRoad).

AuditAttributes.java:

    @Column(name="AAT_DEST_FSAC", nullable = false)
    private String destinationFsac;

    @Column(name="AAT_DEST_CITY_19", nullable = false)
    private String destinationCity;

    @Column(name="AAT_DEST_RD", nullable = false)
    private String destinationRoad;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "AAT_DEST_FSAC", referencedColumnName = "FSAC", insertable = false, updatable = false)
    @JoinColumn(name = "AAT_DEST_CITY_19", referencedColumnName = "OP_STA_CITY_19", insertable = false, updatable = false)
    @JoinColumn(name = "AAT_DEST_RD", referencedColumnName = "OP_RD", insertable = false, updatable = false)
    @Where(clause = "deletePending <> 'Y'")
    private OperatingStation destOperatingStation;

OperatingStation.java:

    @NaturalId
    @Column(name = "FSAC")
    private String fsac;

    @NaturalId
    @Column(name = "OP_STA_CITY_19")
    private String city19;

    @Id
    @NaturalId
    @Column(name = "OP_RD")
    private String operatingRoad;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "destOperatingStation")
    private Set<AuditAttributes> destAuditAttributesSet;

AuditRepository.java:

    @EntityGraph(type = EntityGraph.EntityGraphType.FETCH,
            attributePaths = {
                    "auditAttributes",
                    "auditAttributes.destOperatingStation",
                    "auditAttributes.onOperatingStation",
                    "auditAttributes.offOperatingStation"
            })
    Optional<Audit> findClassificationHistoryRouteBySa(
            @Param("sa") Integer sa);

However, when I start up Spring Boot, I get an exception:

org.springframework.boot.SpringApplication - Application run failed org.hibernate.AnnotationException: referencedColumnNames(FSAC, OP_STA_CITY_19, OP_RD) of com.classification.data.entity.AuditAttributes.destOperatingStation referencing com.classification.data.entity.OperatingStation not mapped to a single property

How do I resolve this error and get the join working correctly?


问:
Errno22 in merger.write
```<code>
merging pdf pages...
Traceback (most recent call last):
  File "D:\downloader.py", line 262, in <module>
    merger.write(f"{book_title}.pdf")
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python311\Lib\site-packages\PyPDF2\_merger.py", line 344, in write
    my_file, ret_fileobj = self.output.write(fileobj)
                           ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python311\Lib\site-packages\PyPDF2\_writer.py", line 932, in write
    stream = FileIO(stream, "wb")
             ^^^^^^^^^^^^^^^^^^^^
OSError: [Errno 22] Invalid argument: 'The syntax of serial verbs in Gojri.pdf'

</code>```

I tried to capture multiple webpages and merge them, but something went wrong as shown above. So How can I fix that problem?

Title: Errno22 in merger.write

Body:
merging pdf pages...
Traceback (most recent call last):
  File "D:\downloader.py", line 262, in <module>
    merger.write(f"{book_title}.pdf")
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python311\Lib\site-packages\PyPDF2\_merger.py", line 344, in write
    my_file, ret_fileobj = self.output.write(fileobj)
                           ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python311\Lib\site-packages\PyPDF2\_writer.py", line 932, in write
    stream = FileIO(stream, "wb")
             ^^^^^^^^^^^^^^^^^^^^
OSError: [Errno 22] Invalid argument: 'The syntax of serial verbs in Gojri.pdf'

I tried to capture multiple webpages and merge them, but something went wrong as shown above. So How can I fix that problem?


问:
manually change color in ggplot2
I wanted to create a stacked bar chart with the colors I've indicated in the color_vector. But it's still printing out the default colors associated with ggplot2.

```<code>#create a stacked barchart of proportion
color_vector <- c("lightcoral", "lightblue1", "lightgoldenrod", "salmon", "peachpuff", "pink2", "tan1", "sienna1", "slategray1", "indianred1", "black")
names(color_vector) <- levels(merged_df$trstprl)

ggplot(merged_df, aes(y=proportion, x=cntry, fill = rev(as.factor(trstprl)))) +
  geom_bar(position="stack", stat="identity") +
  scale_color_manual(name = "trust level", values = color_vector) +
  ylab("% of each ranking for trust level") +
  xlab("country") +
  guides(fill=guide_legend(title="Levels of Trust")) +
  scale_fill_discrete(labels=c('10 = Maximum Trust', '9', '8', '7', '6', '5', '4', '3', '2', '1','0 = No Trust')) +
  ggtitle("Proportion of Trust for Government by Country") +
  theme_stata() +
  theme(legend.position = "top", legend.title=element_text(size=10))
</code>```

I've tried using the scale_color_manual but that doesn't seem to be doing anything. I've also tried changing fill to color = rev(as.factor(trstprl)) but that just changes the color of the outline not the entire area of the barchart i'm trying to change

Title: manually change color in ggplot2

Body:
I wanted to create a stacked bar chart with the colors I've indicated in the color_vector. But it's still printing out the default colors associated with ggplot2.

#create a stacked barchart of proportion
color_vector <- c("lightcoral", "lightblue1", "lightgoldenrod", "salmon", "peachpuff", "pink2", "tan1", "sienna1", "slategray1", "indianred1", "black")
names(color_vector) <- levels(merged_df$trstprl)

ggplot(merged_df, aes(y=proportion, x=cntry, fill = rev(as.factor(trstprl)))) +
  geom_bar(position="stack", stat="identity") +
  scale_color_manual(name = "trust level", values = color_vector) +
  ylab("% of each ranking for trust level") +
  xlab("country") +
  guides(fill=guide_legend(title="Levels of Trust")) +
  scale_fill_discrete(labels=c('10 = Maximum Trust', '9', '8', '7', '6', '5', '4', '3', '2', '1','0 = No Trust')) +
  ggtitle("Proportion of Trust for Government by Country") +
  theme_stata() +
  theme(legend.position = "top", legend.title=element_text(size=10))

I've tried using the scale_color_manual but that doesn't seem to be doing anything. I've also tried changing fill to color = rev(as.factor(trstprl)) but that just changes the color of the outline not the entire area of the barchart i'm trying to change


问:
how can i show PDF file as Bytes using QWebEngineView in PyQt5?
i need to import file from the database as Bytes and show it on the window using QWebEngineView in PyQt5.

this is my code:

from PyQt5 import QtWidgets
from PyQt5 import QtGui
from PyQt5 import QtCore
from PyQt5 import QtWebEngineWidgets
import sys

application = QtWidgets.QApplication(sys.argv)
window = QtWidgets.QWidget()
window_layout = QtWidgets.QGridLayout()

PDF = "D:\export.pdf"

file = open(PDF,"rb")

PDF_as_bytes = file.read()

engine = QtWebEngineWidgets.QWebEngineView()
engine.setMinimumSize(500,500)
engine_settings = engine.settings()
engine_settings.setAttribute(QtWebEngineWidgets.QWebEngineSettings.PluginsEnabled, True)
engine_settings.setAttribute(QtWebEngineWidgets.QWebEngineSettings.ShowScrollBars, True)
engine_settings.setAttribute(QtWebEngineWidgets.QWebEngineSettings.PdfViewerEnabled, True)
engine.load(QtCore.QUrl.fromUserInput(PDF))

window_layout.addWidget(engine)
window.setLayout(window_layout)
window.show()
application.exec()

```
<p>i can show the pdf file when i put its path using this code:</p>
<pre class="lang-py prettyprint-override"><code>engine.load(QtCore.QUrl.fromUserInput(PDF))
</code>```

but i need to show it from bytes data.

i tried to use this code:

engine.load(QtCore.QUrl.fromEncoded(PDF_as_bytes))

```

but this code is wrong.

is there a way to show it using the file bytes code ?

Body:
i need to import file from the database as Bytes and show it on the window using QWebEngineView in PyQt5.

this is my code:

from PyQt5 import QtWidgets
from PyQt5 import QtGui
from PyQt5 import QtCore
from PyQt5 import QtWebEngineWidgets
import sys

application = QtWidgets.QApplication(sys.argv)
window = QtWidgets.QWidget()
window_layout = QtWidgets.QGridLayout()

PDF = "D:\export.pdf"

file = open(PDF,"rb")

PDF_as_bytes = file.read()

engine = QtWebEngineWidgets.QWebEngineView()
engine.setMinimumSize(500,500)
engine_settings = engine.settings()
engine_settings.setAttribute(QtWebEngineWidgets.QWebEngineSettings.PluginsEnabled, True)
engine_settings.setAttribute(QtWebEngineWidgets.QWebEngineSettings.ShowScrollBars, True)
engine_settings.setAttribute(QtWebEngineWidgets.QWebEngineSettings.PdfViewerEnabled, True)
engine.load(QtCore.QUrl.fromUserInput(PDF))

window_layout.addWidget(engine)
window.setLayout(window_layout)
window.show()
application.exec()

i can show the pdf file when i put its path using this code:

engine.load(QtCore.QUrl.fromUserInput(PDF))

but i need to show it from bytes data.

i tried to use this code:

engine.load(QtCore.QUrl.fromEncoded(PDF_as_bytes))

but this code is wrong.

is there a way to show it using the file bytes code ?


问:
Why is my used range not counting the correct used Range?
My code below works perfectly fine with Microsoft Office Professional Plus 2016 it is selecting the last used.row which is 14th column; however with Microsoft 365 version it selects on 13th column. Why is it not working properly?

```<code>Sub SelectLastUsedRange()

Dim Master As Workbook
Dim MasterLastColumn As Long

Set Master = ThisWorkbook

    MasterLastColumn = Master.Sheets(1).UsedRange.Columns.Count
    Master.Sheets(1).Activate
    Master.Sheets(1).Cells(2, MasterLastColumn).Select

End Sub
</code>```

Body:
My code below works perfectly fine with Microsoft Office Professional Plus 2016 it is selecting the last used.row which is 14th column; however with Microsoft 365 version it selects on 13th column. Why is it not working properly?

Sub SelectLastUsedRange()

Dim Master As Workbook
Dim MasterLastColumn As Long

Set Master = ThisWorkbook

    MasterLastColumn = Master.Sheets(1).UsedRange.Columns.Count
    Master.Sheets(1).Activate
    Master.Sheets(1).Cells(2, MasterLastColumn).Select

End Sub


问:
"Error 8525:Eithe enlist this session in a new transaction or the null transaction" in a distributed transaction with many records transfer
I have a linked server from SQL2008 to SQL2kSp3.

I want to Insert,Update,Delete records in SQL2008 according to inserted,updated,deleted records in SQL2kSp3.

All of my statements are between Distributed transaction and commit.

I don't have any problem when I want to do these operation in small data. I tested it on 3 records and operation will do in about 20 seconds. But when I'm testing it in many recods about 1000 records it takes about 20 minutes and  I recieve this error message:

```<code>Distributed transaction completed. Eithe enlist this session in a new transaction or the null transaction[SQLSTATE 42000][Error 8525] The step failed
</code>```

I executed Instcat.sql on SQL2k and restarted my sqlserver but I have the same problem.

It's better to say the first I had sql2k without Service pack and then I installed Sql2kSp3 to upgrade it but when I execute

select @@version I don't see Spk3 in the version of sql.

operating systems:

Sql2008 installed on Windowsxp SP2

Sql2k installed on windows 2003 service pack2

Bandwidth is about:256Kbps

Please hepl me.

ContentLicense: CC BY-SA 3.0

Body:
I have a linked server from SQL2008 to SQL2kSp3.

I want to Insert,Update,Delete records in SQL2008 according to inserted,updated,deleted records in SQL2kSp3.

All of my statements are between Distributed transaction and commit.

I don't have any problem when I want to do these operation in small data. I tested it on 3 records and operation will do in about 20 seconds. But when I'm testing it in many recods about 1000 records it takes about 20 minutes and  I recieve this error message:

Distributed transaction completed. Eithe enlist this session in a new transaction or the null transaction[SQLSTATE 42000][Error 8525] The step failed

I executed Instcat.sql on SQL2k and restarted my sqlserver but I have the same problem.

It's better to say the first I had sql2k without Service pack and then I installed Sql2kSp3 to upgrade it but when I execute

select @@version I don't see Spk3 in the version of sql.

operating systems:

Sql2008 installed on Windowsxp SP2

Sql2k installed on windows 2003 service pack2

Bandwidth is about:256Kbps

Please hepl me.


问:
convert ionic input to ionic select not working in ionic
I am trying to modify a project code, the project is written in ionic but I am not ionic developer

I did some search and change the UI from input field to select, but the value is not shown in the select

the old code

```<code><ion-input name="url" placeholder="{{ 'core.login.siteaddressplaceholder' | translate }}" formControlName="siteUrl"[core-auto-focus]="showKeyboard && !showScanQR" (ionChange)="searchSite($event, siteForm.value.siteUrl)">
</ion-input>
</code>```

my new code is

```<code><ion-select name="url" placeholder="{{ 'core.login.siteaddressplaceholder' | translate }}" formControlName="siteUrl"[core-auto-focus]="showKeyboard && !showScanQR" (ionChange)="searchSite($event, siteForm.value.siteUrl)">
    <ion-select-option value="HTTP://www.google.com">Google</ion-select-option>
    <ion-select-option value="HTTP://www.facebook.com">Facebook</ion-select-option>
</ion-select>
</code>```

Body:
I am trying to modify a project code, the project is written in ionic but I am not ionic developer

I did some search and change the UI from input field to select, but the value is not shown in the select

the old code

<ion-input name="url" placeholder="{{ 'core.login.siteaddressplaceholder' | translate }}" formControlName="siteUrl"[core-auto-focus]="showKeyboard && !showScanQR" (ionChange)="searchSite($event, siteForm.value.siteUrl)">
</ion-input>

my new code is

<ion-select name="url" placeholder="{{ 'core.login.siteaddressplaceholder' | translate }}" formControlName="siteUrl"[core-auto-focus]="showKeyboard && !showScanQR" (ionChange)="searchSite($event, siteForm.value.siteUrl)">
    <ion-select-option value="HTTP://www.google.com">Google</ion-select-option>
    <ion-select-option value="HTTP://www.facebook.com">Facebook</ion-select-option>
</ion-select>


问:
Postgres Custom Type vs Table
first time I model a database in quite some time and I see that Postgres has the ability to define custom enum types very similar to enums in programming language.

My question is when should types be used instead of a table with foreign key ?

In a column like "sex" it looks obvious a type is good choice, but should I do this for all "lookup" tables ? Nationality ? Employee Status etc ?

Thank you for your comments and thoughts!

Title: Postgres Custom Type vs Table


问:
AEM SPA React setup Experience Fragment
I need to create experience fragment in AEM SPA React framework.
Bascially, I copied code setting from this article https://experienceleaguecommunities.adobe.com/t5/adobe-experience-manager/aem-6-4-with-spa-editor-how-to-use-the-experience-fragments/m-p/322742

But it did not give details for how component under JCR node setup , e.g src/main/content/jcr_root/apps/project/components/functional/spasamples/experiencefragment

So I setup .content.xml  and other files like below:

enter image description here

my .content.xml :

```<code><?xml version="1.0" encoding="UTF-8"?>
<jcr:root xmlns:sling="http://sling.apache.org/jcr/sling/1.0" xmlns:cq="http://www.day.com/jcr/cq/1.0" xmlns:jcr="http://www.jcp.org/jcr/1.0"
    cq:styleElements="[div,section,article,main,aside,header,footer]"
    jcr:primaryType="cq:Component"
    jcr:title="Experience Fragment"
    componentGroup="POC SPA React - Content"/>
</code>```

my _cq_editConfig.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<jcr:root xmlns:cq="http://www.day.com/jcr/cq/1.0" xmlns:jcr="http://www.jcp.org/jcr/1.0" xmlns:nt="http://www.jcp.org/jcr/nt/1.0"
    cq:actions="[EDIT,DELETE,INSERT,COPYMOVE]"
    jcr:primaryType="cq:EditConfig">
    <cq:dropTargets jcr:primaryType="nt:unstructured">
        <experiencefragment
            jcr:primaryType="cq:DropTargetConfig"
            accept="[text/html]"
            groups="[content]"
            propertyName="./fragmentVariationPath"/>
    </cq:dropTargets>
    <cq:listeners
        jcr:primaryType="nt:unstructured"
        afterinsert="REFRESH_PAGE"/>
    <cq:actionConfigs jcr:primaryType="nt:unstructured">
        <editInNewTab
            jcr:primaryType="nt:unstructured"
            handler="Granite.author.experienceFragments && Granite.author.experienceFragments.actions.editInNewTab"
            icon="edit"
            text="Edit"/>
    </cq:actionConfigs>
</jcr:root>
</code>```

my content.html

```<code><sly data-sly-use.body="body.js" data-sly-resource="${body.resourcePath @ selectors=[]}"/>
</code>```

my customfooterlibs.html

```<code><sly data-sly-use.clientlib="/libs/granite/sightly/templates/clientlib.html">
    <sly data-sly-call="${clientlib.js @ categories='global_pdc.base'}"/>
</sly>
</code>```

my customheaderlibs.html

```<code><meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<sly data-sly-use.clientLib="/libs/granite/sightly/templates/clientlib.html"
     data-sly-call="${clientlib.js @ categories='global_pdc.dependencies'}"/>
<sly data-sly-use.clientLib="/libs/granite/sightly/templates/clientlib.html"
     data-sly-call="${clientlib.css @ categories='global_pdc.base'}"/>

<!--/* Include Context Hub */-->
<sly data-sly-resource="${'contexthub' @ resourceType='granite/contexthub/components/contexthub'}"/>
</code>```

on my test page, i tried to drop experience fragment from the list,  but it is not showing up like other component does

Any advise?
Thanks

Title: AEM SPA React setup Experience Fragment

Body:
I need to create experience fragment in AEM SPA React framework.
Bascially, I copied code setting from this article https://experienceleaguecommunities.adobe.com/t5/adobe-experience-manager/aem-6-4-with-spa-editor-how-to-use-the-experience-fragments/m-p/322742

But it did not give details for how component under JCR node setup , e.g src/main/content/jcr_root/apps/project/components/functional/spasamples/experiencefragment

So I setup .content.xml  and other files like below:

enter image description here

my .content.xml :

<?xml version="1.0" encoding="UTF-8"?>
<jcr:root xmlns:sling="http://sling.apache.org/jcr/sling/1.0" xmlns:cq="http://www.day.com/jcr/cq/1.0" xmlns:jcr="http://www.jcp.org/jcr/1.0"
    cq:styleElements="[div,section,article,main,aside,header,footer]"
    jcr:primaryType="cq:Component"
    jcr:title="Experience Fragment"
    componentGroup="POC SPA React - Content"/>

my _cq_editConfig.xml:

<?xml version="1.0" encoding="UTF-8"?>
<jcr:root xmlns:cq="http://www.day.com/jcr/cq/1.0" xmlns:jcr="http://www.jcp.org/jcr/1.0" xmlns:nt="http://www.jcp.org/jcr/nt/1.0"
    cq:actions="[EDIT,DELETE,INSERT,COPYMOVE]"
    jcr:primaryType="cq:EditConfig">
    <cq:dropTargets jcr:primaryType="nt:unstructured">
        <experiencefragment
            jcr:primaryType="cq:DropTargetConfig"
            accept="[text/html]"
            groups="[content]"
            propertyName="./fragmentVariationPath"/>
    </cq:dropTargets>
    <cq:listeners
        jcr:primaryType="nt:unstructured"
        afterinsert="REFRESH_PAGE"/>
    <cq:actionConfigs jcr:primaryType="nt:unstructured">
        <editInNewTab
            jcr:primaryType="nt:unstructured"
            handler="Granite.author.experienceFragments && Granite.author.experienceFragments.actions.editInNewTab"
            icon="edit"
            text="Edit"/>
    </cq:actionConfigs>
</jcr:root>

my content.html

<sly data-sly-use.body="body.js" data-sly-resource="${body.resourcePath @ selectors=[]}"/>

my customfooterlibs.html

<sly data-sly-use.clientlib="/libs/granite/sightly/templates/clientlib.html">
    <sly data-sly-call="${clientlib.js @ categories='global_pdc.base'}"/>
</sly>

my customheaderlibs.html

<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<sly data-sly-use.clientLib="/libs/granite/sightly/templates/clientlib.html"
     data-sly-call="${clientlib.js @ categories='global_pdc.dependencies'}"/>
<sly data-sly-use.clientLib="/libs/granite/sightly/templates/clientlib.html"
     data-sly-call="${clientlib.css @ categories='global_pdc.base'}"/>

<sly data-sly-resource="${'contexthub' @ resourceType='granite/contexthub/components/contexthub'}"/>

on my test page, i tried to drop experience fragment from the list,  but it is not showing up like other component does

Any advise?
Thanks


问:
Detect USB-C to 3.5 mm jack adapter as headphone even though headphone is not connected/plugged into adapter
I'm listening to AVAudioSession.routeChangeNotification for audio route change using NotificationCenter.

```<code>NotificationCenter.default.addObserver(self,
                                       selector: #selector(handleRouteChange),
                                       name: AVAudioSession.routeChangeNotification,
                                       object: nil)
</code>```

Based on the notification data we decide if plugged in device is headphone or not by using this function:

```<code>@objc private func handleRouteChange(notification: Notification) {
        guard let userInfo = notification.userInfo,
              let reasonValue = userInfo[AVAudioSessionRouteChangeReasonKey] as? UInt,
              let reason = AVAudioSession.RouteChangeReason(rawValue: reasonValue) else {
                  return
              }

        switch reason {
        case .newDeviceAvailable:
            if hasHeadphones(in: session.currentRoute) {
                // Heaphone Logic
            } else {
               // Speaker logic
            }
        case .oldDeviceUnavailable:
            if !hasHeadphones(in: session.currentRoute) {
                // Speaker logic
            }
        case .override:
            if !hasHeadphones(in: session.currentRoute) {
                // Speaker logic
            }
        default:()
        }
    }

    func hasHeadphones(in routeDescription: AVAudioSessionRouteDescription) -> Bool {
        return !routeDescription.outputs.filter({$0.portType == .headphones}).isEmpty
    }
</code>```

I'm coming across the issue that if the headphone is not plugged into the adapter, routeDescription.outputs array still has one element inside. This element has portType of .headphones which means that the headphone is connected even though headphone is not connected to adapter.

Not advertising but I'm using this adapter for my iPad.

Version: iPad Pro(12.9 Inch) 5th gen

iOS Version: 15.6.1

Is this an expected result or is there any possible workaround for this issue?

Body:
I'm listening to AVAudioSession.routeChangeNotification for audio route change using NotificationCenter.

NotificationCenter.default.addObserver(self,
                                       selector: #selector(handleRouteChange),
                                       name: AVAudioSession.routeChangeNotification,
                                       object: nil)

Based on the notification data we decide if plugged in device is headphone or not by using this function:

@objc private func handleRouteChange(notification: Notification) {
        guard let userInfo = notification.userInfo,
              let reasonValue = userInfo[AVAudioSessionRouteChangeReasonKey] as? UInt,
              let reason = AVAudioSession.RouteChangeReason(rawValue: reasonValue) else {
                  return
              }

        switch reason {
        case .newDeviceAvailable:
            if hasHeadphones(in: session.currentRoute) {
                // Heaphone Logic
            } else {
               // Speaker logic
            }
        case .oldDeviceUnavailable:
            if !hasHeadphones(in: session.currentRoute) {
                // Speaker logic
            }
        case .override:
            if !hasHeadphones(in: session.currentRoute) {
                // Speaker logic
            }
        default:()
        }
    }

    func hasHeadphones(in routeDescription: AVAudioSessionRouteDescription) -> Bool {
        return !routeDescription.outputs.filter({$0.portType == .headphones}).isEmpty
    }

I'm coming across the issue that if the headphone is not plugged into the adapter, routeDescription.outputs array still has one element inside. This element has portType of .headphones which means that the headphone is connected even though headphone is not connected to adapter.

Not advertising but I'm using this adapter for my iPad.

Version: iPad Pro(12.9 Inch) 5th gen

iOS Version: 15.6.1

Is this an expected result or is there any possible workaround for this issue?


问:
ConvertFrom-Json : Cannot bind argument to parameter 'InputObject' because it is null
I have this power shell script which read the Office 365 logs for 2 sharepoint site and generate a csv file:-

```<code>Read-Host -Prompt "Enter your tenant password" -AsSecureString | ConvertFrom-SecureString | Out-File "O365.key"

#Get the script path

$dir = ""

#Get the current date

$date = (Get-Date -f dd-MM-yyyy-hhmmss)

#Store the outputfile

$CSVFile = "$dir\Auditlogs_$date.csv"

#Details for sending email

$From = "*****@*****.com"

$To = "*****@*****.com"

$CC ="*****@*****.com"

$smtp = "outlook.office365.com"

$Subject = "Sharepoint audit logs"

#Whom to notify incase of connection to exchange online module fails. This will be the task owner.

$notify="*****@*****.com"

$Body = "Hi Team, Please find the audit logs for the following sharepoint sites for the last x days.

Thanks, O365 Team "

#Create a backup folder and move all the old files to it.

$destination = "$dir\Backup"

$Move = Get-ChildItem -Path "$dir\Auditlogs_*.csv" #| Sort-Object LastWriteTime -Descending | Select-Object -Skip 1

foreach ($file in $Move) {

  $parent = Split-Path $file.FullName -Parent

  Move-Item $file.FullName -Destination $destination -Force

}

#store the o365 credentials

$TenantUname = "*****@*****.com"

#Run the following single line to store the password of account that will be used to connect to o365 exchange online

#Read-Host -Prompt "Enter your tenant password" -AsSecureString | ConvertFrom-SecureString | Out-File "foldername\O365.key"

#Replace the o365 key file that you stored the password.

$TenantPass = $TenantPass = cat "O365.key" | ConvertTo-SecureString

$TenantCredentials = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $TenantUname,$TenantPass

#make sure the exchangeonline module is installed. The script will fail if module not installed.

Import-Module ExchangeOnlineManagement

try { Connect-ExchangeOnline #-UseWebLogin #-Credential $TenantCredentials } catch [System.Exception] { $ErrorMessage = $_.Exception.Message

          $FailedItem = $_.Exception.ItemName

          $WebReqErr = $error[0] | Select-Object * | Format-List -Force

  Write-Error "An error occurred while attempting to connect to the requested service.  $ErrorMessage"

  Send-MailMessage -From $From -To  $notify -SmtpServer $smtp -Subject "Failed to connect to exchnage online" -Body "Please check ." }

#list of sharepoint sites (* means all sub sites as well)

$SiteURLs = @("https://m******.sharepoint.com/sites/*",

"https://m*******.sharepoint.com/sites/hr-hr/*")

#List of audit logs

#For a list of audit logs, refer https://docs.microsoft.com/en-us/microsoft-365/compliance/search-the-audit-log-in-security-and-compliance?view=o365-worldwide#file-and-page-activities

$Operations = @('PageViewed','FileAccessed','FileDownloaded','FileDeleted')

#audit logs for 1 days from today's date

$startDate=(Get-Date).AddDays(-1)

#Number of iterations ()

$daysToSkip=3

$endDate=Get-Date #today's date

#iteration start for 3 days

     while ($startDate -lt $endDate) {
        $startdate1=$startDate

        $startDate = $startDate.AddDays($daysToSkip)

        $enddate1=$startDate

$FileAccessLog = Search-UnifiedAuditLog -StartDate $startDate1
-EndDate $EndDate1 -Operations $Operations -ResultSize 5000 -ObjectIds $SiteURLs

$FileAccessLog.auditdata | ConvertFrom-Json | Select-Object CreationTime,UserId,Operation,ObjectID,SiteUrl,SourceFileName,ClientIP | `

   Export-Csv $CSVFile -NoTypeInformation -Force -Append
        }

   if ((import-csv $CSVFile).Length -gt 0)    {
    Send-MailMessage -From $From -To $To -SmtpServer $smtp -Subject $Subject -Body $Body -Attachments $CSVFile }
</code>```

But i am getting this error:-

```<code>ConvertFrom-Json : Cannot bind argument to parameter 'InputObject' because it is null.
At line:10 char:28
+ $FileAccessLog.auditdata | ConvertFrom-Json | Select-Object CreationT ...
+                            ~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [ConvertFrom-Json], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ConvertFromJsonCommand
</code>```

Body:
I have this power shell script which read the Office 365 logs for 2 sharepoint site and generate a csv file:-

Read-Host -Prompt "Enter your tenant password" -AsSecureString | ConvertFrom-SecureString | Out-File "O365.key"

#Get the script path

$dir = ""

#Get the current date

$date = (Get-Date -f dd-MM-yyyy-hhmmss)

#Store the outputfile

$CSVFile = "$dir\Auditlogs_$date.csv"

#Details for sending email

$From = "*****@*****.com"

$To = "*****@*****.com"

$CC ="*****@*****.com"

$smtp = "outlook.office365.com"

$Subject = "Sharepoint audit logs"

#Whom to notify incase of connection to exchange online module fails. This will be the task owner.

$notify="*****@*****.com"

$Body = "Hi Team, Please find the audit logs for the following sharepoint sites for the last x days.

Thanks, O365 Team "

#Create a backup folder and move all the old files to it.

$destination = "$dir\Backup"

$Move = Get-ChildItem -Path "$dir\Auditlogs_*.csv" #| Sort-Object LastWriteTime -Descending | Select-Object -Skip 1

foreach ($file in $Move) {

  $parent = Split-Path $file.FullName -Parent

  Move-Item $file.FullName -Destination $destination -Force

}

#store the o365 credentials

$TenantUname = "*****@*****.com"

#Run the following single line to store the password of account that will be used to connect to o365 exchange online

#Read-Host -Prompt "Enter your tenant password" -AsSecureString | ConvertFrom-SecureString | Out-File "foldername\O365.key"

#Replace the o365 key file that you stored the password.

$TenantPass = $TenantPass = cat "O365.key" | ConvertTo-SecureString

$TenantCredentials = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $TenantUname,$TenantPass

#make sure the exchangeonline module is installed. The script will fail if module not installed.

Import-Module ExchangeOnlineManagement

try { Connect-ExchangeOnline #-UseWebLogin #-Credential $TenantCredentials } catch [System.Exception] { $ErrorMessage = $_.Exception.Message

          $FailedItem = $_.Exception.ItemName

          $WebReqErr = $error[0] | Select-Object * | Format-List -Force

  Write-Error "An error occurred while attempting to connect to the requested service.  $ErrorMessage"

  Send-MailMessage -From $From -To  $notify -SmtpServer $smtp -Subject "Failed to connect to exchnage online" -Body "Please check ." }

#list of sharepoint sites (* means all sub sites as well)

$SiteURLs = @("https://m******.sharepoint.com/sites/*",

"https://m*******.sharepoint.com/sites/hr-hr/*")

#List of audit logs

#For a list of audit logs, refer https://docs.microsoft.com/en-us/microsoft-365/compliance/search-the-audit-log-in-security-and-compliance?view=o365-worldwide#file-and-page-activities

$Operations = @('PageViewed','FileAccessed','FileDownloaded','FileDeleted')

#audit logs for 1 days from today's date

$startDate=(Get-Date).AddDays(-1)

#Number of iterations ()

$daysToSkip=3

$endDate=Get-Date #today's date

#iteration start for 3 days

     while ($startDate -lt $endDate) {
        $startdate1=$startDate

        $startDate = $startDate.AddDays($daysToSkip)

        $enddate1=$startDate

$FileAccessLog = Search-UnifiedAuditLog -StartDate $startDate1
-EndDate $EndDate1 -Operations $Operations -ResultSize 5000 -ObjectIds $SiteURLs

$FileAccessLog.auditdata | ConvertFrom-Json | Select-Object CreationTime,UserId,Operation,ObjectID,SiteUrl,SourceFileName,ClientIP | `

   Export-Csv $CSVFile -NoTypeInformation -Force -Append
        }

   if ((import-csv $CSVFile).Length -gt 0)    {
    Send-MailMessage -From $From -To $To -SmtpServer $smtp -Subject $Subject -Body $Body -Attachments $CSVFile }

But i am getting this error:-

ConvertFrom-Json : Cannot bind argument to parameter 'InputObject' because it is null.
At line:10 char:28
+ $FileAccessLog.auditdata | ConvertFrom-Json | Select-Object CreationT ...
+                            ~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [ConvertFrom-Json], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ConvertFromJsonCommand


问:
End user credentials must match the user specified in the request. Request for user [ ephemeral-runner@] does not match the credential for [[MASKED]]
I'm trying to run a gitlab CI pipeline with an ansible stage. This ansible stage is using a service account and identity federation as described in https://ael-computas.medium.com/gcp-workload-identity-federation-on-gitlab-passing-authentication-between-jobs-ffaa2d51be2c

However, I can't seem to get it to use the service account properly. I get the following when ansible tries to authenticate:

```<code>End user credentials must match the user specified in the request. Request for user [ ephemeral-runner@gitlab-ci-plan-free-6-xxxx.iam.gserviceaccount.com] does not match the credential for [[MASKED]]
</code>```

How can I make it use the service account (value stored in [[MASKED]] and not this ephemeral-runner service account? I have no idea what that one is since it's not one of my accounts.

Thanks!

Body:
I'm trying to run a gitlab CI pipeline with an ansible stage. This ansible stage is using a service account and identity federation as described in https://ael-computas.medium.com/gcp-workload-identity-federation-on-gitlab-passing-authentication-between-jobs-ffaa2d51be2c

However, I can't seem to get it to use the service account properly. I get the following when ansible tries to authenticate:

End user credentials must match the user specified in the request. Request for user [ ephemeral-runner@gitlab-ci-plan-free-6-xxxx.iam.gserviceaccount.com] does not match the credential for [[MASKED]]

How can I make it use the service account (value stored in [[MASKED]] and not this ephemeral-runner service account? I have no idea what that one is since it's not one of my accounts.

Thanks!


问:
Django Large File Serving
I am trying to make an app like youtube, where I need to serve huge number of files and each Video file size can be large [ 50MB or 1GB, or 2GB or more].  I am using SQLite DataBase. How can I serve these files in an efficient way?

models.py

```<code>class VideoContent(models.Model):

    contenttitle = models.CharField(max_length=300, blank=False)
    file = models.FileField(blank=False, verbose_name='Your Video Content',
        validators=[FileExtensionValidator(
            allowed_extensions=['MOV', 'avi', 'mp4', 'webm', 'mkv']
        )])
    uploaded = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    def __str__(self) -> str:
        return self.contenttitle.title()
</code>```

** views.py **

```<code>class VideoContents(ListView):

    template_name = 'contents/index.html'
    context_object_name = 'videos'
    ordering = '-uploaded'
    model = VideoContent

    # def get_queryset(self):
    #     return VideoContent.objects.all()

</code>```

Title: Django Large File Serving

Body:
I am trying to make an app like youtube, where I need to serve huge number of files and each Video file size can be large [ 50MB or 1GB, or 2GB or more].  I am using SQLite DataBase. How can I serve these files in an efficient way?

models.py

class VideoContent(models.Model):

    contenttitle = models.CharField(max_length=300, blank=False)
    file = models.FileField(blank=False, verbose_name='Your Video Content',
        validators=[FileExtensionValidator(
            allowed_extensions=['MOV', 'avi', 'mp4', 'webm', 'mkv']
        )])
    uploaded = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    def __str__(self) -> str:
        return self.contenttitle.title()

** views.py **

class VideoContents(ListView):

    template_name = 'contents/index.html'
    context_object_name = 'videos'
    ordering = '-uploaded'
    model = VideoContent

    # def get_queryset(self):
    #     return VideoContent.objects.all()