问:
Keyboard input lost when using cross-process parent/child windows
I am investigating a bug that results in key-presses being 'lost' when users are providing rapid keyboard input to our application. It seems to happen randomly. If a user writes e.g. "I am writing this text fast on my keyboard" the actual text that ends up in the application's text box looks something like "Ia wrting thistext fstn mykeybrd."

We have managed to find out that the issue seems to be related to how we integrate the text-input component into our main application. Our main app is a .NET Framework 4.8 WinForms process. The text-input component is running as a .NET 4.8 WPF app in a separate process. The WinForms app is responsible for launching the WPF process, passing the window handle of its own main window as an argument to the new process. Once launched, the WPF process uses the provided window handle to reparent itself as a child window of the WinForms app. This is done using Win32 API calls through P/Invoke.

```<code>        private void Reparent() {
            ChangeStyle(this.myHandle);
            Win32.SetParent(this.myHandle, this.hostHandle);
        }

        private static void ChangeStyle(IntPtr myHandle) {
            const int GWL_STYLE = -16;
            const uint WS_POPUP = 0x80000000;
            const uint WS_CHILD = 0x40000000;
            uint style = Win32.GetWindowLong(myHandle, GWL_STYLE);
            style |= WS_CHILD;
            style &= ~WS_POPUP;
            Win32.SetWindowLong(myHandle, GWL_STYLE, style);
        }
</code>```

According to MSDN this seems to be legal.

For compatibility reasons, SetParent does not modify the WS_CHILD or WS_POPUP window styles of the window whose parent is being changed. Therefore, if hWndNewParent is NULL, you should also clear the WS_CHILD bit and set the WS_POPUP style after calling SetParent. Conversely, if hWndNewParent is not NULL and the window was previously a child of the desktop, you should clear the WS_POPUP style and set the WS_CHILD style before calling SetParent.

We understand that this is a bit erm... 'unorthodox', but the design has been like this for a long time without any other issues.

Interestingly, removing the code that sets the WS_CHILD flag fixes the lost keys problem, but causes a bunch of other issues instead.

According to Raymond Chen

Creating a cross-thread parent/child or owner/owned window relationship implicitly attaches the input queues of the threads which those windows belong to...

We interpret this like AttachThreadInput is called 'under the hood', but do not fully understand what causes keypresses to be lost. Is it some sort of thread-safety issue? A race condition?

By using the AttachThreadInput function, a thread can share its input states (such as keyboard states and the current focus window) with another thread. Keyboard and mouse events received by both threads are processed in the order they were received until the threads are detached by calling AttachThreadInput a second time and specifying FALSE for the fAttach parameter.

We have used Spy++ to monitor the Windows messages that gets sent to the WPF process and it seems that when you type slowly, WM_KEYDOWN is sent together with WM_CHAR. When the input is lost, we still receive the WM_KEYDOWN messages, but no WM_CHAR. This led us to start investigating the .NET framework source. Among other things, we found the following code in HwndSource.cs

```<code> switch ((WindowMessage)msgdata.msg.message)
            {
            case WindowMessage.WM_SYSKEYDOWN:
            case WindowMessage.WM_KEYDOWN:
                // MITIGATION: HANDLED_KEYDOWN_STILL_GENERATES_CHARS
                // In case a nested message pump is used before we return
                // from processing this message, we disable processing the
                // next WM_CHAR message because if the code pumps messages
                // it should really mark the message as handled.
                _eatCharMessages = true;
                DispatcherOperation restoreCharMessages = Dispatcher.BeginInvoke(DispatcherPriority.Normal, new DispatcherOperationCallback(RestoreCharMessages), null);

                // Force the Dispatcher to post a new message to service any
                // pending operations, so that the operation we just posted
                // is guaranteed to get dispatched after any pending WM_CHAR
                // messages are dispatched.
                Dispatcher.CriticalRequestProcessing(true);
</code>```

The variable named _eatCharMessages could perhaps be related, although debugging this code using dnSpy has not made us any wiser.

We're looking for a Win32-wizard to shed some more light on this. Anything that can point us in the right direction would be greatly appreciated. We need to figure out the root cause of  the problem in order to decide how to fix it.

Body:
I am investigating a bug that results in key-presses being 'lost' when users are providing rapid keyboard input to our application. It seems to happen randomly. If a user writes e.g. "I am writing this text fast on my keyboard" the actual text that ends up in the application's text box looks something like "Ia wrting thistext fstn mykeybrd."

We have managed to find out that the issue seems to be related to how we integrate the text-input component into our main application. Our main app is a .NET Framework 4.8 WinForms process. The text-input component is running as a .NET 4.8 WPF app in a separate process. The WinForms app is responsible for launching the WPF process, passing the window handle of its own main window as an argument to the new process. Once launched, the WPF process uses the provided window handle to reparent itself as a child window of the WinForms app. This is done using Win32 API calls through P/Invoke.

        private void Reparent() {
            ChangeStyle(this.myHandle);
            Win32.SetParent(this.myHandle, this.hostHandle);
        }

        private static void ChangeStyle(IntPtr myHandle) {
            const int GWL_STYLE = -16;
            const uint WS_POPUP = 0x80000000;
            const uint WS_CHILD = 0x40000000;
            uint style = Win32.GetWindowLong(myHandle, GWL_STYLE);
            style |= WS_CHILD;
            style &= ~WS_POPUP;
            Win32.SetWindowLong(myHandle, GWL_STYLE, style);
        }

According to MSDN this seems to be legal.

For compatibility reasons, SetParent does not modify the WS_CHILD or WS_POPUP window styles of the window whose parent is being changed. Therefore, if hWndNewParent is NULL, you should also clear the WS_CHILD bit and set the WS_POPUP style after calling SetParent. Conversely, if hWndNewParent is not NULL and the window was previously a child of the desktop, you should clear the WS_POPUP style and set the WS_CHILD style before calling SetParent.

We understand that this is a bit erm... 'unorthodox', but the design has been like this for a long time without any other issues.

Interestingly, removing the code that sets the WS_CHILD flag fixes the lost keys problem, but causes a bunch of other issues instead.

According to Raymond Chen

Creating a cross-thread parent/child or owner/owned window relationship implicitly attaches the input queues of the threads which those windows belong to...

We interpret this like AttachThreadInput is called 'under the hood', but do not fully understand what causes keypresses to be lost. Is it some sort of thread-safety issue? A race condition?

By using the AttachThreadInput function, a thread can share its input states (such as keyboard states and the current focus window) with another thread. Keyboard and mouse events received by both threads are processed in the order they were received until the threads are detached by calling AttachThreadInput a second time and specifying FALSE for the fAttach parameter.

We have used Spy++ to monitor the Windows messages that gets sent to the WPF process and it seems that when you type slowly, WM_KEYDOWN is sent together with WM_CHAR. When the input is lost, we still receive the WM_KEYDOWN messages, but no WM_CHAR. This led us to start investigating the .NET framework source. Among other things, we found the following code in HwndSource.cs

 switch ((WindowMessage)msgdata.msg.message)
            {
            case WindowMessage.WM_SYSKEYDOWN:
            case WindowMessage.WM_KEYDOWN:
                // MITIGATION: HANDLED_KEYDOWN_STILL_GENERATES_CHARS
                // In case a nested message pump is used before we return
                // from processing this message, we disable processing the
                // next WM_CHAR message because if the code pumps messages
                // it should really mark the message as handled.
                _eatCharMessages = true;
                DispatcherOperation restoreCharMessages = Dispatcher.BeginInvoke(DispatcherPriority.Normal, new DispatcherOperationCallback(RestoreCharMessages), null);

                // Force the Dispatcher to post a new message to service any
                // pending operations, so that the operation we just posted
                // is guaranteed to get dispatched after any pending WM_CHAR
                // messages are dispatched.
                Dispatcher.CriticalRequestProcessing(true);

The variable named _eatCharMessages could perhaps be related, although debugging this code using dnSpy has not made us any wiser.

We're looking for a Win32-wizard to shed some more light on this. Anything that can point us in the right direction would be greatly appreciated. We need to figure out the root cause of  the problem in order to decide how to fix it.


来源: stackexchange

问:
search for excel files that contain a specific substring python rglob
I have a folder that has many subfolders (and those subfolders might have their own subfolders).

What I am trying to achieve is when I am in the main folder and search "survey" in File Explorer, its filters and pulls those matches.

I want excel files from all folders/subfolders/...etc.. that contain "survey" in the filename.

So far I have this, which filters for excel files:

```<code>[item for item in ae_data.rglob("*.xlsx") if item.is_file()]
</code>```

But I cant figure out how to do something like .contains('survey')

ContentLicense: CC BY-SA 4.0

Body:
I have a folder that has many subfolders (and those subfolders might have their own subfolders).

What I am trying to achieve is when I am in the main folder and search "survey" in File Explorer, its filters and pulls those matches.

I want excel files from all folders/subfolders/...etc.. that contain "survey" in the filename.

So far I have this, which filters for excel files:

[item for item in ae_data.rglob("*.xlsx") if item.is_file()]

But I cant figure out how to do something like .contains('survey')


问:
How can I create PPT readable XML from JavaScript (browser)?
I have an app where users create designs that they can then export to SVG via JS.

Unfortunately, SVG is mostly incompatible with PPT and I need to create a separate export format.

How should I export graphical data to a PowerPoint format?
I tried pptxgenjs, but there isn't enough flexibility there.

Is there a single XML file I can export (similar to SVG) that is readable by powerpoint?


问:
g++ static linking gives /usr/bin/ld: cannot find <lib name>
using g++ version :

```<code>g++ --version
g++ (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0
Copyright (C) 2017 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
</code>```

the lib is in path that is passed with "-L":

```<code>vagrant@vagrant:~/cpp/batch$ ls -l /home/vagrant/cpp/libhv/build/lib/
total 34988
-rwxrwxr-x 1 vagrant vagrant  9376136 Dec 29 09:23 libhv.so
-rw-rw-r-- 1 vagrant vagrant 26446694 Dec 29 09:24 libhv_static.a
</code>```

The errors -llibhv_static:

```<code>g++ -fdiagnostics-color=always -Wall -I/home/vagrant/cpp/batch/ -I/home/vagrant/cpp/libhv/build/include/hv/ -std=c++14  -L/home/vagrant/cpp/libhv/build/lib/ -llibhv_static -pthread -g /home/vagrant/cpp/batch/main.cpp -o /home/vagrant/cpp/batch/main.exe
/usr/bin/ld: cannot find -llibhv_static
collect2: error: ld returned 1 exit status
</code>```

with -lhv_static.a

```<code>g++ -fdiagnostics-color=always -Wall -I/home/vagrant/cpp/batch/ -I/home/vagrant/cpp/libhv/build/include/hv/ -std=c++14  -L/home/vagrant/cpp/libhv/build/lib/ -lhv_static.a -pthread -g /home/vagrant/cpp/batch/main.cpp -o /home/vagrant/cpp/batch/main.exe
/usr/bin/ld: cannot find -lhv_static.a
collect2: error: ld returned 1 exit status
</code>```

and with -lhv_static

```<code>g++ -fdiagnostics-color=always -Wall -I/home/vagrant/cpp/batch/ -I/home/vagrant/cpp/libhv/build/include/hv/ -std=c++14  -L/home/vagrant/cpp/libhv/build/lib/ -lhv_static -pthread -g /home/vagrant/cpp/batch/main.cpp -o /home/vagrant/cpp/batch/main.exe
/tmp/ccvMCMRx.o: In function `hv_memcheck':
/home/vagrant/cpp/libhv/build/include/hv/hbase.h:54: undefined reference to `hv_free_cnt'
/home/vagrant/cpp/libhv/build/include/hv/hbase.h:54: undefined reference to `hv_alloc_cnt'
/tmp/ccvMCMRx.o: In function `main':
/home/vagrant/cpp/batch/main.cpp:40: undefined reference to `http_server_run(http_server_s*, int)'
/home/vagrant/cpp/batch/main.cpp:51: undefined reference to `http_server_stop(http_server_s*)'
collect2: error: ld returned 1 exit status
</code>```

Body:
using g++ version :

g++ --version
g++ (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0
Copyright (C) 2017 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

the lib is in path that is passed with "-L":

vagrant@vagrant:~/cpp/batch$ ls -l /home/vagrant/cpp/libhv/build/lib/
total 34988
-rwxrwxr-x 1 vagrant vagrant  9376136 Dec 29 09:23 libhv.so
-rw-rw-r-- 1 vagrant vagrant 26446694 Dec 29 09:24 libhv_static.a

The errors -llibhv_static:

g++ -fdiagnostics-color=always -Wall -I/home/vagrant/cpp/batch/ -I/home/vagrant/cpp/libhv/build/include/hv/ -std=c++14  -L/home/vagrant/cpp/libhv/build/lib/ -llibhv_static -pthread -g /home/vagrant/cpp/batch/main.cpp -o /home/vagrant/cpp/batch/main.exe
/usr/bin/ld: cannot find -llibhv_static
collect2: error: ld returned 1 exit status

with -lhv_static.a

g++ -fdiagnostics-color=always -Wall -I/home/vagrant/cpp/batch/ -I/home/vagrant/cpp/libhv/build/include/hv/ -std=c++14  -L/home/vagrant/cpp/libhv/build/lib/ -lhv_static.a -pthread -g /home/vagrant/cpp/batch/main.cpp -o /home/vagrant/cpp/batch/main.exe
/usr/bin/ld: cannot find -lhv_static.a
collect2: error: ld returned 1 exit status

and with -lhv_static

g++ -fdiagnostics-color=always -Wall -I/home/vagrant/cpp/batch/ -I/home/vagrant/cpp/libhv/build/include/hv/ -std=c++14  -L/home/vagrant/cpp/libhv/build/lib/ -lhv_static -pthread -g /home/vagrant/cpp/batch/main.cpp -o /home/vagrant/cpp/batch/main.exe
/tmp/ccvMCMRx.o: In function `hv_memcheck':
/home/vagrant/cpp/libhv/build/include/hv/hbase.h:54: undefined reference to `hv_free_cnt'
/home/vagrant/cpp/libhv/build/include/hv/hbase.h:54: undefined reference to `hv_alloc_cnt'
/tmp/ccvMCMRx.o: In function `main':
/home/vagrant/cpp/batch/main.cpp:40: undefined reference to `http_server_run(http_server_s*, int)'
/home/vagrant/cpp/batch/main.cpp:51: undefined reference to `http_server_stop(http_server_s*)'
collect2: error: ld returned 1 exit status


问:
C# Linq to EF Separate Subquery into Expression
I have a complex where clause in my EF linq statement which repeats a subquery expression, on _db.OPESRRecoveryElements, but with different parameters, one of which is depending on records from the main entity, OPCases/OPCaseDto.

The query as it is works, but its hard for people to read. Ideally I'd like to be able to create an expression which could be re-used at the 3 necessary points and would still allow it to execute as a single, server-side SQL statement.

Is there a way to create an Expression / IQueryable definition which can be used for a subquery like this?

```<code>List<OPCaseDto> opCases = await _db.OPCases
  .ProjectTo<OPCaseDto>(_autoMapperConfig, null, requestedExpands)
  .Where(c =>
      c.OPStatusId == OPStatusIds.AwaitingRecoveryElement
      && (
          (c.OPCategoryLetter == "B"
              // Only need a gross pensionable element if there is an outstanding gross pensionable figure
              && (c.GrossOverpaidPensionable - c.GrossRecoveredPensionable == 0
                  || _db.OPESRRecoveryElements.Any(e => !e.NonPensionable && e.OPRecoveryMethod.OPTypeLetter == "G"
                      && !e.OPRecoveryPlans.Any(rp
                      => (rp.RecoveryStatus == OPRecoveryStatuses.NotStarted || rp.RecoveryStatus == OPRecoveryStatuses.InRecovery)
                      && rp.AssignmentNo == c.RecoveryAssignmentNo)))
              // Only need a gross non-pensionable element if there is an outstanding gross non-pensionable figure
              && (c.GrossOverpaidNonPensionable - c.GrossRecoveredNonPensionable == 0
                  || _db.OPESRRecoveryElements.Any(e => e.NonPensionable && e.OPRecoveryMethod.OPTypeLetter == "G"
                      && !e.OPRecoveryPlans.Any(rp
                      => (rp.RecoveryStatus == OPRecoveryStatuses.NotStarted || rp.RecoveryStatus == OPRecoveryStatuses.InRecovery)
                      && rp.AssignmentNo == c.RecoveryAssignmentNo))))
      || (c.OPCategoryLetter == "D"
          // Don't need to check for an outstanding net figure - if the case is net and isn't complete, there will be one!
          && _db.OPESRRecoveryElements.Any(e => e.OPRecoveryMethod.OPTypeLetter == "N"
              && !e.OPRecoveryPlans.Any(rp
                  => (rp.RecoveryStatus == OPRecoveryStatuses.NotStarted || rp.RecoveryStatus == OPRecoveryStatuses.InRecovery)
                  && rp.AssignmentNo == c.RecoveryAssignmentNo)))
      )
  )
  .AsNoTracking()
  .ToListAsync();
</code>```

If it wasn't for the c.RecoveryAssignmentNo part, I could easily create an expression like:

```<code>public Expression<Func<OPESRRecoveryElement, bool>> NoActiveRecoveryPlans(string opType, bool nonPen)
{
    return e => e.OPRecoveryMethod.OPTypeLetter == opType
        && e.NonPensionable == nonPen
        && !e.OPRecoveryPlans.Any(rp
            => (rp.RecoveryStatus == OPRecoveryStatuses.NotStarted || rp.RecoveryStatus == OPRecoveryStatuses.InRecovery));
}
</code>```

and use it like:

```<code>(c.OPCategoryLetter == "B"
    // Only need a gross pensionable element if there is an outstanding gross pensionable figure
    && (c.GrossOverpaidPensionable - c.GrossRecoveredPensionable == 0
        || _db.OPESRRecoveryElements.Any(NoActiveRecoveryPlans("G", false)))
</code>```

and it would get executed before the query to get the OPCases.

I could also fetch all the OPCaseDto records and OPESRRecoveryElements as separate queries and filter in memory, but I don't want to do that.

If I add a parameter to the function, string assignmentNo, I (unsurprisingly) get an error -  "Unable to cast object of type 'System.Linq.Expressions.InstanceMethodCallExpression3' to type 'System.Linq.Expressions.LambdaExpression'"

Body:
I have a complex where clause in my EF linq statement which repeats a subquery expression, on _db.OPESRRecoveryElements, but with different parameters, one of which is depending on records from the main entity, OPCases/OPCaseDto.

The query as it is works, but its hard for people to read. Ideally I'd like to be able to create an expression which could be re-used at the 3 necessary points and would still allow it to execute as a single, server-side SQL statement.

Is there a way to create an Expression / IQueryable definition which can be used for a subquery like this?

List<OPCaseDto> opCases = await _db.OPCases
  .ProjectTo<OPCaseDto>(_autoMapperConfig, null, requestedExpands)
  .Where(c =>
      c.OPStatusId == OPStatusIds.AwaitingRecoveryElement
      && (
          (c.OPCategoryLetter == "B"
              // Only need a gross pensionable element if there is an outstanding gross pensionable figure
              && (c.GrossOverpaidPensionable - c.GrossRecoveredPensionable == 0
                  || _db.OPESRRecoveryElements.Any(e => !e.NonPensionable && e.OPRecoveryMethod.OPTypeLetter == "G"
                      && !e.OPRecoveryPlans.Any(rp
                      => (rp.RecoveryStatus == OPRecoveryStatuses.NotStarted || rp.RecoveryStatus == OPRecoveryStatuses.InRecovery)
                      && rp.AssignmentNo == c.RecoveryAssignmentNo)))
              // Only need a gross non-pensionable element if there is an outstanding gross non-pensionable figure
              && (c.GrossOverpaidNonPensionable - c.GrossRecoveredNonPensionable == 0
                  || _db.OPESRRecoveryElements.Any(e => e.NonPensionable && e.OPRecoveryMethod.OPTypeLetter == "G"
                      && !e.OPRecoveryPlans.Any(rp
                      => (rp.RecoveryStatus == OPRecoveryStatuses.NotStarted || rp.RecoveryStatus == OPRecoveryStatuses.InRecovery)
                      && rp.AssignmentNo == c.RecoveryAssignmentNo))))
      || (c.OPCategoryLetter == "D"
          // Don't need to check for an outstanding net figure - if the case is net and isn't complete, there will be one!
          && _db.OPESRRecoveryElements.Any(e => e.OPRecoveryMethod.OPTypeLetter == "N"
              && !e.OPRecoveryPlans.Any(rp
                  => (rp.RecoveryStatus == OPRecoveryStatuses.NotStarted || rp.RecoveryStatus == OPRecoveryStatuses.InRecovery)
                  && rp.AssignmentNo == c.RecoveryAssignmentNo)))
      )
  )
  .AsNoTracking()
  .ToListAsync();

If it wasn't for the c.RecoveryAssignmentNo part, I could easily create an expression like:

public Expression<Func<OPESRRecoveryElement, bool>> NoActiveRecoveryPlans(string opType, bool nonPen)
{
    return e => e.OPRecoveryMethod.OPTypeLetter == opType
        && e.NonPensionable == nonPen
        && !e.OPRecoveryPlans.Any(rp
            => (rp.RecoveryStatus == OPRecoveryStatuses.NotStarted || rp.RecoveryStatus == OPRecoveryStatuses.InRecovery));
}

and use it like:

(c.OPCategoryLetter == "B"
    // Only need a gross pensionable element if there is an outstanding gross pensionable figure
    && (c.GrossOverpaidPensionable - c.GrossRecoveredPensionable == 0
        || _db.OPESRRecoveryElements.Any(NoActiveRecoveryPlans("G", false)))

and it would get executed before the query to get the OPCases.

I could also fetch all the OPCaseDto records and OPESRRecoveryElements as separate queries and filter in memory, but I don't want to do that.

If I add a parameter to the function, string assignmentNo, I (unsurprisingly) get an error -  "Unable to cast object of type 'System.Linq.Expressions.InstanceMethodCallExpression3' to type 'System.Linq.Expressions.LambdaExpression'"


问:
MLFLOW UnicodeDecodeError: 'utf-8' codec error while logging the model
I am trying to log a model with MLflow but each time i get the following warning. The debug mode have been activated to have a more verbose warning.

```<code>2023/01/09 18:17:50 WARNING mlflow.utils.environment: Encountered an unexpected error while inferring pip requirements (model URI: C:\Users\XXXX\AppData\Local\Temp\tmp25zp2aqv\model\model.pkl, flavor: sklearn), fall back to return ['scikit-learn==1.0.2', 'cloudpickle==2.1.0']. Set logging level to DEBUG to see the full traceback.
2023/01/09 18:17:50 DEBUG mlflow.utils.environment:
Traceback (most recent call last):
  File "D:\_verse\test_mlflow\lib\site-packages\mlflow\utils\environment.py", line 378, in infer_pip_requirements
    return _infer_requirements(model_uri, flavor)
  File "D:\_verse\test_mlflow\lib\site-packages\mlflow\utils\requirements_utils.py", line 345, in _infer_requirements
    modules = _capture_imported_modules(model_uri, flavor)
  File "D:\_verse\test_mlflow\lib\site-packages\mlflow\utils\requirements_utils.py", line 277, in _capture_imported_modules
    json.dumps(sys.path),
  File "D:\_verse\test_mlflow\lib\site-packages\mlflow\utils\requirements_utils.py", line 208, in _run_command
    stderr = stderr.decode("utf-8")
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 472: invalid continuation byte
</code>```

Here is a part of the code :

```<code>
####======= mlflow store =======####
with mlflow.start_run():

    print("Elasticnet model (alpha=%f, l1_ratio=%f):" % (alpha, l1_ratio))
    print("  RMSE: %s" % rmse)
    print("  MAE: %s" % mae)
    print("  R2: %s" % r2)
    print("\n")

    # Parameters logging
    for i in model_parameters:
        mlflow.log_param(get_variable_name(i), i)

    # Metrics logging
    for i in model_metrics:
        mlflow.log_metric(get_variable_name(i), i)

    tracking_url_type_store = urlparse(mlflow.get_tracking_uri()).scheme

    print(f"URL type store : {tracking_url_type_store}\n")

    # Model registry does not work with file store
    if tracking_url_type_store != "file":
        mlflow.sklearn.log_model(lr, "model", registered_model_name="ElasticnetWineModel")
    else:
        mlflow.sklearn.log_model(lr, "model")

# Users informations
print(f"\nAll the data have been stored there : {mlflow.get_tracking_uri()}")
print("\n========== End of local run ==========")
print("==========   %s seconds   ==========" % round((time.time() - start_time),2))
</code>```

If somebody can give any advices, it would be nice :)

Body:
I am trying to log a model with MLflow but each time i get the following warning. The debug mode have been activated to have a more verbose warning.

2023/01/09 18:17:50 WARNING mlflow.utils.environment: Encountered an unexpected error while inferring pip requirements (model URI: C:\Users\XXXX\AppData\Local\Temp\tmp25zp2aqv\model\model.pkl, flavor: sklearn), fall back to return ['scikit-learn==1.0.2', 'cloudpickle==2.1.0']. Set logging level to DEBUG to see the full traceback.
2023/01/09 18:17:50 DEBUG mlflow.utils.environment:
Traceback (most recent call last):
  File "D:\_verse\test_mlflow\lib\site-packages\mlflow\utils\environment.py", line 378, in infer_pip_requirements
    return _infer_requirements(model_uri, flavor)
  File "D:\_verse\test_mlflow\lib\site-packages\mlflow\utils\requirements_utils.py", line 345, in _infer_requirements
    modules = _capture_imported_modules(model_uri, flavor)
  File "D:\_verse\test_mlflow\lib\site-packages\mlflow\utils\requirements_utils.py", line 277, in _capture_imported_modules
    json.dumps(sys.path),
  File "D:\_verse\test_mlflow\lib\site-packages\mlflow\utils\requirements_utils.py", line 208, in _run_command
    stderr = stderr.decode("utf-8")
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 472: invalid continuation byte

Here is a part of the code :

####======= mlflow store =======####
with mlflow.start_run():

    print("Elasticnet model (alpha=%f, l1_ratio=%f):" % (alpha, l1_ratio))
    print("  RMSE: %s" % rmse)
    print("  MAE: %s" % mae)
    print("  R2: %s" % r2)
    print("\n")

    # Parameters logging
    for i in model_parameters:
        mlflow.log_param(get_variable_name(i), i)

    # Metrics logging
    for i in model_metrics:
        mlflow.log_metric(get_variable_name(i), i)

    tracking_url_type_store = urlparse(mlflow.get_tracking_uri()).scheme

    print(f"URL type store : {tracking_url_type_store}\n")

    # Model registry does not work with file store
    if tracking_url_type_store != "file":
        mlflow.sklearn.log_model(lr, "model", registered_model_name="ElasticnetWineModel")
    else:
        mlflow.sklearn.log_model(lr, "model")

# Users informations
print(f"\nAll the data have been stored there : {mlflow.get_tracking_uri()}")
print("\n========== End of local run ==========")
print("==========   %s seconds   ==========" % round((time.time() - start_time),2))

If somebody can give any advices, it would be nice :)


问:
Can I have scss and a css loader at the same time to support different assets?
I have a legacy project with .scss files, so in webpack.config.js I use:

```<code>            {
            test: /\.scss$/,
            use: [
                mode === 'production'? MiniCssExtractPlugin.loader : 'style-loader',
                'css-loader',
                'postcss-loader',
                'sass-loader',
            ],
        }
</code>```

Now I have a requirement to integrate another huge project inside, which has .css files instead.

In order to support the new added files, should I add a new loader in the webpack.config.js or should I modify the test field and put test: /\.s?css$/ ?

Body:
I have a legacy project with .scss files, so in webpack.config.js I use:

            {
            test: /\.scss$/,
            use: [
                mode === 'production'? MiniCssExtractPlugin.loader : 'style-loader',
                'css-loader',
                'postcss-loader',
                'sass-loader',
            ],
        }

Now I have a requirement to integrate another huge project inside, which has .css files instead.

In order to support the new added files, should I add a new loader in the webpack.config.js or should I modify the test field and put test: /\.s?css$/ ?


问:
Foreign key is not saving the data in the table
I am using the sequelize-typescript package and postgresql as a database. I am building a chat app and I want to save the sendBy field in the chat's table where the id will be the users id (primary key from the users table)

Here is the chat.dto.ts file code:

```<code>export class CreateChatDto implements IChat {
  @IsNotEmpty()
  message: string | undefined;

  @IsNotEmpty()
  @IsInt()
  sendby: number | undefined;
}
</code>```

The controller file:

```<code>@Controller('chat')
@SerializeOptions({
  groups: extendedChatGroupsForSerializing,
})
export class ChatController {
  constructor(private readonly chatService: ChatServices) {}
@Post()
  async createChat(@Body() createChatData: CreateChatDto, @Req() req: any) {
    try {
      const user = req.user;
      createChatData.sendby = user.id as number;
      const newDoc = await this.chatService.create(createChatData);
      return utils.sendSuccess(SUCCESS.S200.DEFAULT, newDoc);
    } catch (error) {
      throw new SpecificExceptionFilter(error.parent.detail);
    }
  }
}
</code>```

The create method in the service file:

```<code>async create(chat: CreateChatDto): Promise<Chat> {
    return await this.chatRepository.create<Chat>(chat as Chat);
  }
</code>```

The chat.entity file:

```<code>@Table({
  tableName: 'netabe_chatData',
})
@ObjectType()
export class Chat extends Model<IChat> {
  @Field(() => Number, { description: 'ID of the ChatData' })
  declare id: number;

  @Column({
    type: DataType.STRING,
  })
  @Field(() => String, { description: 'Chat message' })
  message: string;

  @ForeignKey(() => User)
  @Column({
    type: DataType.NUMBER,
  })
  @Field(() => Number, { description: 'Message send by' })
  sendby: number;

  @BelongsTo(() => User)
  user: User;
}
</code>```

So I do not understand what could be wrong here. Whenever I send message from postman it says:

```<code>"message": [
        "sendby must be an integer number",
        "sendby should not be empty"
    ],
</code>```

although I am getting the value for sendby and the value is also a number but my request is not even reaching the controller.

Body:
I am using the sequelize-typescript package and postgresql as a database. I am building a chat app and I want to save the sendBy field in the chat's table where the id will be the users id (primary key from the users table)

Here is the chat.dto.ts file code:

export class CreateChatDto implements IChat {
  @IsNotEmpty()
  message: string | undefined;

  @IsNotEmpty()
  @IsInt()
  sendby: number | undefined;
}

The controller file:

@Controller('chat')
@SerializeOptions({
  groups: extendedChatGroupsForSerializing,
})
export class ChatController {
  constructor(private readonly chatService: ChatServices) {}
@Post()
  async createChat(@Body() createChatData: CreateChatDto, @Req() req: any) {
    try {
      const user = req.user;
      createChatData.sendby = user.id as number;
      const newDoc = await this.chatService.create(createChatData);
      return utils.sendSuccess(SUCCESS.S200.DEFAULT, newDoc);
    } catch (error) {
      throw new SpecificExceptionFilter(error.parent.detail);
    }
  }
}

The create method in the service file:

async create(chat: CreateChatDto): Promise<Chat> {
    return await this.chatRepository.create<Chat>(chat as Chat);
  }

The chat.entity file:

@Table({
  tableName: 'netabe_chatData',
})
@ObjectType()
export class Chat extends Model<IChat> {
  @Field(() => Number, { description: 'ID of the ChatData' })
  declare id: number;

  @Column({
    type: DataType.STRING,
  })
  @Field(() => String, { description: 'Chat message' })
  message: string;

  @ForeignKey(() => User)
  @Column({
    type: DataType.NUMBER,
  })
  @Field(() => Number, { description: 'Message send by' })
  sendby: number;

  @BelongsTo(() => User)
  user: User;
}

So I do not understand what could be wrong here. Whenever I send message from postman it says:

"message": [
        "sendby must be an integer number",
        "sendby should not be empty"
    ],

although I am getting the value for sendby and the value is also a number but my request is not even reaching the controller.


问:
Linear regression is not returning all of my coefficients from my 'Team' column or category
I want to look at the coefficient estimates for all of my different sales teams. I have 20 teams listed in a "Teams" column and about 24 observations for each. However, when I run my regression, I am only seeing 15 of the 20 teams in my model summary. I want to see all of them, any thoughts?

Here is my code and output:

(log_teams <- lm(Worked ~ Team+Activity+Presented+Confirmed+Jobs_Filled+Converted,  data = df))%>%
  summary
```
<p>Output:</p>
<pre class="lang-r prettyprint-override"><code>Call:
lm(formula = Worked ~ Team + Activity + Presented + Confirmed +
    Jobs_Filled + Converted, data = WBY)

Residuals:
    Min      1Q  Median      3Q     Max
-4.4035 -1.0048  0.0000  0.8774  5.1677
Coefficients:
             Estimate Std. Error t value Pr(>|t|)
(Intercept)  2.609486   1.869903   1.396   0.1699
TeamCRW      0.110828   1.908735   0.058   0.9540
TeamEMW     -1.068797   2.767863  -0.386   0.7013
TeamGSW     -0.424508   2.795353  -0.152   0.8800
TeamNS2     -1.234508   2.388392  -0.517   0.6078
TeamNUW     -1.458735   2.083549  -0.700   0.4875
TeamOBW      3.224057   2.103054   1.533   0.1324
TeamORT     -0.432185   1.884824  -0.229   0.8197
TeamPC1      4.338479   2.115219   2.051   0.0462 *
TeamPC2     -1.002268   2.227166  -0.450   0.6549
TeamPDW      2.560784   2.791501   0.917   0.3640
TeamPLW      1.381216   2.151150   0.642   0.5242
TeamPYW     -1.074374   2.799772  -0.384   0.7030
TeamSB2     -0.646769   2.288132  -0.283   0.7788
TeamSYW      2.252061   1.833820   1.228   0.2259
TeamWMO      0.857452   2.302522   0.372   0.7114
Activity    -0.000627   0.002906  -0.216   0.8302
Presented    0.162181   0.331876   0.489   0.6275
Confirmed   -0.242462   0.317139  -0.765   0.4486
Jobs_Filled -0.025657   0.016099  -1.594   0.1182
Converted    0.006213   0.002610   2.381   0.0217 *
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 2.247 on 44 degrees of freedom
  (427 observations deleted due to missingness)
Multiple R-squared:  0.5217,    Adjusted R-squared:  0.3043
F-statistic:   2.4 on 20 and 44 DF,  p-value: 0.007786*
</code>```

Body:
I want to look at the coefficient estimates for all of my different sales teams. I have 20 teams listed in a "Teams" column and about 24 observations for each. However, when I run my regression, I am only seeing 15 of the 20 teams in my model summary. I want to see all of them, any thoughts?

Here is my code and output:

(log_teams <- lm(Worked ~ Team+Activity+Presented+Confirmed+Jobs_Filled+Converted,  data = df))%>%
  summary

Output:

Call:
lm(formula = Worked ~ Team + Activity + Presented + Confirmed +
    Jobs_Filled + Converted, data = WBY)

Residuals:
    Min      1Q  Median      3Q     Max
-4.4035 -1.0048  0.0000  0.8774  5.1677
Coefficients:
             Estimate Std. Error t value Pr(>|t|)
(Intercept)  2.609486   1.869903   1.396   0.1699
TeamCRW      0.110828   1.908735   0.058   0.9540
TeamEMW     -1.068797   2.767863  -0.386   0.7013
TeamGSW     -0.424508   2.795353  -0.152   0.8800
TeamNS2     -1.234508   2.388392  -0.517   0.6078
TeamNUW     -1.458735   2.083549  -0.700   0.4875
TeamOBW      3.224057   2.103054   1.533   0.1324
TeamORT     -0.432185   1.884824  -0.229   0.8197
TeamPC1      4.338479   2.115219   2.051   0.0462 *
TeamPC2     -1.002268   2.227166  -0.450   0.6549
TeamPDW      2.560784   2.791501   0.917   0.3640
TeamPLW      1.381216   2.151150   0.642   0.5242
TeamPYW     -1.074374   2.799772  -0.384   0.7030
TeamSB2     -0.646769   2.288132  -0.283   0.7788
TeamSYW      2.252061   1.833820   1.228   0.2259
TeamWMO      0.857452   2.302522   0.372   0.7114
Activity    -0.000627   0.002906  -0.216   0.8302
Presented    0.162181   0.331876   0.489   0.6275
Confirmed   -0.242462   0.317139  -0.765   0.4486
Jobs_Filled -0.025657   0.016099  -1.594   0.1182
Converted    0.006213   0.002610   2.381   0.0217 *
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 2.247 on 44 degrees of freedom
  (427 observations deleted due to missingness)
Multiple R-squared:  0.5217,    Adjusted R-squared:  0.3043
F-statistic:   2.4 on 20 and 44 DF,  p-value: 0.007786*


问:
I'm not able to use awsume even after installation in WSL
I am using WSL in windows 10. I want to use awsume in wsl-ubuntu.
The installation was done using pip.
But the awsume command give the following error:

```<code>
Warning: the awsume shell script is not being sourced, please use awsume-configure to install the alias
/mnt/c/Users/My Name/AppData/Local/Programs/Python/Python38/Scripts/awsume: line 8: awsumepy: command not found
/mnt/c/Users/My Name/AppData/Local/Programs/Python/Python38/Scripts/awsume: line 183: return: can only `return' from a function or sourced script
</code>```

I've configured aws in wsl again. I guess the .aws directory in wsl points to .aws in windows. But after installing aws-cli in wsl-ubuntu again, the local installation points to /usr/local/bin/aws

Tried using hash awsume to fix the issue, but it didn't work
Any other fixes

Body:
I am using WSL in windows 10. I want to use awsume in wsl-ubuntu.
The installation was done using pip.
But the awsume command give the following error:

Warning: the awsume shell script is not being sourced, please use awsume-configure to install the alias
/mnt/c/Users/My Name/AppData/Local/Programs/Python/Python38/Scripts/awsume: line 8: awsumepy: command not found
/mnt/c/Users/My Name/AppData/Local/Programs/Python/Python38/Scripts/awsume: line 183: return: can only `return' from a function or sourced script

I've configured aws in wsl again. I guess the .aws directory in wsl points to .aws in windows. But after installing aws-cli in wsl-ubuntu again, the local installation points to /usr/local/bin/aws

Tried using hash awsume to fix the issue, but it didn't work
Any other fixes


问:
String converted to object when wrapped with brackets -
I've seen this example but cant find any docs as to why this happens. wrapping the const in brackets creates an object like below. can anyone enlighten me</p>
```<code>const test = "some text"

console.log({test})

{test: 'some text'}
</code>```

Body:
I've seen this example but cant find any docs as to why this happens. wrapping the const in brackets creates an object like below. can anyone enlighten me

const test = "some text"

console.log({test})

{test: 'some text'}


问:
How to properly dockerize a mobile application?
I am currently trying to have a dockerfile which will containerize my mobile application.
Inside the dockerfile, I would like to run ./gradlew assembleDebug.
I believe I properly installed the SDKs as the ./gradlew assembleDebug does get executed, but it does not succeed.
Many of the dependencies to get installed properly.
Unfortunately, the build fails when arriving at the dependency of react-native-webview.
It fails with the following error:

```<code>FAILURE: Build failed with an exception.
#30 288.9
#30 288.9 * What went wrong:
#30 288.9 Could not determine the dependencies of task ':app:compileVldDebugJavaWithJavac'.
#30 288.9 > Could not resolve all dependencies for configuration ':app:vldDebugRuntimeClasspath'.
#30 288.9    > Could not create task ':app:generateCfDebugLintModel'.
#30 288.9       > java.lang.NullPointerException (no error message)
</code>```

I have tried my hardest to debug the issue, but I can't seem to find what even the task compileVldDebugJavaWithJavac is online, and I can't seem to find what dependencies I might be missing. This is what my dockerfile looks like:

```<code>FROM gradle:7.3.2-jdk11

# Install Android SDK
RUN apt-get update && apt-get install -y wget
RUN apt-get update && apt-get install -y unzip
# https://dl.google.com/android/repository/commandlinetools-linux-6514223_latest.zip
RUN wget https://dl.google.com/android/repository/commandlinetools-linux-6514223_latest.zip -O android-sdk.zip \
    && unzip android-sdk.zip -d /opt/android-sdk \
    && rm android-sdk.zip

# Set the ANDROID_SDK_ROOT environment variable
ENV ANDROID_SDK_ROOT=/opt/android-sdk
ENV ANDROID_HOME=/opt/android-sdk
ENV PATH="$PATH:$ANDROID_SDK_ROOT/cmdline-tools/tools/bin"

# Accept licenses
#RUN yes | sdkmanager --licenses
RUN chmod 777 /root

#Get NPM
RUN apt-get update && apt-get install -y nodejs npm
RUN npm install semver

RUN yes Y | sdkmanager --install "build-tools;31.0.0" "platforms;android-31" "platform-tools" "ndk;24.0.8215888"
ENV PATH="$PATH:$ANDROID_SDK_ROOT/platform-tools"
ENV PATH="$PATH:$ANDROID_SDK_ROOT/tools"
ENV PATH="$PATH:$ANDROID_SDK_ROOT/emulator"
RUN npm install --location=global @wdio/cli
RUN npm install --location=global appium
RUN chmod 777 /root
RUN npm install --location=global react-devtools

#Install essentials
RUN apt-get update && apt-get install build-essential -y \
    && apt-get install file -y \
    && apt-get install apt-utils -y

#See if we can run a gradlew command to build the APK
WORKDIR /project

# Copy the project files, including the gradlew script
COPY . .

WORKDIR /project/android

# Make the gradlew script executable
RUN chmod +x gradlew
#RUN ./gradlew clean
RUN ./gradlew assembleDebug
</code>```

I am running locally on a Mac, and the build does work fine. My idea was to copy the full project onto a docker container and do the same build there and I would expect it to work, but it does not. I have tried running ./gradlew clean as well with no luck, and I have tried countless other references in order to try to succeed.
I have seen examples with JDK 8, but I need JDK 11 for my build, and it somehow makes the task that much harder?
Has anyone run in the same issue? Would anyone have any pointers please?

Body:
I am currently trying to have a dockerfile which will containerize my mobile application.
Inside the dockerfile, I would like to run ./gradlew assembleDebug.
I believe I properly installed the SDKs as the ./gradlew assembleDebug does get executed, but it does not succeed.
Many of the dependencies to get installed properly.
Unfortunately, the build fails when arriving at the dependency of react-native-webview.
It fails with the following error:

FAILURE: Build failed with an exception.
#30 288.9
#30 288.9 * What went wrong:
#30 288.9 Could not determine the dependencies of task ':app:compileVldDebugJavaWithJavac'.
#30 288.9 > Could not resolve all dependencies for configuration ':app:vldDebugRuntimeClasspath'.
#30 288.9    > Could not create task ':app:generateCfDebugLintModel'.
#30 288.9       > java.lang.NullPointerException (no error message)

I have tried my hardest to debug the issue, but I can't seem to find what even the task compileVldDebugJavaWithJavac is online, and I can't seem to find what dependencies I might be missing. This is what my dockerfile looks like:

FROM gradle:7.3.2-jdk11

# Install Android SDK
RUN apt-get update && apt-get install -y wget
RUN apt-get update && apt-get install -y unzip
# https://dl.google.com/android/repository/commandlinetools-linux-6514223_latest.zip
RUN wget https://dl.google.com/android/repository/commandlinetools-linux-6514223_latest.zip -O android-sdk.zip \
    && unzip android-sdk.zip -d /opt/android-sdk \
    && rm android-sdk.zip

# Set the ANDROID_SDK_ROOT environment variable
ENV ANDROID_SDK_ROOT=/opt/android-sdk
ENV ANDROID_HOME=/opt/android-sdk
ENV PATH="$PATH:$ANDROID_SDK_ROOT/cmdline-tools/tools/bin"

# Accept licenses
#RUN yes | sdkmanager --licenses
RUN chmod 777 /root

#Get NPM
RUN apt-get update && apt-get install -y nodejs npm
RUN npm install semver

RUN yes Y | sdkmanager --install "build-tools;31.0.0" "platforms;android-31" "platform-tools" "ndk;24.0.8215888"
ENV PATH="$PATH:$ANDROID_SDK_ROOT/platform-tools"
ENV PATH="$PATH:$ANDROID_SDK_ROOT/tools"
ENV PATH="$PATH:$ANDROID_SDK_ROOT/emulator"
RUN npm install --location=global @wdio/cli
RUN npm install --location=global appium
RUN chmod 777 /root
RUN npm install --location=global react-devtools

#Install essentials
RUN apt-get update && apt-get install build-essential -y \
    && apt-get install file -y \
    && apt-get install apt-utils -y

#See if we can run a gradlew command to build the APK
WORKDIR /project

# Copy the project files, including the gradlew script
COPY . .

WORKDIR /project/android

# Make the gradlew script executable
RUN chmod +x gradlew
#RUN ./gradlew clean
RUN ./gradlew assembleDebug

I am running locally on a Mac, and the build does work fine. My idea was to copy the full project onto a docker container and do the same build there and I would expect it to work, but it does not. I have tried running ./gradlew clean as well with no luck, and I have tried countless other references in order to try to succeed.
I have seen examples with JDK 8, but I need JDK 11 for my build, and it somehow makes the task that much harder?
Has anyone run in the same issue? Would anyone have any pointers please?


问:
UNITY 2D Game lagging after switching apps or rerun
I've got almost finished 2D unity game, but witch huge problem. Every time I switch from game to home screen and get back to game, everything starts to lagg. First thing I did after that discovery was exit game and launch it again, but result is the same. Only thing that fix this problem is "force stop" app in the phone settings.
Then game runs smooth until exit or switch to other app...
I've tested app on old s7edge and there it runs really well, problem is on s20+ witch 120hz mode on. on 60hz works fine. I've tried custom main manifest option (Unity, problem with android build on 120hz devices) and it has been working fine until android update to 13.
I don't know if this is just exynos based problem, for now I have just those two phones for tests.
did anyone had similar problem?</p>


问:
How to pass a custom variable to styles file through 'withStyles'?
I'm trying to create a custom marquee component with a custom animation time prop, but i need to pass this prop to my styles file through withStyles function and i dont know how do it

This is how i did the component and how i used the styles

Marquee Component:

import React from 'react';
import { withStyles } from '@material-ui/core';
import styles from './MarqueeStyles';

const Marquee = ({ classes, children, animationTime }) => {
  return (

{children}

{children}

{children}

{children}

  );
};

export default withStyles(styles)(Marquee);
```
<p><strong>Styles file:</strong></p>
<pre class="lang-js prettyprint-override"><code>import { createStyles } from '@material-ui/core';

const styles = (theme) => {
  return createStyles({
    marquee: {
      ...someStyles

      '& .scroll': {
        animation: `$marqueeAnimation 30s linear infinite`,
      },
    },

    '@keyframes marqueeAnimation': {
      from: {
        transform: 'translateX(0)',
      },
      to: {
        transform: 'translateX(calc(-100% - 1rem))',
      },
    },
  });
};

export default styles;
</code>```

i want to do something like:

<Marquee animationTime="30s" />
```
<pre class="lang-js prettyprint-override"><code>import { createStyles } from '@material-ui/core';

const styles = ({theme, animationTime) => {
  return createStyles({
    marquee: {

      ...someStyles

      '& .scroll': {
        animation: `$marqueeAnimation ${animationTime} linear infinite`,
      },
    },

    '@keyframes marqueeAnimation': {
      from: {
        transform: 'translateX(0)',
      },
      to: {
        transform: 'translateX(calc(-100% - 1rem))',
      },
    },
  });
};

export default styles;
</code>```

Body:
I'm trying to create a custom marquee component with a custom animation time prop, but i need to pass this prop to my styles file through withStyles function and i dont know how do it

This is how i did the component and how i used the styles

Marquee Component:

import React from 'react';
import { withStyles } from '@material-ui/core';
import styles from './MarqueeStyles';

const Marquee = ({ classes, children, animationTime }) => {
  return (

{children}

{children}

{children}

{children}

  );
};

export default withStyles(styles)(Marquee);

Styles file:

import { createStyles } from '@material-ui/core';

const styles = (theme) => {
  return createStyles({
    marquee: {
      ...someStyles

      '& .scroll': {
        animation: `$marqueeAnimation 30s linear infinite`,
      },
    },

    '@keyframes marqueeAnimation': {
      from: {
        transform: 'translateX(0)',
      },
      to: {
        transform: 'translateX(calc(-100% - 1rem))',
      },
    },
  });
};

export default styles;

i want to do something like:

<Marquee animationTime="30s" />

import { createStyles } from '@material-ui/core';

const styles = ({theme, animationTime) => {
  return createStyles({
    marquee: {

      ...someStyles

      '& .scroll': {
        animation: `$marqueeAnimation ${animationTime} linear infinite`,
      },
    },

    '@keyframes marqueeAnimation': {
      from: {
        transform: 'translateX(0)',
      },
      to: {
        transform: 'translateX(calc(-100% - 1rem))',
      },
    },
  });
};

export default styles;


问:
Where should I define DB connections in Next.js 13? I am unable to call /pages/api files in React Server components
I am trying Next.js 13 and I am not actually sure where should I define my back end logic that is reused over multiple components because if I move the logic to to old /pages/api route then I am unable to call the server itself with this const members = await fetch('/api/members') as it returns following error:

```<code>at async /Users/<>/projects/node_modules/next/dist/server/app-render.js:1059:51 {
    input: '/api/members',
    code: 'ERR_INVALID_URL'
  }
</code>```

But based on Next.js 13 documentation, I should reuse same calls at the component level:

```<code>Good to know: For layouts, it's not possible to pass data between a parent layout and its children.
We recommend **fetching data directly inside the layout that needs it**, even if you're requesting the same data multiple times in a route.
Behind the scenes, React and Next.js will cache and dedupe requests to avoid the same data being fetched more than once.
</code>```

So should I just create some custom javascript object and totally forgot about using /api route or is there a way how to have all logic defined in /api and integrate with with React Server Components?

Body:
I am trying Next.js 13 and I am not actually sure where should I define my back end logic that is reused over multiple components because if I move the logic to to old /pages/api route then I am unable to call the server itself with this const members = await fetch('/api/members') as it returns following error:

at async /Users/<>/projects/node_modules/next/dist/server/app-render.js:1059:51 {
    input: '/api/members',
    code: 'ERR_INVALID_URL'
  }

But based on Next.js 13 documentation, I should reuse same calls at the component level:

Good to know: For layouts, it's not possible to pass data between a parent layout and its children.
We recommend **fetching data directly inside the layout that needs it**, even if you're requesting the same data multiple times in a route.
Behind the scenes, React and Next.js will cache and dedupe requests to avoid the same data being fetched more than once.

So should I just create some custom javascript object and totally forgot about using /api route or is there a way how to have all logic defined in /api and integrate with with React Server Components?


问:
DMS partioning tuning in S3 target
I'm pushing data from a RDS MySQL to S3. My S3 target endpoint have this settings:

```<code>{
  "CsvRowDelimiter": "\\n",
  "CsvDelimiter": ",",
  "AddColumnName": true,
  "CompressionType": "NONE",
  "EnableStatistics": true,
  "DatePartitionEnabled": true,
  "DatePartitionSequence": "YYYYMMDD",
  "DatePartitionDelimiter": "SLASH",
  "EncryptionMode": "SSE_KMS",
  "ServerSideEncryptionKmsKeyId": "XXXXX",
  "TimestampColumnName":"TIMESTAMP",
  "IncludeOpForFullLoad": true,
  "CdcInsertsOnly": false
}
</code>```

At the end my folder structure is looking like this:

```<code>-/
--/my_table_name
---LOAD00000001.csv
---/2023
----/01
-----/09
------20230109-165206632.csv
</code>```

I have two questions regarding settings without finding the answer:

Can we setup some prefix on the date folders? I want to follow Hive naming convention (.eg. /year=2023/month=01/day=09/)

Is this possible to have the initial load csv file not located at the root, but inside the date folders structure?

Title: DMS partioning tuning in S3 target

Body:
I'm pushing data from a RDS MySQL to S3. My S3 target endpoint have this settings:

{
  "CsvRowDelimiter": "\\n",
  "CsvDelimiter": ",",
  "AddColumnName": true,
  "CompressionType": "NONE",
  "EnableStatistics": true,
  "DatePartitionEnabled": true,
  "DatePartitionSequence": "YYYYMMDD",
  "DatePartitionDelimiter": "SLASH",
  "EncryptionMode": "SSE_KMS",
  "ServerSideEncryptionKmsKeyId": "XXXXX",
  "TimestampColumnName":"TIMESTAMP",
  "IncludeOpForFullLoad": true,
  "CdcInsertsOnly": false
}

At the end my folder structure is looking like this:

-/
--/my_table_name
---LOAD00000001.csv
---/2023
----/01
-----/09
------20230109-165206632.csv

I have two questions regarding settings without finding the answer:

Can we setup some prefix on the date folders? I want to follow Hive naming convention (.eg. /year=2023/month=01/day=09/)

Is this possible to have the initial load csv file not located at the root, but inside the date folders structure?


问:
spring Webclient and custom logger, how to keep context?
I call a REST api using Webclient

i am using a customized netty HTTPClient with a loggingHandler that I use to log my call. (I got it from here WebClient - how to get request body?)

```<code>@Slf4j
@Component
public class LoggingCustomizer implements WebClientCustomizer {

    @Override public void customize(WebClient.Builder webClientBuilder) {
        HttpClient httpClient = HttpClient.create()
            .doOnRequest((httpClientRequest, connection) -> connection.addHandlerFirst(new LoggingHandler()));
        webClientBuilder.clientConnector(new ReactorClientHttpConnector(httpClient));
    }

    private static class LoggingHandler extends ChannelDuplexHandler {

        @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
            if (msg instanceof FullHttpRequest request) {
                log.debug("DOWNSTREAM  REQUEST: METHOD: {}, URI: {}, BODY: {}, HEADERS: {}",
                    request.method(), request.uri(), request.content().toString(defaultCharset()), request.headers());
            } else if (msg instanceof HttpRequest request) {
                log.debug("DOWNSTREAM  REQUEST: METHOD: {}, URI: {}, HEADERS: {}",
                    request.method(), request.uri(), request.headers());
            } else if (msg instanceof FullHttpMessage message) {
                log.debug("DOWNSTREAM  REQUEST: BODY: {}",
                    message.content().toString(defaultCharset()));
            }
            super.write(ctx, msg, promise);
        }

        @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            if (msg instanceof FullHttpResponse response) {
                log.debug("DOWNSTREAM RESPONSE: STATUS: {}, BODY: {}, HEADERS: {}",
                    response.status().code(), response.content().toString(defaultCharset()), response.headers());
            } else if (msg instanceof HttpResponse response) {
                log.debug("DOWNSTREAM RESPONSE: STATUS: {}, HEADERS: {}",
                    response.status().code(), response.headers());
            } else if (!(msg instanceof LastHttpContent) && msg instanceof HttpContent httpContent) {
                log.debug("DOWNSTREAM RESPONSE: BODY: {}",
                    httpContent.content().toString(defaultCharset()));
            }
            super.channelRead(ctx, msg);
        }
    }

}
</code>```

but i need to get My correlation_Id from the treadContext to the logger.

i have tried using a webClient with a contextwrite to copy the context so that it could be accessible in the thread.

```<code>
                ...
                .retrieve()
                .onStatus(HttpStatus::is4xxClientError, response -> ...)
                .onStatus(HttpStatus::is5xxServerError, response -> ...)
                .bodyToMono(...))
                .contextWrite(context -> Context.of(MDC.getCopyOfContextMap()))
                .doFinally(signalType -> MDC.clear())
                .block()
                ;

</code>```

but i cannot get it in the logginghandler, i have nothing in threadContext or MDC

```<code>            var context2 = MDC.getMap();
            var context = ThreadContext.getContext();
            var response = (HttpResponse) msg;
</code>```

Am I doing something wrong?

Body:
I call a REST api using Webclient

i am using a customized netty HTTPClient with a loggingHandler that I use to log my call. (I got it from here WebClient - how to get request body?)

@Slf4j
@Component
public class LoggingCustomizer implements WebClientCustomizer {

    @Override public void customize(WebClient.Builder webClientBuilder) {
        HttpClient httpClient = HttpClient.create()
            .doOnRequest((httpClientRequest, connection) -> connection.addHandlerFirst(new LoggingHandler()));
        webClientBuilder.clientConnector(new ReactorClientHttpConnector(httpClient));
    }

    private static class LoggingHandler extends ChannelDuplexHandler {

        @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
            if (msg instanceof FullHttpRequest request) {
                log.debug("DOWNSTREAM  REQUEST: METHOD: {}, URI: {}, BODY: {}, HEADERS: {}",
                    request.method(), request.uri(), request.content().toString(defaultCharset()), request.headers());
            } else if (msg instanceof HttpRequest request) {
                log.debug("DOWNSTREAM  REQUEST: METHOD: {}, URI: {}, HEADERS: {}",
                    request.method(), request.uri(), request.headers());
            } else if (msg instanceof FullHttpMessage message) {
                log.debug("DOWNSTREAM  REQUEST: BODY: {}",
                    message.content().toString(defaultCharset()));
            }
            super.write(ctx, msg, promise);
        }

        @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            if (msg instanceof FullHttpResponse response) {
                log.debug("DOWNSTREAM RESPONSE: STATUS: {}, BODY: {}, HEADERS: {}",
                    response.status().code(), response.content().toString(defaultCharset()), response.headers());
            } else if (msg instanceof HttpResponse response) {
                log.debug("DOWNSTREAM RESPONSE: STATUS: {}, HEADERS: {}",
                    response.status().code(), response.headers());
            } else if (!(msg instanceof LastHttpContent) && msg instanceof HttpContent httpContent) {
                log.debug("DOWNSTREAM RESPONSE: BODY: {}",
                    httpContent.content().toString(defaultCharset()));
            }
            super.channelRead(ctx, msg);
        }
    }

}

but i need to get My correlation_Id from the treadContext to the logger.

i have tried using a webClient with a contextwrite to copy the context so that it could be accessible in the thread.

                ...
                .retrieve()
                .onStatus(HttpStatus::is4xxClientError, response -> ...)
                .onStatus(HttpStatus::is5xxServerError, response -> ...)
                .bodyToMono(...))
                .contextWrite(context -> Context.of(MDC.getCopyOfContextMap()))
                .doFinally(signalType -> MDC.clear())
                .block()
                ;

but i cannot get it in the logginghandler, i have nothing in threadContext or MDC

            var context2 = MDC.getMap();
            var context = ThreadContext.getContext();
            var response = (HttpResponse) msg;

Am I doing something wrong?


问:
how to search through pointers
I have a program in which there is a function to like the posts other users have posted.
I have to search through all the users who have already liked the post to see if the current user using the app has already liked the post or not.
if not, then the number of likes must be increased by 1 and also the user be stored among the likers so they can't like this post more than once.
The  problem is that I don't know how to search through the likers to find out if the user have already liked the post or not.

```<code>typedef struct user user;
struct user{
    char* userName;
    char* password;
    user* next;
};
typedef struct message message;
struct message{
    char* content;
    user* owner;
    user** likers;
    int likes;
    int postID;
    message* next;
};
int postLiking(user* owner, user* liker, int postID,message* dummyMessage){
    /*dummyMessage is the first message node*/
    while(dummyMessage!=NULL){
        if(dummyMessage->owner==owner){
            if(dummyMessage->postID==postID){
                /*must check if the liker has liked to post or not;if not, add them to the likers and increase the likes by 1*/
                //return 1;
            }
            else{
                printf("the user doesn't have a post with this post ID");
                return 0;
            }
        }
    }
}
</code>```

edited:I have this other idea:

```<code>typedef struct message message;
struct message{
    char* content;
    user* owner;
    int likes;
    int postID;
    message* next;
    likers* head;
};
typedef likers likers;
struct likers{
    char* liker;
    likers* next;
};
</code>```

edited: but I'[m not sure how to use it to search through the likers yet.

my idea was to save the likers as double pointers as you can see above. but I don't know how to search through them.
also I don't know if there are any better ways to save the likers.
I'll be glad if you help.
or maybe I have to kind of make a linked list within a linked list?

Title: how to search through pointers

Body:
I have a program in which there is a function to like the posts other users have posted.
I have to search through all the users who have already liked the post to see if the current user using the app has already liked the post or not.
if not, then the number of likes must be increased by 1 and also the user be stored among the likers so they can't like this post more than once.
The  problem is that I don't know how to search through the likers to find out if the user have already liked the post or not.

typedef struct user user;
struct user{
    char* userName;
    char* password;
    user* next;
};
typedef struct message message;
struct message{
    char* content;
    user* owner;
    user** likers;
    int likes;
    int postID;
    message* next;
};
int postLiking(user* owner, user* liker, int postID,message* dummyMessage){
    /*dummyMessage is the first message node*/
    while(dummyMessage!=NULL){
        if(dummyMessage->owner==owner){
            if(dummyMessage->postID==postID){
                /*must check if the liker has liked to post or not;if not, add them to the likers and increase the likes by 1*/
                //return 1;
            }
            else{
                printf("the user doesn't have a post with this post ID");
                return 0;
            }
        }
    }
}

edited:I have this other idea:

typedef struct message message;
struct message{
    char* content;
    user* owner;
    int likes;
    int postID;
    message* next;
    likers* head;
};
typedef likers likers;
struct likers{
    char* liker;
    likers* next;
};

edited: but I'[m not sure how to use it to search through the likers yet.

my idea was to save the likers as double pointers as you can see above. but I don't know how to search through them.
also I don't know if there are any better ways to save the likers.
I'll be glad if you help.
or maybe I have to kind of make a linked list within a linked list?


问:
Axis 1 is out of bounds for array of dimension 1 - while trying tp print metrics of DecisionTreeClassifier
I got this problem when I'm trying to print the metrics of a sckitlearn decision tree classifier for mnist dataset.

My X_train and X_ test has a shape of (48000, 784) and (12,000,784) respectively and the y_train and y_test are (48000, ) and (12,000, ) respectively maybe I need to reshape the train or test data somehow? Thanks for your help!

Fit a model and gain metrics.


问:
What is the point of passing in params to an abstract base class in this manner?
I was trying to understand how the backtesting.py module is written and came across this code.

```<code>class Strategy(metaclass=ABCMeta):
    """
    A trading strategy base class. Extend this class and
    override methods
    `backtesting.backtesting.Strategy.init` and
    `backtesting.backtesting.Strategy.next` to define
    your own strategy.
    """
    def __init__(self, broker, data, params):
        self._indicators = []
        self._broker: _Broker = broker
        self._data: _Data = data
        self._params = self._check_params(params)

    def __repr__(self):
        return '<Strategy ' + str(self) + '>'

    def __str__(self):
        params = ','.join(f'{i[0]}={i[1]}' for i in zip(self._params.keys(),
                                                        map(_as_str, self._params.values())))
        if params:
            params = '(' + params + ')'
        return f'{self.__class__.__name__}{params}'

    def _check_params(self, params):
        for k, v in params.items():
            if not hasattr(self, k):
                raise AttributeError(
                    f"Strategy '{self.__class__.__name__}' is missing parameter '{k}'."
                    "Strategy class should define parameters as class variables before they "
                    "can be optimized or run with.")
            setattr(self, k, v)
        return params
</code>```

From what I have understood it seems that the to instantiate an object of the strategy class we need three arguments broker, data, params  It seems that valid form of the params is supposed to be a dictionary with keys already being present as attributes. So does that mean params = {broker : "blah", data: "blahblah"} is the form that needs to be passed? WHat is the point of doing this in such a manner instead of directly passing the values to data and broker?

I tried to instantiate an object of the Strategy class using arbitrary dictionaries, just to understand what's going on.

This code q = Strategy("nn", [],{"b":33, "a":44}) gives the following error:

Strategy 'Strategy' is missing parameter 'b'.Strategy class should define parameters as class variables before they can be optimized or run with.

However if I do this:

q = Strategy("nn", [],{"_broker":33, "_data":44})

The code runs without errors.

Whatpurpose does this serve?

Body:
I was trying to understand how the backtesting.py module is written and came across this code.

class Strategy(metaclass=ABCMeta):
    """
    A trading strategy base class. Extend this class and
    override methods
    `backtesting.backtesting.Strategy.init` and
    `backtesting.backtesting.Strategy.next` to define
    your own strategy.
    """
    def __init__(self, broker, data, params):
        self._indicators = []
        self._broker: _Broker = broker
        self._data: _Data = data
        self._params = self._check_params(params)

    def __repr__(self):
        return '<Strategy ' + str(self) + '>'

    def __str__(self):
        params = ','.join(f'{i[0]}={i[1]}' for i in zip(self._params.keys(),
                                                        map(_as_str, self._params.values())))
        if params:
            params = '(' + params + ')'
        return f'{self.__class__.__name__}{params}'

    def _check_params(self, params):
        for k, v in params.items():
            if not hasattr(self, k):
                raise AttributeError(
                    f"Strategy '{self.__class__.__name__}' is missing parameter '{k}'."
                    "Strategy class should define parameters as class variables before they "
                    "can be optimized or run with.")
            setattr(self, k, v)
        return params

From what I have understood it seems that the to instantiate an object of the strategy class we need three arguments broker, data, params  It seems that valid form of the params is supposed to be a dictionary with keys already being present as attributes. So does that mean params = {broker : "blah", data: "blahblah"} is the form that needs to be passed? WHat is the point of doing this in such a manner instead of directly passing the values to data and broker?

I tried to instantiate an object of the Strategy class using arbitrary dictionaries, just to understand what's going on.

This code q = Strategy("nn", [],{"b":33, "a":44}) gives the following error:

Strategy 'Strategy' is missing parameter 'b'.Strategy class should define parameters as class variables before they can be optimized or run with.

However if I do this:

q = Strategy("nn", [],{"_broker":33, "_data":44})

The code runs without errors.

Whatpurpose does this serve?


问:
Problem with calling a Package with Procedure and Varray Inside
I'm starting new into SQL and we got an exercise related to Packages and Varrays. To be more specific, I have to create a python script which connects to my BD and inserts a varray of 100 numbers in a table.

I've create the package this way:

```<code>create or replace PACKAGE Pack AS
TYPE num_array IS VARRAY(100) OF NUMBER;
PROCEDURE procediment_1 (arr in num_array);
END Pack
</code>```

and its body

```<code>create or replace PACKAGE BODY PACK AS
PROCEDURE procediment_1 (arr in num_array) AS
BEGIN
FOR i IN 1..arr.COUNT LOOP
INSERT INTO B VALUES (arr(i));
END LOOP;
END;
END Pack;
</code>```

About the python script, here it is:

```<code>lista = []
x=0
while x < 100:
RandomNumero = random.randint(0, 1000)
if RandomNumero not in lista:
lista.append(RandomNumero)
x += 1
args = [lista]
cur.callproc("PACK.procediment_1", args)
conn.commit()
</code>```

Imagine that all imports and the cursor (cur) work perfectly.

The problem comes when this error appears:

```<code>cur.callproc("PACK.procediment_1", args)
cx_Oracle.DatabaseError: ORA-06550: line 1, column 7:
PLS-00306: wrong number or types of arguments in call to 'PROCEDIMENT_1'
ORA-06550: line 1, column 7:
PL/SQL: Statement ignored
</code>```

I know that the variable "args" might be the problem, but I don't know how to solve it. I have read a lot about python and SQL variables and I think that the way I do it is correct.

In fact, if I try to do it using SQL and not Python, like this:

```<code>DECLARE
TYPE v1 IS VARRAY(10) OF NUMBER;
VAR1 V1 := v1(1,2,3,4,5,6,7,8,9,10);
begin
pack.procediment_1(arr=>V1);
end;
</code>```

but still doesn't work.

I have a bad level of English, so I tried my best explaining myself. If anyone has any recommendation I will listen to it.

Thank you.

Body:
I'm starting new into SQL and we got an exercise related to Packages and Varrays. To be more specific, I have to create a python script which connects to my BD and inserts a varray of 100 numbers in a table.

I've create the package this way:

create or replace PACKAGE Pack AS
TYPE num_array IS VARRAY(100) OF NUMBER;
PROCEDURE procediment_1 (arr in num_array);
END Pack

and its body

create or replace PACKAGE BODY PACK AS
PROCEDURE procediment_1 (arr in num_array) AS
BEGIN
FOR i IN 1..arr.COUNT LOOP
INSERT INTO B VALUES (arr(i));
END LOOP;
END;
END Pack;

About the python script, here it is:

lista = []
x=0
while x < 100:
RandomNumero = random.randint(0, 1000)
if RandomNumero not in lista:
lista.append(RandomNumero)
x += 1
args = [lista]
cur.callproc("PACK.procediment_1", args)
conn.commit()

Imagine that all imports and the cursor (cur) work perfectly.

The problem comes when this error appears:

cur.callproc("PACK.procediment_1", args)
cx_Oracle.DatabaseError: ORA-06550: line 1, column 7:
PLS-00306: wrong number or types of arguments in call to 'PROCEDIMENT_1'
ORA-06550: line 1, column 7:
PL/SQL: Statement ignored

I know that the variable "args" might be the problem, but I don't know how to solve it. I have read a lot about python and SQL variables and I think that the way I do it is correct.

In fact, if I try to do it using SQL and not Python, like this:

DECLARE
TYPE v1 IS VARRAY(10) OF NUMBER;
VAR1 V1 := v1(1,2,3,4,5,6,7,8,9,10);
begin
pack.procediment_1(arr=>V1);
end;

but still doesn't work.

I have a bad level of English, so I tried my best explaining myself. If anyone has any recommendation I will listen to it.

Thank you.


问:
C++ regex - How can I convert std::smatch's elements to e.g. string, size_t and float?
I'm quite novice to C++, but here's my question. While building a regex to store names and corresponding numbers, I got an error while trying to convert the captured values in my std::smatch object to other types, like a std::string, size_t or float. The values below, given by res [1/2/3/4] do give me what I want when simply outputted through cout. Doing anything more with them doesn't work though. For example, passing them to a function which expects a string or a float.

I tried to figure out the type with e.g. typeid() and see if I could convert it, but no success. The attempt with typeid() gave the following type, which I don't recognize:

```<code>NSt7__cxx119sub_matchIN9__gnu_cxx17__normal_iteratorIPKcNS_12basic_stringIcSt11char_traitsIcESaIcEEEEEEE
</code>```

Here is the relevant code:

```<code>#include <regex>
#include <fstream>
#include <string>
#include <typeinfo>
using namespace std;

void regexExampleFunction(string filename)
{
    ifstream file(fileName);
    regex rex("^([A-z.]+\\s?[a-z]+)\\s([A-z]+)\\s(\\d{5})\\s(\\d.\\d)");
    smatch res;
    string line;

    while (getline(file, line))
    {
        regex_search(line, res, rex);

        cout << res[1] << " " << res[2] << " " << res[3] << " " << res[4] << '\n';
        cout << typeid(res[1]).name() << '\n'; // outputs the type above^
    }
}

int main(int argc, char **argv)
{
    regexExampleFunction(argv[1]);
}
</code>```

There must be some error I'm making, or just something I'm missing. It'd be great to hear your feedback.

Body:
I'm quite novice to C++, but here's my question. While building a regex to store names and corresponding numbers, I got an error while trying to convert the captured values in my std::smatch object to other types, like a std::string, size_t or float. The values below, given by res [1/2/3/4] do give me what I want when simply outputted through cout. Doing anything more with them doesn't work though. For example, passing them to a function which expects a string or a float.

I tried to figure out the type with e.g. typeid() and see if I could convert it, but no success. The attempt with typeid() gave the following type, which I don't recognize:

NSt7__cxx119sub_matchIN9__gnu_cxx17__normal_iteratorIPKcNS_12basic_stringIcSt11char_traitsIcESaIcEEEEEEE

Here is the relevant code:

#include <regex>
#include <fstream>
#include <string>
#include <typeinfo>
using namespace std;

void regexExampleFunction(string filename)
{
    ifstream file(fileName);
    regex rex("^([A-z.]+\\s?[a-z]+)\\s([A-z]+)\\s(\\d{5})\\s(\\d.\\d)");
    smatch res;
    string line;

    while (getline(file, line))
    {
        regex_search(line, res, rex);

        cout << res[1] << " " << res[2] << " " << res[3] << " " << res[4] << '\n';
        cout << typeid(res[1]).name() << '\n'; // outputs the type above^
    }
}

int main(int argc, char **argv)
{
    regexExampleFunction(argv[1]);
}

There must be some error I'm making, or just something I'm missing. It'd be great to hear your feedback.