问:
Android: How to reset MANAGE_EXTERNAL_STORAGE between each test?
I have setup my Android instrumentationTest so that all data is cleared between each test thanks to testInstrumentationRunnerArguments clearPackageData: 'true'

This works fine except for the "All files access" that remains in the state of the last test.

I can grant "all files access" through UiAutomator from within the app.

But I can't revoke it because when I'm in the "All files access" window, logcat reports that my app was killed because "MANAGE_EXTERNAL_STORAGE" changed. So the  myDevice.pressBack() to revert to my activity is innefective: nothing happens, I'm staying on that window without leaving it.

log

```<code>system_process I/ActivityManager: Killing 24511:<my.app>.debug/u0a162 (adj 0): MANAGE_EXTERNAL_STORAGE changed.
</code>```

log context

```<code>24511-24533/<my.app>.debug I/QueryController: Matched selector: UiSelector[TEXT_REGEX=(?i)Allow access to manage all files] <<==>> [android.view.accessibility.AccessibilityNodeInfo@13b0b; boundsInParent: Rect(0, 0 - 753, 71); boundsInScreen: Rect(63, 954 - 816, 1025); packageName: com.android.settings; className: android.widget.TextView; text: Allow access to manage all files; error: null; maxTextLength: -1; stateDescription: null; contentDescription: null; tooltipText: null; viewIdResName: android:id/title; checkable: false; checked: false; focusable: false; focused: false; selected: false; clickable: false; longClickable: false; contextClickable: false; enabled: true; password: false; scrollable: false; importantForAccessibility: true; visible: true; actions: [AccessibilityAction: ACTION_SELECT - null, AccessibilityAction: ACTION_CLEAR_SELECTION - null, AccessibilityAction: ACTION_ACCESSIBILITY_FOCUS - null, AccessibilityAction: ACTION_NEXT_AT_MOVEMENT_GRANULARITY - null, AccessibilityAction: ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY - null, AccessibilityAction: ACTION_SET_SELECTION - null, AccessibilityAction: ACTION_SHOW_ON_SCREEN - null]]
24511-24533/<my.app>.debug D/InteractionController: clickAndSync(439, 989)
1227-1227/com.google.android.apps.nexuslauncher D/TaplEvents: TIS / TouchInteractionService.onInputEvent: MotionEvent { action=ACTION_DOWN, actionButton=0, id[0]=0, x[0]=439.0, y[0]=989.0, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, classification=NONE, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=19166666, downTime=19166666, deviceId=-1, source=0x1002, displayId=0, eventId=-606474784 }
1227-1227/com.google.android.apps.nexuslauncher D/TaplEvents: TIS / TouchInteractionService.onInputEvent: MotionEvent { action=ACTION_UP, actionButton=0, id[0]=0, x[0]=439.0, y[0]=989.0, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, classification=NONE, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=19166784, downTime=19166666, deviceId=-1, source=0x1002, displayId=0, eventId=-468631845 }
1680-8178/com.google.android.providers.media.module I/MediaProvider: Invalidating LocalCallingIdentity cache for package <my.app>.debug. Reason: op android:read_external_storage
351-538/? E/android.hardware.audio@7.0-impl.ranchu: device/generic/goldfish/audio/stream_out.cpp:updateSourceMetadata:377 failure: Result::NOT_SUPPORTED
607-3275/system_process I/ActivityManager: Killing 24511:<my.app>.debug/u0a162 (adj 0): MANAGE_EXTERNAL_STORAGE changed.
607-3275/system_process W/ActivityManager: Crash of app <my.app>.debug running instrumentation ComponentInfo{<my.app>.debug.test/androidx.test.runner.AndroidJUnitRunner}
607-3275/system_process I/ActivityManager: Force stopping <my.app>.debug appid=10162 user=0: finished inst
607-3275/system_process I/WindowManager:   Force removing ActivityRecord{27550bc u0 <my.app>.debug/<my.app>.MainActivity t123}
607-3275/system_process W/InputManager-JNI: Input channel object '10c60ec <my.app>.debug/<my.app>.MainActivity (client)' was disposed without first being removed with the input manager!
607-659/system_process I/libprocessgroup: Successfully killed process cgroup uid 10162 pid 24511 in 5ms
607-649/system_process D/ContentCapturePerUserService: onActivityEvent(): no remote service
1545-1545/com.google.android.inputmethod.latin I/AppBase: AppBase.onTrimMemory():738 onTrimMemory(): 5
1545-1545/com.google.android.inputmethod.latin I/GoogleInputMethodService: GoogleInputMethodService.onTrimMemory():4463 onTrimMemory(): 5
23224-23251/com.google.android.apps.messaging W/Bugle: TextClassifierLibManagerImpl: Reclaiming memory at level: 80
607-656/system_process W/UsageStatsService: Unexpected activity event reported! (<my.app>.debug/<my.app>.MainActivity event : 23 instanceId : 96015535)
24497-24497/? D/AndroidRuntime: Shutting down VM
24555-24585/? D/EGL_emulation: app_time_stats: avg=147.68ms min=4.52ms max=627.87ms count=10
349-349/? I/Zygote: Process 24511 exited due to signal 9 (Killed)
24497-24510/? W/Binder: Caught a RuntimeException from the binder stub implementation.
    java.lang.SecurityException: Calling from not trusted UID!
        at android.app.UiAutomationConnection.throwIfCalledByNotTrustedUidLocked(UiAutomationConnection.java:601)
        at android.app.UiAutomationConnection.shutdown(UiAutomationConnection.java:505)
        at android.app.IUiAutomationConnection$Stub.onTransact(IUiAutomationConnection.java:437)
        at android.os.Binder.execTransactInternal(Binder.java:1184)
        at android.os.Binder.execTransact(Binder.java:1143)
607-649/system_process W/ActivityManager: setHasOverlayUi called on unknown pid: 24511
607-1541/system_process V/ActivityManager: Got obituary of 24511:<my.app>.debug
</code>```

Code to toggle from within my app.

    public static void toggleAllFilesAccess() throws Exception {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R &&
                ! Environment.isExternalStorageManager() &&
                ! Environment.isExternalStorageLegacy()) {

            UiDevice device = UiDevice.getInstance(getInstrumentation());

            Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();
            String permit_manage_external_storage = new String();
            int resId;

            PackageManager manager = context.getPackageManager();

            // Identifier names are taken here:
            // https://cs.android.com/android/platform/superproject/+/master:packages/apps/Settings/res/values/strings.xml
            Resources resources = manager.getResourcesForApplication("com.android.settings");
            resId = resources.getIdentifier("permit_manage_external_storage", "string", "com.android.settings");
            permit_manage_external_storage = resources.getString(resId);

            onView(withText(R.string.pref_allFilesAccess_title)).perform(click());

            UiObject uiElement2 = device.findObject(new UiSelector().textMatches("(?i)" + permit_manage_external_storage));
            uiElement2.click();
            device.pressBack();
        }
    }
```

Any suggestion on how to achieve this?

Body:
I have setup my Android instrumentationTest so that all data is cleared between each test thanks to testInstrumentationRunnerArguments clearPackageData: 'true'

This works fine except for the "All files access" that remains in the state of the last test.

I can grant "all files access" through UiAutomator from within the app.

But I can't revoke it because when I'm in the "All files access" window, logcat reports that my app was killed because "MANAGE_EXTERNAL_STORAGE" changed. So the  myDevice.pressBack() to revert to my activity is innefective: nothing happens, I'm staying on that window without leaving it.

log

system_process I/ActivityManager: Killing 24511:<my.app>.debug/u0a162 (adj 0): MANAGE_EXTERNAL_STORAGE changed.

log context

24511-24533/<my.app>.debug I/QueryController: Matched selector: UiSelector[TEXT_REGEX=(?i)Allow access to manage all files] <<==>> [android.view.accessibility.AccessibilityNodeInfo@13b0b; boundsInParent: Rect(0, 0 - 753, 71); boundsInScreen: Rect(63, 954 - 816, 1025); packageName: com.android.settings; className: android.widget.TextView; text: Allow access to manage all files; error: null; maxTextLength: -1; stateDescription: null; contentDescription: null; tooltipText: null; viewIdResName: android:id/title; checkable: false; checked: false; focusable: false; focused: false; selected: false; clickable: false; longClickable: false; contextClickable: false; enabled: true; password: false; scrollable: false; importantForAccessibility: true; visible: true; actions: [AccessibilityAction: ACTION_SELECT - null, AccessibilityAction: ACTION_CLEAR_SELECTION - null, AccessibilityAction: ACTION_ACCESSIBILITY_FOCUS - null, AccessibilityAction: ACTION_NEXT_AT_MOVEMENT_GRANULARITY - null, AccessibilityAction: ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY - null, AccessibilityAction: ACTION_SET_SELECTION - null, AccessibilityAction: ACTION_SHOW_ON_SCREEN - null]]
24511-24533/<my.app>.debug D/InteractionController: clickAndSync(439, 989)
1227-1227/com.google.android.apps.nexuslauncher D/TaplEvents: TIS / TouchInteractionService.onInputEvent: MotionEvent { action=ACTION_DOWN, actionButton=0, id[0]=0, x[0]=439.0, y[0]=989.0, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, classification=NONE, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=19166666, downTime=19166666, deviceId=-1, source=0x1002, displayId=0, eventId=-606474784 }
1227-1227/com.google.android.apps.nexuslauncher D/TaplEvents: TIS / TouchInteractionService.onInputEvent: MotionEvent { action=ACTION_UP, actionButton=0, id[0]=0, x[0]=439.0, y[0]=989.0, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, classification=NONE, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=19166784, downTime=19166666, deviceId=-1, source=0x1002, displayId=0, eventId=-468631845 }
1680-8178/com.google.android.providers.media.module I/MediaProvider: Invalidating LocalCallingIdentity cache for package <my.app>.debug. Reason: op android:read_external_storage
351-538/? E/android.hardware.audio@7.0-impl.ranchu: device/generic/goldfish/audio/stream_out.cpp:updateSourceMetadata:377 failure: Result::NOT_SUPPORTED
607-3275/system_process I/ActivityManager: Killing 24511:<my.app>.debug/u0a162 (adj 0): MANAGE_EXTERNAL_STORAGE changed.
607-3275/system_process W/ActivityManager: Crash of app <my.app>.debug running instrumentation ComponentInfo{<my.app>.debug.test/androidx.test.runner.AndroidJUnitRunner}
607-3275/system_process I/ActivityManager: Force stopping <my.app>.debug appid=10162 user=0: finished inst
607-3275/system_process I/WindowManager:   Force removing ActivityRecord{27550bc u0 <my.app>.debug/<my.app>.MainActivity t123}
607-3275/system_process W/InputManager-JNI: Input channel object '10c60ec <my.app>.debug/<my.app>.MainActivity (client)' was disposed without first being removed with the input manager!
607-659/system_process I/libprocessgroup: Successfully killed process cgroup uid 10162 pid 24511 in 5ms
607-649/system_process D/ContentCapturePerUserService: onActivityEvent(): no remote service
1545-1545/com.google.android.inputmethod.latin I/AppBase: AppBase.onTrimMemory():738 onTrimMemory(): 5
1545-1545/com.google.android.inputmethod.latin I/GoogleInputMethodService: GoogleInputMethodService.onTrimMemory():4463 onTrimMemory(): 5
23224-23251/com.google.android.apps.messaging W/Bugle: TextClassifierLibManagerImpl: Reclaiming memory at level: 80
607-656/system_process W/UsageStatsService: Unexpected activity event reported! (<my.app>.debug/<my.app>.MainActivity event : 23 instanceId : 96015535)
24497-24497/? D/AndroidRuntime: Shutting down VM
24555-24585/? D/EGL_emulation: app_time_stats: avg=147.68ms min=4.52ms max=627.87ms count=10
349-349/? I/Zygote: Process 24511 exited due to signal 9 (Killed)
24497-24510/? W/Binder: Caught a RuntimeException from the binder stub implementation.
    java.lang.SecurityException: Calling from not trusted UID!
        at android.app.UiAutomationConnection.throwIfCalledByNotTrustedUidLocked(UiAutomationConnection.java:601)
        at android.app.UiAutomationConnection.shutdown(UiAutomationConnection.java:505)
        at android.app.IUiAutomationConnection$Stub.onTransact(IUiAutomationConnection.java:437)
        at android.os.Binder.execTransactInternal(Binder.java:1184)
        at android.os.Binder.execTransact(Binder.java:1143)
607-649/system_process W/ActivityManager: setHasOverlayUi called on unknown pid: 24511
607-1541/system_process V/ActivityManager: Got obituary of 24511:<my.app>.debug

Code to toggle from within my app.

    public static void toggleAllFilesAccess() throws Exception {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R &&
                ! Environment.isExternalStorageManager() &&
                ! Environment.isExternalStorageLegacy()) {

            UiDevice device = UiDevice.getInstance(getInstrumentation());

            Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();
            String permit_manage_external_storage = new String();
            int resId;

            PackageManager manager = context.getPackageManager();

            // Identifier names are taken here:
            // https://cs.android.com/android/platform/superproject/+/master:packages/apps/Settings/res/values/strings.xml
            Resources resources = manager.getResourcesForApplication("com.android.settings");
            resId = resources.getIdentifier("permit_manage_external_storage", "string", "com.android.settings");
            permit_manage_external_storage = resources.getString(resId);

            onView(withText(R.string.pref_allFilesAccess_title)).perform(click());

            UiObject uiElement2 = device.findObject(new UiSelector().textMatches("(?i)" + permit_manage_external_storage));
            uiElement2.click();
            device.pressBack();
        }
    }

Any suggestion on how to achieve this?


来源: stackexchange

问:
Find the areas near my point based in coordinates - excel
There are a few areas, each with its own value, i enter with a lat and long that i want to know in which area it is and give the value for that area. So far, so good. Found how to find where my lat and long is, but - this is where im breaking my head - i want know which area is the closest, then i can take its value and calculate the average between the two values (the value inside the area and the value of the nearest area).

I'm using this code below to know in which area my coordinate is:

```<code>Public Function PtInPoly(Polygon As Range, Xcoord As Double, Ycoord As Double) As Boolean
  Dim x As Long, m As Double, b As Double, Poly As Variant, NumSidesCrossed As Long
  Poly = Polygon
  For x = 1 To UBound(Poly) - 1
    If Poly(x, 1) > Xcoord Xor Poly(x + 1, 1) > Xcoord Then
      m = (Poly(x + 1, 2) - Poly(x, 2)) / (Poly(x + 1, 1) - Poly(x, 1))
      b = (Poly(x, 2) * Poly(x + 1, 1) - Poly(x, 1) * Poly(x + 1, 2)) / (Poly(x + 1, 1) - Poly(x, 1))
      If m * Xcoord + b > Ycoord Then NumSidesCrossed = NumSidesCrossed + 1
    End If
  Next
  PtInPoly = NumSidesCrossed Mod 2
End Function
</code>```

There are 27 maps (columns L and M, O and P...), each with its coordinates forming an area. Each area has a designated value (Column F). In column E, i'm using the formula from the Public Function code to know where my coordinates (column A and B) are.

ContentLicense: CC BY-SA 4.0

Body:
There are a few areas, each with its own value, i enter with a lat and long that i want to know in which area it is and give the value for that area. So far, so good. Found how to find where my lat and long is, but - this is where im breaking my head - i want know which area is the closest, then i can take its value and calculate the average between the two values (the value inside the area and the value of the nearest area).

I'm using this code below to know in which area my coordinate is:

Public Function PtInPoly(Polygon As Range, Xcoord As Double, Ycoord As Double) As Boolean
  Dim x As Long, m As Double, b As Double, Poly As Variant, NumSidesCrossed As Long
  Poly = Polygon
  For x = 1 To UBound(Poly) - 1
    If Poly(x, 1) > Xcoord Xor Poly(x + 1, 1) > Xcoord Then
      m = (Poly(x + 1, 2) - Poly(x, 2)) / (Poly(x + 1, 1) - Poly(x, 1))
      b = (Poly(x, 2) * Poly(x + 1, 1) - Poly(x, 1) * Poly(x + 1, 2)) / (Poly(x + 1, 1) - Poly(x, 1))
      If m * Xcoord + b > Ycoord Then NumSidesCrossed = NumSidesCrossed + 1
    End If
  Next
  PtInPoly = NumSidesCrossed Mod 2
End Function

There are 27 maps (columns L and M, O and P...), each with its coordinates forming an area. Each area has a designated value (Column F). In column E, i'm using the formula from the Public Function code to know where my coordinates (column A and B) are.


问:
How to import a function from a class without import in all class using webpack?
I'm new to webpack.
I have a class A which imports a function from class B. But for some reason webpack is importing all B class instead of importing only the function foo. any idea why it's importing all B?

```<code>import {foo} from './B'
export default class A {
    foo();
    ...
}
</code>```
```<code>export default class B {
   ...
    static foo(){
      //Do something
    }
}
export const foo = B.foo;
</code>```

I tried

```<code>export default class B {
    ...
}

export function foo(){
 //Do something
}
</code>```

Body:
I'm new to webpack.
I have a class A which imports a function from class B. But for some reason webpack is importing all B class instead of importing only the function foo. any idea why it's importing all B?

import {foo} from './B'
export default class A {
    foo();
    ...
}

export default class B {
   ...
    static foo(){
      //Do something
    }
}
export const foo = B.foo;

I tried

export default class B {
    ...
}

export function foo(){
 //Do something
}


问:
Issue with installing Git via Homebrew on Mac
I'm trying to set up Git for the first time so that I can import my project from VS Code. It's been pretty frustrating trying to figure it out on my own.

I tried to install Git by following a YouTube video, but my terminal gave me this message:

```<code>==> You are using macOS 10.13.
==> We (and Apple) do not provide support for this old version.
This installation may not succeed.
After installation, you will encounter build failures with some formulae.
Please create pull requests instead of asking for help on Homebrew's GitHub,
Twitter or any other official channels. You are responsible for resolving any
issues you experience while you are running this old version.

==> This script will install:
/usr/local/bin/brew
/usr/local/share/doc/homebrew
/usr/local/share/man/man1/brew.1
/usr/local/share/zsh/site-functions/_brew
/usr/local/etc/bash_completion.d/brew
/usr/local/Homebrew

Press RETURN/ENTER to continue or any other key to abort:
</code>```

I don't know if I should proceed, as I don't want to come across any major issues when trying to share my projects. Should I, or is there something else that I need to do?

I copied/pasted this into my terminal from Homebrew:

```<code>/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
</code>```

Body:
I'm trying to set up Git for the first time so that I can import my project from VS Code. It's been pretty frustrating trying to figure it out on my own.

I tried to install Git by following a YouTube video, but my terminal gave me this message:

==> You are using macOS 10.13.
==> We (and Apple) do not provide support for this old version.
This installation may not succeed.
After installation, you will encounter build failures with some formulae.
Please create pull requests instead of asking for help on Homebrew's GitHub,
Twitter or any other official channels. You are responsible for resolving any
issues you experience while you are running this old version.

==> This script will install:
/usr/local/bin/brew
/usr/local/share/doc/homebrew
/usr/local/share/man/man1/brew.1
/usr/local/share/zsh/site-functions/_brew
/usr/local/etc/bash_completion.d/brew
/usr/local/Homebrew

Press RETURN/ENTER to continue or any other key to abort:

I don't know if I should proceed, as I don't want to come across any major issues when trying to share my projects. Should I, or is there something else that I need to do?

I copied/pasted this into my terminal from Homebrew:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"


问:
How to add pivot tables to slicer using VBA
I'm trying to add pivot tables references to my slicer.
I'm creating the pivot table in a procedure like this

```<code>sub createPivot ()
Dim pCache As PivotCache
Dim pTable As PivotTable
Dim pRange As Rangetype here

Set pRange = wsMiss.Cells(1, 1).Resize(lastRowMiss, lastColMiss)
Set pCache = wb.PivotCaches.Create(xlDatabase, pRange)
Set pTable = pCache.CreatePivotTable(ws.Cells(iRow, iCol), "PivotLeave")

End sub
</code>```

Then, I'm creating a slicer in the parent procedure like this

```<code>sub createSlicer ()
Dim sCache As SlicerCache
Dim sDate As slicer

Set sCache = wbN.SlicerCaches.Add2(ws.PivotTables("PivotLeave"), "Months")
Set sDate = sCache.Slicers.Add(ws)

</code>```

Finally, I try to integrate other PivotTables (created in other procedures) in the same procedure where I created the slicer like this:

```<code>Dim sColl as SlicerPivotTables
Set sColl = wbN.SlicerCaches(sCache.Name).PivotTables
sColl.AddPivotTable (ws.PivotTables("PivotActivities"))
</code>```

The slicer is creating nicely and is linked to the correct PivotTable, but when I try to add the other I get a "Run-time error '424' Object Required".

Even though I only shared snippets, they are copy-pasted.
Finally, it may help to add that I don't know what I'm doing. I've been trying to find my way around using MSDN documentation but it is desperately short.

I already tried to change the way I set "sColl", thinking it might be an issue regarding the SlicerCache. I tried to hardcode the index (sCache.Name), to refer to it's parent using (sCache.parent) or to replace "sCache" by the slicer name "Months" but all I got was an error "Invalid procedure call or argument".

Thanks for all the help you can give,

Regards,

Rudy

Body:
I'm trying to add pivot tables references to my slicer.
I'm creating the pivot table in a procedure like this

sub createPivot ()
Dim pCache As PivotCache
Dim pTable As PivotTable
Dim pRange As Rangetype here

Set pRange = wsMiss.Cells(1, 1).Resize(lastRowMiss, lastColMiss)
Set pCache = wb.PivotCaches.Create(xlDatabase, pRange)
Set pTable = pCache.CreatePivotTable(ws.Cells(iRow, iCol), "PivotLeave")

End sub

Then, I'm creating a slicer in the parent procedure like this

sub createSlicer ()
Dim sCache As SlicerCache
Dim sDate As slicer

Set sCache = wbN.SlicerCaches.Add2(ws.PivotTables("PivotLeave"), "Months")
Set sDate = sCache.Slicers.Add(ws)

Finally, I try to integrate other PivotTables (created in other procedures) in the same procedure where I created the slicer like this:

Dim sColl as SlicerPivotTables
Set sColl = wbN.SlicerCaches(sCache.Name).PivotTables
sColl.AddPivotTable (ws.PivotTables("PivotActivities"))

The slicer is creating nicely and is linked to the correct PivotTable, but when I try to add the other I get a "Run-time error '424' Object Required".

Even though I only shared snippets, they are copy-pasted.
Finally, it may help to add that I don't know what I'm doing. I've been trying to find my way around using MSDN documentation but it is desperately short.

I already tried to change the way I set "sColl", thinking it might be an issue regarding the SlicerCache. I tried to hardcode the index (sCache.Name), to refer to it's parent using (sCache.parent) or to replace "sCache" by the slicer name "Months" but all I got was an error "Invalid procedure call or argument".

Thanks for all the help you can give,

Regards,

Rudy


问:
Stdio initialisation - embedded, newlib, freeRTOS
I am not actually sure where the best place to post this is as it is a combination of newlib code, FreeRTOS and a custom implementation.  Application is embedded ARM using GCC (arm-eabi...), newlib from standard GCC for ARM installation, FreeRTOS on embedded target (STM32).

The root issue is that calling fprint(stderr, "error\n") fails the first time it is called.  Calling printf before solves the issue.

Fails

```<code>int err = fprint(stderr, "error\n");   // err = -1, failed!
</code>```

OK

```<code>int err = printf("hi\n");              // err = 3, OK
err = fprint(stderr, "error\n");       // err = 6, OK
</code>```

I have found the cause of this issue, its a bit long winded to explain, but it comes down to  threads reent structure being not fully initialised until the first call of a std out function that implicitly uses stdout, stderr or stdin.  e.g. printf, puts etc.

I will try explain what is going on:

When a thread is created, FreeRTOS initiallises the threads reent struct using the default initialiser.  This initialises the std file pointers to point to the FILE structures in the reent struct itself.

FreeRTOS tasks.c initialises the tasks reent struct:

```<code>#if ( configUSE_NEWLIB_REENTRANT == 1 )
{
    /* Initialise this task's Newlib reent structure. */
    _REENT_INIT_PTR( ( &( pxNewTCB->xNewLib_reent ) ) );
}
#endif
</code>```

_REENT_INIT_PTR sets the std file pointers in the reent struct to the file descriptors in the reent struct itself (https://github.com/eblot/newlib/blob/master/newlib/libc/include/sys/reent.h):

```<code>#define _REENT_INIT_PTR(var) \
  { memset((var), 0, sizeof(*(var))); \
    (var)->_stdin = &(var)->__sf[0]; \
    (var)->_stdout = &(var)->__sf[1]; \
    (var)->_stderr = &(var)->__sf[2]; \
</code>```

The file descriptors in the reent struct are by default zeroed (first line memset) so invalid.

Calling printf causes a call to initialise the reent struct.  This is done by calling __sinit (via _REENT_SMALL_CHECK_INIT) if the structure has not been initialised before (https://github.com/eblot/newlib/blob/master/newlib/libc/stdio/printf.c).

```<code>int
_DEFUN(printf, (fmt),
       const char *fmt _DOTS)
{
  int ret;
  va_list ap;
  struct _reent *ptr = _REENT;

  _REENT_SMALL_CHECK_INIT (ptr);
  va_start (ap, fmt);
  ret = _vfprintf_r (ptr, _stdout_r (ptr), fmt, ap);
  va_end (ap);
  return ret;
}
</code>```

(https://github.com/eblot/newlib/blob/master/newlib/libc/include/sys/reent.h)

```<code># define _REENT_SMALL_CHECK_INIT(ptr)       \
  do                        \
    {                       \
      if ((ptr) && !(ptr)->__sdidinit)      \
    __sinit (ptr);              \
    }                       \
  while (0)
</code>```

__sinit does a whole lot of work including initialising the global reeent structure (if it has not been initialised), and copying the global reent structures stdio file pointers to the tasks local stdio file points, thereby making them valid.  __sinit definiton is in https://github.com/eblot/newlib/blob/master/newlib/libc/stdio/findfp.c.

Note that fprintf does not call __sinit, so in this case, the stderr file pointer is used uninitialised if fprintf is called before printf (https://github.com/eblot/newlib/blob/master/newlib/libc/stdio/fprintf.c).

```<code>int
_DEFUN(fprintf, (fp, fmt),
       FILE *fp _AND
       const char *fmt _DOTS)
{
  int ret;
  va_list ap;

  va_start (ap, fmt);
  ret = _vfprintf_r (_REENT, fp, fmt, ap);
  va_end (ap);
  return ret;
}
</code>```

So, while I am not claiming that anything is broken, I am not sure how the tasks local reent structure is meant to get initialised before any calls to fprintf.  A simple printf at the start of the thread would resolve this.  But it would mean I need to do that at the start of every task that might use fprintf.  By default assert calls fprintf, so I would need to have a printf at the start of any thread that might use assert (actually how this issue was found).

I am interested to hear any feedback or advice on this one.  I already have a workaround for this application (custom assert function), but I would like to understand and learn a bit more about what is going on here.

Body:
I am not actually sure where the best place to post this is as it is a combination of newlib code, FreeRTOS and a custom implementation.  Application is embedded ARM using GCC (arm-eabi...), newlib from standard GCC for ARM installation, FreeRTOS on embedded target (STM32).

The root issue is that calling fprint(stderr, "error\n") fails the first time it is called.  Calling printf before solves the issue.

Fails

int err = fprint(stderr, "error\n");   // err = -1, failed!

OK

int err = printf("hi\n");              // err = 3, OK
err = fprint(stderr, "error\n");       // err = 6, OK

I have found the cause of this issue, its a bit long winded to explain, but it comes down to  threads reent structure being not fully initialised until the first call of a std out function that implicitly uses stdout, stderr or stdin.  e.g. printf, puts etc.

I will try explain what is going on:

When a thread is created, FreeRTOS initiallises the threads reent struct using the default initialiser.  This initialises the std file pointers to point to the FILE structures in the reent struct itself.

FreeRTOS tasks.c initialises the tasks reent struct:

#if ( configUSE_NEWLIB_REENTRANT == 1 )
{
    /* Initialise this task's Newlib reent structure. */
    _REENT_INIT_PTR( ( &( pxNewTCB->xNewLib_reent ) ) );
}
#endif

_REENT_INIT_PTR sets the std file pointers in the reent struct to the file descriptors in the reent struct itself (https://github.com/eblot/newlib/blob/master/newlib/libc/include/sys/reent.h):

#define _REENT_INIT_PTR(var) \
  { memset((var), 0, sizeof(*(var))); \
    (var)->_stdin = &(var)->__sf[0]; \
    (var)->_stdout = &(var)->__sf[1]; \
    (var)->_stderr = &(var)->__sf[2]; \

The file descriptors in the reent struct are by default zeroed (first line memset) so invalid.

Calling printf causes a call to initialise the reent struct.  This is done by calling __sinit (via _REENT_SMALL_CHECK_INIT) if the structure has not been initialised before (https://github.com/eblot/newlib/blob/master/newlib/libc/stdio/printf.c).

int
_DEFUN(printf, (fmt),
       const char *fmt _DOTS)
{
  int ret;
  va_list ap;
  struct _reent *ptr = _REENT;

  _REENT_SMALL_CHECK_INIT (ptr);
  va_start (ap, fmt);
  ret = _vfprintf_r (ptr, _stdout_r (ptr), fmt, ap);
  va_end (ap);
  return ret;
}

(https://github.com/eblot/newlib/blob/master/newlib/libc/include/sys/reent.h)

# define _REENT_SMALL_CHECK_INIT(ptr)       \
  do                        \
    {                       \
      if ((ptr) && !(ptr)->__sdidinit)      \
    __sinit (ptr);              \
    }                       \
  while (0)

__sinit does a whole lot of work including initialising the global reeent structure (if it has not been initialised), and copying the global reent structures stdio file pointers to the tasks local stdio file points, thereby making them valid.  __sinit definiton is in https://github.com/eblot/newlib/blob/master/newlib/libc/stdio/findfp.c.

Note that fprintf does not call __sinit, so in this case, the stderr file pointer is used uninitialised if fprintf is called before printf (https://github.com/eblot/newlib/blob/master/newlib/libc/stdio/fprintf.c).

int
_DEFUN(fprintf, (fp, fmt),
       FILE *fp _AND
       const char *fmt _DOTS)
{
  int ret;
  va_list ap;

  va_start (ap, fmt);
  ret = _vfprintf_r (_REENT, fp, fmt, ap);
  va_end (ap);
  return ret;
}

So, while I am not claiming that anything is broken, I am not sure how the tasks local reent structure is meant to get initialised before any calls to fprintf.  A simple printf at the start of the thread would resolve this.  But it would mean I need to do that at the start of every task that might use fprintf.  By default assert calls fprintf, so I would need to have a printf at the start of any thread that might use assert (actually how this issue was found).

I am interested to hear any feedback or advice on this one.  I already have a workaround for this application (custom assert function), but I would like to understand and learn a bit more about what is going on here.


问:
Error connecting to SQL Server 2012 using NodeJS and mssql package
I'm using the mssql package for node in a MacOs Monterey:

```<code>import mssql from "mssql"

connect = async () => {
    try {
      var cfg = {
        server: "10.0.0.180",
        authentication: {
          type: "default",
          options: {
            userName: "username",
            password: "password",
          },
        },
        options: {
          encrypt: true,
          enableArithAbort: true,
          integratedSecurity: true,
          trustServerCertificate: true,
          rowCollectionOnDone: true,
          database: "db",
          cryptoCredentialsDetails: {
            // Required for SQL Server 2012 connection,
            // as node 18 uses a newer TLS protocol
            minVersion: "TLSv1",
          },
        },
      };

      let conn = await mssql.connect(cfg);

      return conn;
    } catch (error) {
      return null;
    }

    return false;
  };
</code>```

Working with node v18.13.0 I'm getting the following error:

ConnectionError: Failed to connect to 10.0.0.180:1433 - 0036761901000000:error:0A000102:SSL routines:ssl_choose_client_version:unsupported protocol:../deps/openssl/openssl/ssl/statem/statem_lib.c:1986:

My project config:

```<code> "dependencies": {
    "mssql": "^9.0.1",
    "nconf": "^0.12.0",
    "qs": "^6.11.0"
  },
  "devDependencies": {
    "@babel/core": "^7.20.2",
    "@babel/node": "^7.20.2",
    "@babel/preset-env": "^7.20.2",
    "babel-loader": "^9.1.0",
    "webpack": "^5.75.0",
    "webpack-cli": "^4.10.0"
  }
</code>```

I'm stuck on that as I cannot connect to the database. What might be causing this?

Body:
I'm using the mssql package for node in a MacOs Monterey:

import mssql from "mssql"

connect = async () => {
    try {
      var cfg = {
        server: "10.0.0.180",
        authentication: {
          type: "default",
          options: {
            userName: "username",
            password: "password",
          },
        },
        options: {
          encrypt: true,
          enableArithAbort: true,
          integratedSecurity: true,
          trustServerCertificate: true,
          rowCollectionOnDone: true,
          database: "db",
          cryptoCredentialsDetails: {
            // Required for SQL Server 2012 connection,
            // as node 18 uses a newer TLS protocol
            minVersion: "TLSv1",
          },
        },
      };

      let conn = await mssql.connect(cfg);

      return conn;
    } catch (error) {
      return null;
    }

    return false;
  };

Working with node v18.13.0 I'm getting the following error:

ConnectionError: Failed to connect to 10.0.0.180:1433 - 0036761901000000:error:0A000102:SSL routines:ssl_choose_client_version:unsupported protocol:../deps/openssl/openssl/ssl/statem/statem_lib.c:1986:

My project config:

 "dependencies": {
    "mssql": "^9.0.1",
    "nconf": "^0.12.0",
    "qs": "^6.11.0"
  },
  "devDependencies": {
    "@babel/core": "^7.20.2",
    "@babel/node": "^7.20.2",
    "@babel/preset-env": "^7.20.2",
    "babel-loader": "^9.1.0",
    "webpack": "^5.75.0",
    "webpack-cli": "^4.10.0"
  }

I'm stuck on that as I cannot connect to the database. What might be causing this?


问:
Is it possible to update the download location for a file in Chrome in Karate UI to the target folder?
I am using Karate UI for a test as part of which some steps involve the downloading of a file and validating the existence of the same.

Is it possible to update the download location of the file to target folder instead of default downloads folder?
How can I configure driver in karate config to get the file downloaded at the preferred location?

I have tried using userDataDir, but this isn't working.

Any help will be appreciated.


问:
Building App with Config File (White Label) not working with Null Safety
I added the config file like this. But when I try to build iOS there is the error "my config don't support null safety" what can I do ?

```<code>class FlavorStrings {
static const String APP_HEADING_COPY = "BASE APP HEADING";
static const int COLORCODE = 2312312;
}
</code>```

/var/folders/mk/xvjbsrs56fn17mh2_60n28d40000gn/T/flutter_tools.Kc07aJ/flutter_ios_build_temp_diryUd6y9/temporary_xcresult_bundle

Body:
I added the config file like this. But when I try to build iOS there is the error "my config don't support null safety" what can I do ?

class FlavorStrings {
static const String APP_HEADING_COPY = "BASE APP HEADING";
static const int COLORCODE = 2312312;
}

/var/folders/mk/xvjbsrs56fn17mh2_60n28d40000gn/T/flutter_tools.Kc07aJ/flutter_ios_build_temp_diryUd6y9/temporary_xcresult_bundle


问:
Why am I Encountering 403 Error On Windows Service Container?
I'm new to docker and am working on trying to containerize one of my org's solutions. It's a windows service that is used to build data packages that are distributed to clients. It has a small web front end that is used to interact with it and kick off package builds. After building the image and running the container, I have all of the binaries from the Visual Studio solution copied over to a directory under C:/inetpub/wwwroot on the container, and have a port mapping from 1337 on my host machine to 80 on the container.

However, when I try to browse to localhost:1337 to access the web front end for the service running on the container I get a 403 error like the linked image. Would anyone happen to know what might be causing this? Dockerfile is pasted below as well for reference, thanks in advance for any help.

403 Error Page

```<code># escape=\

FROM mcr.microsoft.com/dotnet/framework/aspnet:4.8-windowsservercore-ltsc2019

SHELL ["powershell", "-Command", "$ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue';"]

COPY ./bin /inetpub/wwwroot/

RUN icacls 'C:/inetpub/wwwroot' /grant 'Everyone:(OI)(CI)F'

EXPOSE 80

WORKDIR "C:/inetpub/wwwroot/"
RUN New-Service -Name "\"CDR"\"  -StartupType "\"Automatic"\"  -BinaryPathName "\"C:\\inetpub\\wwwroot\\CDR_Service.exe"\";

ENTRYPOINT ["powershell"]
CMD Start-Service \""CDR Service\""; \
    Get-EventLog -LogName System -After (Get-Date).AddHours(-1) | Format-List ;\
    $idx = (get-eventlog -LogName System -Newest 1).Index; \
    while ($true) \
    {; \
    start-sleep -Seconds 1; \
    $idx2  = (Get-EventLog -LogName System -newest 1).index; \
    get-eventlog -logname system -newest ($idx2 - $idx) |  sort index | Format-List; \
    $idx = $idx2; \
    }
</code>```

Created Dockerfile for windows service based on template I found on stackoverflow. Built an image using it after making the necessary changes for my specific app. Ran container from generated image expecting to be able to browse to the dashboard of the app, but am encountering a 403 forbidden error whenever browsing to it.

Body:
I'm new to docker and am working on trying to containerize one of my org's solutions. It's a windows service that is used to build data packages that are distributed to clients. It has a small web front end that is used to interact with it and kick off package builds. After building the image and running the container, I have all of the binaries from the Visual Studio solution copied over to a directory under C:/inetpub/wwwroot on the container, and have a port mapping from 1337 on my host machine to 80 on the container.

However, when I try to browse to localhost:1337 to access the web front end for the service running on the container I get a 403 error like the linked image. Would anyone happen to know what might be causing this? Dockerfile is pasted below as well for reference, thanks in advance for any help.

403 Error Page

# escape=\

FROM mcr.microsoft.com/dotnet/framework/aspnet:4.8-windowsservercore-ltsc2019

SHELL ["powershell", "-Command", "$ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue';"]

COPY ./bin /inetpub/wwwroot/

RUN icacls 'C:/inetpub/wwwroot' /grant 'Everyone:(OI)(CI)F'

EXPOSE 80

WORKDIR "C:/inetpub/wwwroot/"
RUN New-Service -Name "\"CDR"\"  -StartupType "\"Automatic"\"  -BinaryPathName "\"C:\\inetpub\\wwwroot\\CDR_Service.exe"\";

ENTRYPOINT ["powershell"]
CMD Start-Service \""CDR Service\""; \
    Get-EventLog -LogName System -After (Get-Date).AddHours(-1) | Format-List ;\
    $idx = (get-eventlog -LogName System -Newest 1).Index; \
    while ($true) \
    {; \
    start-sleep -Seconds 1; \
    $idx2  = (Get-EventLog -LogName System -newest 1).index; \
    get-eventlog -logname system -newest ($idx2 - $idx) |  sort index | Format-List; \
    $idx = $idx2; \
    }

Created Dockerfile for windows service based on template I found on stackoverflow. Built an image using it after making the necessary changes for my specific app. Ran container from generated image expecting to be able to browse to the dashboard of the app, but am encountering a 403 forbidden error whenever browsing to it.


问:
In firestore rules, allow reading only users that belong to at least one of the workspaces to which the client belongs
According to the program architecture, the "member" object has a unique pair of workspaceId and userId. Thus, each workspace has one or more members (users), while each user has one or more members (workspaces).

To prevent the client from reading users that do not belong to any of the workspaces s/he belongs to, I came up with the following firestore rule:

match /users/{userId} {
    allow read: if request.auth != null && belongsToAnyWorkspace(userId);
}

function belongsToAnyWorkspace(userId) {
    let memberWithUser = get(/databases/$(database)/documents/members/{document=**}).data;

  return memberWithUser.userId == userId && existAuth(memberWithUser)
}

function existAuth(memWithUser){
  let member = get(/databases/$(database)/documents/members/{document=**}).data;

  return member.workspaceId == memWithUser.workspaceId
             && member.userId == request.auth.uid;
}
```

The result is that firestore blocks reading for all users. My impression is that the logic of my formulas is correct, but the syntax is flawed. For example, I don't think it's correct to use there wildcard {document=**} as a way to get "any document from the collection members". Any help is appreciated!

Body:
According to the program architecture, the "member" object has a unique pair of workspaceId and userId. Thus, each workspace has one or more members (users), while each user has one or more members (workspaces).

To prevent the client from reading users that do not belong to any of the workspaces s/he belongs to, I came up with the following firestore rule:

match /users/{userId} {
    allow read: if request.auth != null && belongsToAnyWorkspace(userId);
}

function belongsToAnyWorkspace(userId) {
    let memberWithUser = get(/databases/$(database)/documents/members/{document=**}).data;

  return memberWithUser.userId == userId && existAuth(memberWithUser)
}

function existAuth(memWithUser){
  let member = get(/databases/$(database)/documents/members/{document=**}).data;

  return member.workspaceId == memWithUser.workspaceId
             && member.userId == request.auth.uid;
}

The result is that firestore blocks reading for all users. My impression is that the logic of my formulas is correct, but the syntax is flawed. For example, I don't think it's correct to use there wildcard {document=**} as a way to get "any document from the collection members". Any help is appreciated!


问:
ST_TRANSFORM not working correctly with non-standert srid
I have two tables with geometry data. One table has MULTIPOLYGON geometry in non-standard srid and another has POINT geometry in 4326. I have a spatial_ref_sys table with a correct description for my srid. Then I want to use st_contains for geometry from these tables. I use st_transform to convert geometry from one table to srid from another, but the function returns geometry under Africa (all geometry is on the territory of Europe). Also, I want to admit that I use proj description from QGIS, and in this program, all works correctly. I use PostGIS 3.2. Here is my code for st_contains:

```<code>select st_contains(st_transform(geom_multipolygon_in_4326, SRID_from_another_table), geom_point_in_non_standart_srid);
</code>```

Here is my proj:

```<code>+proj=tmerc +lat_0=0 +lon_0=30 +k=1 +x_0=-10000 +y_0=-5540000 +ellps=krass +towgs84=23.92,-141.27,-80.9,0,0.35,0.82,-0.12000000004786 +units=m +no_defs
</code>```

However, when I use PostGIS 2.2 all works correctly with an identical proj description. I don't understand what the problem is. Maybe someone can help me, because I only found a solution by creating a layer in qgis and then importing it into the database, but this is not a solution for me, because the point geometry is formed through a query to Google and I still need to transform it using st_transform.

Body:
I have two tables with geometry data. One table has MULTIPOLYGON geometry in non-standard srid and another has POINT geometry in 4326. I have a spatial_ref_sys table with a correct description for my srid. Then I want to use st_contains for geometry from these tables. I use st_transform to convert geometry from one table to srid from another, but the function returns geometry under Africa (all geometry is on the territory of Europe). Also, I want to admit that I use proj description from QGIS, and in this program, all works correctly. I use PostGIS 3.2. Here is my code for st_contains:

select st_contains(st_transform(geom_multipolygon_in_4326, SRID_from_another_table), geom_point_in_non_standart_srid);

Here is my proj:

+proj=tmerc +lat_0=0 +lon_0=30 +k=1 +x_0=-10000 +y_0=-5540000 +ellps=krass +towgs84=23.92,-141.27,-80.9,0,0.35,0.82,-0.12000000004786 +units=m +no_defs

However, when I use PostGIS 2.2 all works correctly with an identical proj description. I don't understand what the problem is. Maybe someone can help me, because I only found a solution by creating a layer in qgis and then importing it into the database, but this is not a solution for me, because the point geometry is formed through a query to Google and I still need to transform it using st_transform.


问:
Can't Knit to HTML my R markdown file in R studio
Error message

Here is the error message. The R markdown file can run just fine from top to bottom. But I'm not sure why it says cannot open connection

I tried seeing if there was an error with my directory path but it was fine


问:
Spring boot Java JPA saveAll not saving all data
I am trying to get some data from CSV file and then save it on start of the application. But when i run saveAll() of the repo it will save only up to 348 rows to the DB while the file has over 400 rows in. I can see in the debbuger that correct amount of data is passed to the saving method.

```<code>@SpringBootApplication
@EnableJpaRepositories("com.example.demo")
public class DemoApplication {

    private final StationsServicesImpl stationsServices;

    public DemoApplication(StationsServicesImpl stationsServices) {
        this.stationsServices = stationsServices;
    }

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    public List<CsvStations> parseCSVToCSVStationsObject() throws IOException {
        Reader reader = Files.newBufferedReader(Paths.get("src/main/resources/stations.csv"));
        CsvToBean<CsvStations> csvToBean = new CsvToBeanBuilder(reader).withType(CsvStations.class).withIgnoreLeadingWhiteSpace(false).build();
        List<CsvStations> csvStations = csvToBean.parse();
        return csvStations;
    }

    @EventListener(ApplicationReadyEvent.class)
    public void onStartApp() throws IOException {
        List<StationsDAO> stations = parseCSVToCSVStationsObject().stream()
                    .map(s -> new StationsDAO(
                                Long.parseLong(s.getId()),
                                s.getName(),
                                s.getAdress(),
                                s.getKaupunki(),
                                s.getKapasiteet(),
                                s.getOperaattor(),
                                s.getX(),
                                s.getY()
                    )).collect(Collectors.toList());

        stationsServices.addStations(stations);
    }
}
</code>```

the addStations() method inside has just basically .saveAll() of JpaRepository;

I've tried also to loop and use just the .save() method but still same thing and tried to change this too spring.jpa.properties.hibernate.jdbc.batch_size=100.

Body:
I am trying to get some data from CSV file and then save it on start of the application. But when i run saveAll() of the repo it will save only up to 348 rows to the DB while the file has over 400 rows in. I can see in the debbuger that correct amount of data is passed to the saving method.

@SpringBootApplication
@EnableJpaRepositories("com.example.demo")
public class DemoApplication {

    private final StationsServicesImpl stationsServices;

    public DemoApplication(StationsServicesImpl stationsServices) {
        this.stationsServices = stationsServices;
    }

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    public List<CsvStations> parseCSVToCSVStationsObject() throws IOException {
        Reader reader = Files.newBufferedReader(Paths.get("src/main/resources/stations.csv"));
        CsvToBean<CsvStations> csvToBean = new CsvToBeanBuilder(reader).withType(CsvStations.class).withIgnoreLeadingWhiteSpace(false).build();
        List<CsvStations> csvStations = csvToBean.parse();
        return csvStations;
    }

    @EventListener(ApplicationReadyEvent.class)
    public void onStartApp() throws IOException {
        List<StationsDAO> stations = parseCSVToCSVStationsObject().stream()
                    .map(s -> new StationsDAO(
                                Long.parseLong(s.getId()),
                                s.getName(),
                                s.getAdress(),
                                s.getKaupunki(),
                                s.getKapasiteet(),
                                s.getOperaattor(),
                                s.getX(),
                                s.getY()
                    )).collect(Collectors.toList());

        stationsServices.addStations(stations);
    }
}

the addStations() method inside has just basically .saveAll() of JpaRepository;

I've tried also to loop and use just the .save() method but still same thing and tried to change this too spring.jpa.properties.hibernate.jdbc.batch_size=100.


问:
Where to obtain Crystal Reports XI R2 service packs in 2023
Does anyone know where I can obtain Crystal Reports XI R2 service packs in 2023?  All the SAP links appear to be broken.</p>


问:
Why using remove for minus values they are still in list?
I wrote the function which supposed to remove minus values from the list.
Function removes all minus values except -3 and i have no idea why

```<code>def trzecia():
    lista = [2, -1, 3, -2, -3]
    for x in lista:
        if x < 0:
            lista.remove(x)
    print(lista)

trzecia()
</code>```

Could someone explain me why -3 is still on list?

Body:
I wrote the function which supposed to remove minus values from the list.
Function removes all minus values except -3 and i have no idea why

def trzecia():
    lista = [2, -1, 3, -2, -3]
    for x in lista:
        if x < 0:
            lista.remove(x)
    print(lista)

trzecia()

Could someone explain me why -3 is still on list?


问:
Any way to determine if HTML5 viewport is occluded by other windows in popular browsers?
I doubt there would be a general Javascript method for doing this, but is there perhaps any way to determine if the viewport or window.document (the renderable portion of the window) is occluded by other windows prior to the window.document regaining focus?

The reason I want this functionality is that I would like to, upon regaining focus, avoid the typical input processing of the first left mouse click on the window if and only if the window was at least partially occluded. A person who has full visibility of the window intuitively expects that first click to cause interaction, regardless of focus status, however, if the window is obstructed, that first click is typically made with the intent bringing the window to the forefront without interaction.

All searches are yielding are methods to determine if an element is visible in your viewport, which is completely different.

Edit: I noticed that finance.yahoo.com has videos that are automatically muted when they are not visible. I'm not sure how that is accomplished, but perhaps the same mechanism could be used if someone knows what it is.


问:
Create a text file from data in a worksheet based on values in the worksheet
I have an excel worksheet where i need to pull data from a columns based on other columns.  So if column Filename is SysInfoMgrServices.csv and column 7.4 J2 = "x" then i need the value in column variable name to be appended to a text document. See image. I would like it to loop through find all of the values in column B variable name if there is a corresponding value of "x" in column E 7.4 J2 and a corresponding value in column A SysInfoMgrServices.csv then insert into a text file. So if column 1 = SysInfoMgrServices.csv and column 2 = x bring back column 3 and insert into a text file. - Thanks

Tried recording macros but not confident in will loop through worksheet.  Tried using filters.


问:
Python typevar signature for function that extracts objects of a specific type from a nested dictionary
I have some data organized into the following structure:

```<code>T = TypeVar("T")

my_data: Dict[type[T], Dict[str, List[T]]] = dict()
</code>```

Thus, given a type T, this dictionary will return another dictionary that is keyed by a string identifier, mapping to a list of objects of the type T.

To appease my python typechecker, I want to write a function that extracts data from the dictionary when given a type T and the string identifier. Something like this:

```<code>def _extract_by_type_and_id(self, some_data:Dict[Type[T], Dict[str, List[T]]], some_type:Type[T], batch_id:str) -> tuple[T, ...]:

    return tuple(some_data[some_type][batch_id])
</code>```

Then I call my function like this:

```<code>_extract_by_type_and_id(my_data, MyClass, my_id)
</code>```

The problem is, when I try to use this function, and assign the output to something that expect a Tuple[MyClass, ...], the type checker is still upset, saying that the function returns one of two types: the schema specified, or the generic type:

```<code>Argument of type "tuple[MyClass | T@_extract_by_type_and_id, ...]" cannot be assigned to parameter "my_class_objects" of type "Tuple[MySchema, ...]"
</code>```

The key here being that for some reason, a union of MySchema and T@_extract_by_type_and_id are being returned by that function. Is there some way to specify that the function can accept these generic types T, but whichever type R is passed into the some_type parameter is the one (and only one) that the function should return?

Thank you in advance

Body:
I have some data organized into the following structure:

T = TypeVar("T")

my_data: Dict[type[T], Dict[str, List[T]]] = dict()

Thus, given a type T, this dictionary will return another dictionary that is keyed by a string identifier, mapping to a list of objects of the type T.

To appease my python typechecker, I want to write a function that extracts data from the dictionary when given a type T and the string identifier. Something like this:

def _extract_by_type_and_id(self, some_data:Dict[Type[T], Dict[str, List[T]]], some_type:Type[T], batch_id:str) -> tuple[T, ...]:

    return tuple(some_data[some_type][batch_id])

Then I call my function like this:

_extract_by_type_and_id(my_data, MyClass, my_id)

The problem is, when I try to use this function, and assign the output to something that expect a Tuple[MyClass, ...], the type checker is still upset, saying that the function returns one of two types: the schema specified, or the generic type:

Argument of type "tuple[MyClass | T@_extract_by_type_and_id, ...]" cannot be assigned to parameter "my_class_objects" of type "Tuple[MySchema, ...]"

The key here being that for some reason, a union of MySchema and T@_extract_by_type_and_id are being returned by that function. Is there some way to specify that the function can accept these generic types T, but whichever type R is passed into the some_type parameter is the one (and only one) that the function should return?

Thank you in advance


问:
Problem with interacting between blocs in flutter_bloc
I have problem updating a bloc from outside. Allow me to explain.

I have a master/detail sort of page. At some point the detail widget got complicated, and I decided to break it to its own Bloc.

The master looks like this:

```<code>PageView.builder(
                itemCount: state.count, // Can be null
                controller: pageController,
                itemBuilder: (context, index) {
                  log.fine('loading $index');
                  return _Child(data: state.items[index]);
                }
            ))
</code>```

Now the _Child looks like this:

```<code>class _Child extends StatelessWidget {
  final Item data;

  const _Child({Key? key, required this.data}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (_) =>
          ChildBloc(
              context.read<AuthenticationBloc>(),
              data),
      child: PostWidget(data),
    );
  }
}
</code>```

The problem is, the create method is called just once as long as it is mounted. So the future calls to the _Child(data) doesn't create the ChildBloc even though it recreates the _child widget.

How do I fix this issues?

Body:
I have problem updating a bloc from outside. Allow me to explain.

I have a master/detail sort of page. At some point the detail widget got complicated, and I decided to break it to its own Bloc.

The master looks like this:

PageView.builder(
                itemCount: state.count, // Can be null
                controller: pageController,
                itemBuilder: (context, index) {
                  log.fine('loading $index');
                  return _Child(data: state.items[index]);
                }
            ))

Now the _Child looks like this:

class _Child extends StatelessWidget {
  final Item data;

  const _Child({Key? key, required this.data}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (_) =>
          ChildBloc(
              context.read<AuthenticationBloc>(),
              data),
      child: PostWidget(data),
    );
  }
}

The problem is, the create method is called just once as long as it is mounted. So the future calls to the _Child(data) doesn't create the ChildBloc even though it recreates the _child widget.

How do I fix this issues?


问:
graphqql codegen enums are not found when referenced in resolvers
My schema is defined:

```<code>export default gql`
  enum MyCoolEnum {
    A
    B
    C
  }

  extend type Mutation {
    changeValue(
      valueToChange: MyCoolEnum!
    ): JSON
  }
`;

</code>```

Which produces the following in the generatedSchema

```<code>export enum MyCoolEnum {
  A = 'A',
  B = 'B',
  C = 'C'
}
</code>```

And my codegen.yml looks like

```<code>schema: schema.graphql
generates:
  ./src/types/__generated__/graphqlSchema.ts:
    plugins:
      - typescript
      - typescript-resolvers
</code>```

In my resolver this works

```<code>import { Resolvers, MyCoolEnum } from 'types/__generated__/graphqlSchema';

const resolvers: Resolvers = {
  Mutation: {
    changeValue: async (_, { valueToChange }) => {
      if (valueToChange === 'A') {
        // change A value
      } else if (valueToChange === 'B') {
        // change B value
      } else {
        // change C value
      }
    },
  },
};
</code>```

But the second I reference the generated enum, like the following, I get Error: Cannot find module 'types/__generated__/graphqlSchema'

```<code>import { Resolvers, MyCoolEnum } from 'types/__generated__/graphqlSchema';

const resolvers: Resolvers = {
  Mutation: {
    changeValue: async (_, { valueToChange }) => {
      if (valueToChange === MyCoolEnum.A) {
</code>```

Body:
My schema is defined:

export default gql`
  enum MyCoolEnum {
    A
    B
    C
  }

  extend type Mutation {
    changeValue(
      valueToChange: MyCoolEnum!
    ): JSON
  }
`;

Which produces the following in the generatedSchema

export enum MyCoolEnum {
  A = 'A',
  B = 'B',
  C = 'C'
}

And my codegen.yml looks like

schema: schema.graphql
generates:
  ./src/types/__generated__/graphqlSchema.ts:
    plugins:
      - typescript
      - typescript-resolvers

In my resolver this works

import { Resolvers, MyCoolEnum } from 'types/__generated__/graphqlSchema';

const resolvers: Resolvers = {
  Mutation: {
    changeValue: async (_, { valueToChange }) => {
      if (valueToChange === 'A') {
        // change A value
      } else if (valueToChange === 'B') {
        // change B value
      } else {
        // change C value
      }
    },
  },
};

But the second I reference the generated enum, like the following, I get Error: Cannot find module 'types/__generated__/graphqlSchema'

import { Resolvers, MyCoolEnum } from 'types/__generated__/graphqlSchema';

const resolvers: Resolvers = {
  Mutation: {
    changeValue: async (_, { valueToChange }) => {
      if (valueToChange === MyCoolEnum.A) {


问:
Check If User Input Is Valid
Current Code:

```<code>def character_a():

    character_a = input('Enter First Dot or Dash (. / -): ')

character_a()

if not character_a == "." or "-":
    print('Invalid Character.. Try Again')
    character_a()

else:
    print('Valid Character')
</code>```

Hello Im trying to write a python script where it asks you for a input of either a "." or "-" only problem is that you can in theory do any other letter or number. And I got it to check if its a character like a,b,c,etc But not Numbers How Can i make sure they only do "-", ".". And for my future code how can I also check to make sure they either do "-", ".", or "0" And not some other random character/digit like ; or ] etc etc.

Title: Check If User Input Is Valid

Body:
Current Code:

def character_a():

    character_a = input('Enter First Dot or Dash (. / -): ')

character_a()

if not character_a == "." or "-":
    print('Invalid Character.. Try Again')
    character_a()

else:
    print('Valid Character')

Hello Im trying to write a python script where it asks you for a input of either a "." or "-" only problem is that you can in theory do any other letter or number. And I got it to check if its a character like a,b,c,etc But not Numbers How Can i make sure they only do "-", ".". And for my future code how can I also check to make sure they either do "-", ".", or "0" And not some other random character/digit like ; or ] etc etc.


问:
Cannot read properties of undefined error when passing function as parameter from service
I have to pass a function of service as a parameter to another function. Whenever, I try to pass function as parameter and it executes, then I get error 'Cannot read properties of undefined myService'

When I call this.myService.method() individually. It's completely working fine. There is no problem. What could be the issue?

My ts file:

```<code>constructor(private myService: MyService)

     function1(): void {
            this.function2(this.myService.method)
        }

    function2(f: Function)
    {
        f();

    }
</code>```

Body:
I have to pass a function of service as a parameter to another function. Whenever, I try to pass function as parameter and it executes, then I get error 'Cannot read properties of undefined myService'

When I call this.myService.method() individually. It's completely working fine. There is no problem. What could be the issue?

My ts file:

constructor(private myService: MyService)

     function1(): void {
            this.function2(this.myService.method)
        }

    function2(f: Function)
    {
        f();

    }


问:
How can I use dbstl::db_map<string, list<string>> in Berkeley DB C++?
How can i use dbstl::db_map<string, list< string>>?
I use Berkeley DB STL in C++ and Visual Studio 2015

I want to use list< string> as value of db_map, but i get an error. I understand that no one does this, but i need to do this on assignment. How can i fix this error?  Perhaps there is some alternative solution?

My code:

```<code>#define _CRT_SECURE_NO_WARNINGS
#pragma comment(lib, "libdb181.lib")
#pragma comment(lib, "libdb_stl181.lib")

#include "stdafx.h"
#include <iostream>
#include <dbstl_map.h>
#include <list>
using namespace std;

int main(){
    const char* db_name = "db";
    const char* db_home_dir = "dbdir";

    DbEnv env(DB_CXX_NO_EXCEPTIONS);
    Db* pdb;

    try {
        dbstl::dbstl_startup();

        env.set_error_stream(&cerr);
        env.open(db_home_dir, DB_CREATE | DB_INIT_MPOOL, 0);

        pdb = new Db(&env, DB_CXX_NO_EXCEPTIONS);
        pdb->open(NULL, db_name, NULL, DB_BTREE, DB_CREATE, 0);

        typedef dbstl::db_map<string, list<string>> dbmap_list;
        dbmap_list map_list(pdb, &env);

        string key_list = "list";
        list<string> value_list;
        value_list.push_back("first"); value_list.push_back("second");
        map_list.insert({ key_list, value_list });

        list<string> outvalue_list = map_list[key_list];
        list<string>::iterator it = outvalue_list.begin();
        cout << *it;

        dbstl::dbstl_exit();

        if (pdb != NULL) {
            pdb->close(0);
            delete pdb;
        }
        env.close(0);

    }
    catch (DbException& e) {
        cerr << "DbException: " << e.what() << endl;
        _sleep(5000);
        return -1;
    }
    catch (std::exception& e) {
        cerr << e.what() << endl;
        _sleep(5000);
        return -1;
    }

    cout << "hello";
    _sleep(5000);
    return 0;
}
</code>```

My error:

Program: C:\Windows\SYSTEM32\MSVCP140D.dll File: C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\list Line: 211

Expression: list iterator not dereferencable

For information on how your program can cause an assertion failure,
see the Visual C++ documentation on asserts.

(Press Retry to debug the application) ConsoleApplication8.exe has
triggered a breakpoint.

Debug Assertion Failed!

Program:
..._V36\p1\ConsoleApplication8\x64\Debug\ConsoleApplication8.exe File:
C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\list
Line: 212

Expression: "Standard C++ Libraries Out of Range" && 0

For information on how your program can cause an assertion failure,
see the Visual C++ documentation on asserts.

(Press Retry to debug the application) 'ConsoleApplication8.exe'
(Win32): Loaded
'C:\Windows\assembly\GAC_MSIL\Microsoft.VisualStudio.Debugger.Runtime\14.0.0.0__b03f5f7f11d50a3a\Microsoft.VisualStudio.Debugger.Runtime.dll'.
'ConsoleApplication8.exe' (Win32): Loaded
'C:\Windows\assembly\GAC_MSIL\Microsoft.VisualStudio.Debugger.Runtime\14.0.0.0__b03f5f7f11d50a3a\Microsoft.VisualStudio.Debugger.Runtime.dll'.
'ConsoleApplication8.exe' (Win32): Unloaded
'C:\Windows\assembly\GAC_MSIL\Microsoft.VisualStudio.Debugger.Runtime\14.0.0.0__b03f5f7f11d50a3a\Microsoft.VisualStudio.Debugger.Runtime.dll' 'ConsoleApplication8.exe' (CLR v4.0.30319: ConsoleApplication8.exe):
Loaded
'C:\Windows\assembly\GAC_MSIL\Microsoft.VisualStudio.Debugger.Runtime\14.0.0.0__b03f5f7f11d50a3a\Microsoft.VisualStudio.Debugger.Runtime.dll'.
Unhandled exception at 0x00007FFB60CF10CB (ucrtbased.dll) in
ConsoleApplication8.exe: An invalid parameter was passed to a function
that considers invalid parameters fatal.

Body:
How can i use dbstl::db_map<string, list< string>>?
I use Berkeley DB STL in C++ and Visual Studio 2015

I want to use list< string> as value of db_map, but i get an error. I understand that no one does this, but i need to do this on assignment. How can i fix this error?  Perhaps there is some alternative solution?

My code:

#define _CRT_SECURE_NO_WARNINGS
#pragma comment(lib, "libdb181.lib")
#pragma comment(lib, "libdb_stl181.lib")

#include "stdafx.h"
#include <iostream>
#include <dbstl_map.h>
#include <list>
using namespace std;

int main(){
    const char* db_name = "db";
    const char* db_home_dir = "dbdir";

    DbEnv env(DB_CXX_NO_EXCEPTIONS);
    Db* pdb;

    try {
        dbstl::dbstl_startup();

        env.set_error_stream(&cerr);
        env.open(db_home_dir, DB_CREATE | DB_INIT_MPOOL, 0);

        pdb = new Db(&env, DB_CXX_NO_EXCEPTIONS);
        pdb->open(NULL, db_name, NULL, DB_BTREE, DB_CREATE, 0);

        typedef dbstl::db_map<string, list<string>> dbmap_list;
        dbmap_list map_list(pdb, &env);

        string key_list = "list";
        list<string> value_list;
        value_list.push_back("first"); value_list.push_back("second");
        map_list.insert({ key_list, value_list });

        list<string> outvalue_list = map_list[key_list];
        list<string>::iterator it = outvalue_list.begin();
        cout << *it;

        dbstl::dbstl_exit();

        if (pdb != NULL) {
            pdb->close(0);
            delete pdb;
        }
        env.close(0);

    }
    catch (DbException& e) {
        cerr << "DbException: " << e.what() << endl;
        _sleep(5000);
        return -1;
    }
    catch (std::exception& e) {
        cerr << e.what() << endl;
        _sleep(5000);
        return -1;
    }

    cout << "hello";
    _sleep(5000);
    return 0;
}

My error:

Program: C:\Windows\SYSTEM32\MSVCP140D.dll File: C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\list Line: 211

Expression: list iterator not dereferencable

For information on how your program can cause an assertion failure,
see the Visual C++ documentation on asserts.

(Press Retry to debug the application) ConsoleApplication8.exe has
triggered a breakpoint.

Debug Assertion Failed!

Program:
..._V36\p1\ConsoleApplication8\x64\Debug\ConsoleApplication8.exe File:
C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\list
Line: 212

Expression: "Standard C++ Libraries Out of Range" && 0

For information on how your program can cause an assertion failure,
see the Visual C++ documentation on asserts.

(Press Retry to debug the application) 'ConsoleApplication8.exe'
(Win32): Loaded
'C:\Windows\assembly\GAC_MSIL\Microsoft.VisualStudio.Debugger.Runtime\14.0.0.0__b03f5f7f11d50a3a\Microsoft.VisualStudio.Debugger.Runtime.dll'.
'ConsoleApplication8.exe' (Win32): Loaded
'C:\Windows\assembly\GAC_MSIL\Microsoft.VisualStudio.Debugger.Runtime\14.0.0.0__b03f5f7f11d50a3a\Microsoft.VisualStudio.Debugger.Runtime.dll'.
'ConsoleApplication8.exe' (Win32): Unloaded
'C:\Windows\assembly\GAC_MSIL\Microsoft.VisualStudio.Debugger.Runtime\14.0.0.0__b03f5f7f11d50a3a\Microsoft.VisualStudio.Debugger.Runtime.dll' 'ConsoleApplication8.exe' (CLR v4.0.30319: ConsoleApplication8.exe):
Loaded
'C:\Windows\assembly\GAC_MSIL\Microsoft.VisualStudio.Debugger.Runtime\14.0.0.0__b03f5f7f11d50a3a\Microsoft.VisualStudio.Debugger.Runtime.dll'.
Unhandled exception at 0x00007FFB60CF10CB (ucrtbased.dll) in
ConsoleApplication8.exe: An invalid parameter was passed to a function
that considers invalid parameters fatal.


问:
When connecting to owncloud i get 'You are accessing the server from an untrusted domain'
Just installed owncloud using the instructions in https://doc.owncloud.com/server/next/admin_manual/installation/docker/ and when I try to connect to the server from my machine I get the following error message...

```<code>You are accessing the server from an untrusted domain.
Please contact your administrator. If you are an administrator of this instance, configure the "trusted_domains" setting in config/config.php. An example configuration is provided in config/config.sample.php or at the documentation.
</code>```

IK what the error message means and how I would normally fix it in a standard apache setup, but how do I change these in the docker images?

I tried changing the line OWNCLOUD_TRUSTED_DOMAINS in the .env file to a wildcard (originally it said localhost) and that did not help.

Body:
Just installed owncloud using the instructions in https://doc.owncloud.com/server/next/admin_manual/installation/docker/ and when I try to connect to the server from my machine I get the following error message...

You are accessing the server from an untrusted domain.
Please contact your administrator. If you are an administrator of this instance, configure the "trusted_domains" setting in config/config.php. An example configuration is provided in config/config.sample.php or at the documentation.

IK what the error message means and how I would normally fix it in a standard apache setup, but how do I change these in the docker images?

I tried changing the line OWNCLOUD_TRUSTED_DOMAINS in the .env file to a wildcard (originally it said localhost) and that did not help.


问:
kubernetes on Oracle OCI Always free exec format error
I create a cluster kuberntes using the Shape: VM.Standard.A1.Flex(Ampere arm-based processor)
I'm using terraform amperetacle

I'm created a golang project and created the Dockerfile

```<code>FROM golang:1.18 AS build
COPY ./api /api
WORKDIR /api
COPY . .

RUN CGO_ENABLED=0 GOOS=linux go build -mod vendor -a -o ./processor ./cmd/processor

FROM alpine
RUN apk add --no-cache ca-certificates
RUN mkdir /app
COPY --from=build /api/processor /app/processor
WORKDIR /app
RUN chmod +x /app/processor
CMD ["./processor"]
</code>```

If I run image it works

But when kubernets run

exec ./processor: exec format error

Body:
I create a cluster kuberntes using the Shape: VM.Standard.A1.Flex(Ampere arm-based processor)
I'm using terraform amperetacle

I'm created a golang project and created the Dockerfile

FROM golang:1.18 AS build
COPY ./api /api
WORKDIR /api
COPY . .

RUN CGO_ENABLED=0 GOOS=linux go build -mod vendor -a -o ./processor ./cmd/processor

FROM alpine
RUN apk add --no-cache ca-certificates
RUN mkdir /app
COPY --from=build /api/processor /app/processor
WORKDIR /app
RUN chmod +x /app/processor
CMD ["./processor"]

If I run image it works

But when kubernets run

exec ./processor: exec format error


问:
Android scoped storage access permissions not enforced?
Having difficulty understanding scoped storage and how it is used and enforced.
According to the android docs here -> https://developer.android.com/training/data-storage/shared/media#storage-permission

```<code>To access media files that other apps have created, you must declare the appropriate
storage-related permissions, and the files must reside in one of the following media
collections:

MediaStore.Images
MediaStore.Video
MediaStore.Audio
</code>```

I have an app that expects to attach local files - images or PDFs - to an invoice.  Running on a device running Android 13, I would have expected, given the documentation, that my app would not be able to access an image created by a 3rd party app, but that's not the case.  The app can access any file, whether is downloads, a specific folder from a 3rd party app.  I haven't added any extra permissions but the app has no issues pulling images from a tiktok folder, or anywhere.

Maybe I don't understand the phrase "media files that other apps have created" - I would have thought a TIkTok video, or Lensa image or Toon-Art images in their respective folders would not be accessible from another app, but they are.

What am I missing here?

Body:
Having difficulty understanding scoped storage and how it is used and enforced.
According to the android docs here -> https://developer.android.com/training/data-storage/shared/media#storage-permission

To access media files that other apps have created, you must declare the appropriate
storage-related permissions, and the files must reside in one of the following media
collections:

MediaStore.Images
MediaStore.Video
MediaStore.Audio

I have an app that expects to attach local files - images or PDFs - to an invoice.  Running on a device running Android 13, I would have expected, given the documentation, that my app would not be able to access an image created by a 3rd party app, but that's not the case.  The app can access any file, whether is downloads, a specific folder from a 3rd party app.  I haven't added any extra permissions but the app has no issues pulling images from a tiktok folder, or anywhere.

Maybe I don't understand the phrase "media files that other apps have created" - I would have thought a TIkTok video, or Lensa image or Toon-Art images in their respective folders would not be accessible from another app, but they are.

What am I missing here?


问:
Is there a way to override Jekyll's link validation when using the link tag?
Is there a way to override Jekyll's link validation when using the {% link %} tag?

Per the Jekyll docs:

One major benefit of using the link or post_url tag is link
validation. If the link doesn’t exist, Jekyll won’t build your site.
This is a good thing, as it will alert you to a broken link so you can
fix it (rather than allowing you to build and deploy a site with
broken links).

But I want to allow broken links in some of my documents - or at the very least, I want Jekyll to build the rest of my site.  Can I override this on a case-by-case basis (i.e. wrap the link tag with some other tag)?  Is there a _config.yml setting I can use?  A plugin?

And while I appreciate good-natured questions/suggestions such as "you shouldn't build a site with broken links!" please know this site is just for me, not the world at large.  I'll know what to do with my own 404, I promise :)


Title: Java error class [D cannot be cast to class java.lang.Comparable ([D and java.lang.Comparable are in module java.base of loader 'bootstrap'). why?

Body:
I ran out of room in the title, so I will explain more here.  In my code, I am trying to find where the highest value lies in the array.  I get an exception on the binary search.  Can anybody help me figure out why this is happening?

import java.util.Arrays;
import java.util.*;

public class Q {

    static double [][] Q = {
            {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
            {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,},
            {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
            {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}
    };
    static int state = 0 - 0;
    static int next = 0;
    static int reward = 0;
    static int action = 0;
    public static void main(String[] args) {
        //System.out.println(state);
        // TODO Auto-generated method stub
        for(int i = 0; i < 100000   ; i++) {
            System.out.println("new");
        int rand = (int) (Math.random()* 4) + 1;
        rand = rand - 1;
        if(((int)Math.random() *2) + 1 == 1) {
        if(Q[state][0] == Q[state][1] &&
                Q[state][1] == Q[state][2] &&
                Q[state][2] == Q[state][3]//0 &&
                        ) {
            //  Q[state][3]);
        action = rand;
        } else {
            action = Arrays.binarySearch(Q,
                    Math.max(Q[state][0], Math.max(Q[state][1], Math.max(Q[state][2], Q[state][3]))));
        }
        }//
        //
        //
    //  M////
        else {
            action = rand;
        }

I have no idea why this error randomely started happening.


问:
Flutter build ipa -allowProvisioningUpdates
I'm working on a custom CI system using shell.

I have a script, that sets up a flutter project (according to a specified configuration). Basically it looks like that:

Read config

Read secrets

Create a new Flutter Project

flutter clean

Swap some files (like AndroidManifest.xml, Info.plist) in order to configure the app for release

flutter pub get

flutterfire configure

Swap app assets and generate app icons

A ruby script that enables push notifications capability

Build aab and ipa

Upload to GP and AS

Everything works fine, except the build ipa part. I get the error:

```<code>Error (Xcode): No profiles for 'x.y.z.a' were found: Xcode couldn't find any iOS App Development provisioning profiles matching 'x.y.z.a'. Automatic signing is disabled and unable to generate a profile. To enable automatic signing, pass -allowProvisioningUpdates to xcodebuild.
/Users/me/Repos/mynewproject/mynewapp/ios/Runner.xcodeproj
</code>```

The provisioning profile already exists in App Store Connect. I just need to make sure it's available for the build.

I suppose something is wrong with Xcodes automatic signing, I would need to find a way to programmatically configure the Xcode project so that it allows Provisioning Updates. Maybe is there a way to set something, so that the -allowProvisioningUpdates flag will be passed to xcodebuild, when running flutter build ipa?

Body:
I'm working on a custom CI system using shell.

I have a script, that sets up a flutter project (according to a specified configuration). Basically it looks like that:

Read config

Read secrets

Create a new Flutter Project

flutter clean

Swap some files (like AndroidManifest.xml, Info.plist) in order to configure the app for release

flutter pub get

flutterfire configure

Swap app assets and generate app icons

A ruby script that enables push notifications capability

Build aab and ipa

Upload to GP and AS

Everything works fine, except the build ipa part. I get the error:

Error (Xcode): No profiles for 'x.y.z.a' were found: Xcode couldn't find any iOS App Development provisioning profiles matching 'x.y.z.a'. Automatic signing is disabled and unable to generate a profile. To enable automatic signing, pass -allowProvisioningUpdates to xcodebuild.
/Users/me/Repos/mynewproject/mynewapp/ios/Runner.xcodeproj

The provisioning profile already exists in App Store Connect. I just need to make sure it's available for the build.

I suppose something is wrong with Xcodes automatic signing, I would need to find a way to programmatically configure the Xcode project so that it allows Provisioning Updates. Maybe is there a way to set something, so that the -allowProvisioningUpdates flag will be passed to xcodebuild, when running flutter build ipa?


问:
equating java classes with different annotations
If we have the following condition

Server Domain class

```<code>package com.server;
class A {
    @Foo
    B b;

    @Foo
    int c;
}
</code>```

Now on the server we do..

```<code>Gson gson = new Gson();
String json = gson.toJson(storeOfListsOfChangedDomainObjectsOnClient);
</code>```

and send the json to the client ....

Also we take the server domain class, and put it on the client with the same package name, but different annotations, as follows

Client Domain class

```<code>package com.server;
class A {
    @Bar
    B b;

    @Bar
    int c;
}
</code>```

on the client we do....

```<code>Gson gson = new Gson();
</code>```

is the following correct ........

```<code>com.server.A response = gson.fromJson(json, A.class);
</code>```

Will the object be equated?

Because otherwise, we will have to take each response class (domain class) of the server and copy each variable individually to the domain class of the client.

Also, the @Foo and @Bar are Hibernate annotation on the Server side, and ORMLite annotations (for Android) on the client side.

ContentLicense: CC BY-SA 3.0

Body:
If we have the following condition

Server Domain class

package com.server;
class A {
    @Foo
    B b;

    @Foo
    int c;
}

Now on the server we do..

Gson gson = new Gson();
String json = gson.toJson(storeOfListsOfChangedDomainObjectsOnClient);

and send the json to the client ....

Also we take the server domain class, and put it on the client with the same package name, but different annotations, as follows

Client Domain class

package com.server;
class A {
    @Bar
    B b;

    @Bar
    int c;
}

on the client we do....

Gson gson = new Gson();

is the following correct ........

com.server.A response = gson.fromJson(json, A.class);

Will the object be equated?

Because otherwise, we will have to take each response class (domain class) of the server and copy each variable individually to the domain class of the client.

Also, the @Foo and @Bar are Hibernate annotation on the Server side, and ORMLite annotations (for Android) on the client side.


问:
How can I get the full precision of a decimal from a stored procedure using Hibernate?
I have a SQL Server 2019 stored procedure with a output parameter of decimal(38,36). I call the stored procedure from a Spring Repository (using latest version of Spring Boot at time of writing):

```<code>//code in service layer that calls stored procedure via Spring repo
BigDecimal value = metricRepository.getMetricValue("myMetric");
</code>```

value should be to 36 decimals. Instead I get a value rounded to four decimal places. Why don't I get all decimal places? What should I do to get all 36 decimal places?

Here's what I'm using to print the value:

```<code>pw.printf("%38.34f,%n", value); //pw is a PrintWriter
</code>```

For example, if the database returns

0.0622665006200000000000000000000000

the code above will print:

0.0623000000000000000000000000000000

Here is my repository and domain object:

```<code>public interface MetricRepository extends Repository<Metric, Long> {

    @Transactional
    @Procedure(name = "Metric.metricProc", outputParameterName = "value")
    BigDecimal getMetricValue(@Param("metricname") String name);

}

@Entity
@NamedStoredProcedureQuery(name = "Metric.metricProc", procedureName = "Metric.metricCapProc", parameters = {
          @StoredProcedureParameter(mode = ParameterMode.IN, name = "metricname", type = String.class),
          @StoredProcedureParameter(mode = ParameterMode.OUT, name = "anotherOutParam", type = BigDecimal.class),
          @StoredProcedureParameter(mode = ParameterMode.OUT, name = "value", type = BigDecimal.class)})
public class Metric {

    @Id
    public String metricName;

}
</code>```

Update

When I change output param type to Double, I get the full precision. But according to Microsoft, the SQL Server type DECIMAL should map to BigDecimal?!? So, I'm still wondering why I can't get full precision using BigDecimal and a little concerned about the accuracy of using Double.

```<code>@StoredProcedureParameter(mode = ParameterMode.OUT, name = "value", type = Double.class)
</code>```

Update 2

This decision to round appears to be with Hibernate. With trace logging I found the following when type is set to BigDecimal:

2023-01-12T18:24:20.728-06:00 TRACE 28576 --- [restartedMain]
org.hibernate.orm.jdbc.extract           : extracted procedure output
parameter ([3] : [NUMERIC]) - [0.0623]

With Double, the following is logged:

2023-01-12T18:25:19.851-06:00 TRACE 21980 --- [restartedMain]
org.hibernate.orm.jdbc.extract           : extracted procedure output
parameter ([3] : [FLOAT]) - [0.06226650062]

How can I tell Hibernate not to round when using BigDecimal?

I found this in the Hibernate DecimalJdbcType code but not sure if / how it's responsible for rounding:

```<code>@Override
    public <T> BasicJavaType<T> getJdbcRecommendedJavaTypeMapping(
            Integer length,
            Integer scale,
            TypeConfiguration typeConfiguration) {
        return (BasicJavaType<T>) typeConfiguration.getJavaTypeRegistry().getDescriptor( BigDecimal.class );
    }
</code>```

Update 3

I found that setting scale to 34 (number of digits to the right of decimal point) is easy using JDBC:

```<code> cs.registerOutParameter(3, Types.DECIMAL, 34);
</code>```

But still can't figure out how to do this using Hibernate. Is it not possible with Hibernate?

Body:
I have a SQL Server 2019 stored procedure with a output parameter of decimal(38,36). I call the stored procedure from a Spring Repository (using latest version of Spring Boot at time of writing):

//code in service layer that calls stored procedure via Spring repo
BigDecimal value = metricRepository.getMetricValue("myMetric");

value should be to 36 decimals. Instead I get a value rounded to four decimal places. Why don't I get all decimal places? What should I do to get all 36 decimal places?

Here's what I'm using to print the value:

pw.printf("%38.34f,%n", value); //pw is a PrintWriter

For example, if the database returns

0.0622665006200000000000000000000000

the code above will print:

0.0623000000000000000000000000000000

Here is my repository and domain object:

public interface MetricRepository extends Repository<Metric, Long> {

    @Transactional
    @Procedure(name = "Metric.metricProc", outputParameterName = "value")
    BigDecimal getMetricValue(@Param("metricname") String name);

}

@Entity
@NamedStoredProcedureQuery(name = "Metric.metricProc", procedureName = "Metric.metricCapProc", parameters = {
          @StoredProcedureParameter(mode = ParameterMode.IN, name = "metricname", type = String.class),
          @StoredProcedureParameter(mode = ParameterMode.OUT, name = "anotherOutParam", type = BigDecimal.class),
          @StoredProcedureParameter(mode = ParameterMode.OUT, name = "value", type = BigDecimal.class)})
public class Metric {

    @Id
    public String metricName;

}

Update

When I change output param type to Double, I get the full precision. But according to Microsoft, the SQL Server type DECIMAL should map to BigDecimal?!? So, I'm still wondering why I can't get full precision using BigDecimal and a little concerned about the accuracy of using Double.

@StoredProcedureParameter(mode = ParameterMode.OUT, name = "value", type = Double.class)

Update 2

This decision to round appears to be with Hibernate. With trace logging I found the following when type is set to BigDecimal:

2023-01-12T18:24:20.728-06:00 TRACE 28576 --- [restartedMain]
org.hibernate.orm.jdbc.extract           : extracted procedure output
parameter ([3] : [NUMERIC]) - [0.0623]

With Double, the following is logged:

2023-01-12T18:25:19.851-06:00 TRACE 21980 --- [restartedMain]
org.hibernate.orm.jdbc.extract           : extracted procedure output
parameter ([3] : [FLOAT]) - [0.06226650062]

How can I tell Hibernate not to round when using BigDecimal?

I found this in the Hibernate DecimalJdbcType code but not sure if / how it's responsible for rounding:

@Override
    public <T> BasicJavaType<T> getJdbcRecommendedJavaTypeMapping(
            Integer length,
            Integer scale,
            TypeConfiguration typeConfiguration) {
        return (BasicJavaType<T>) typeConfiguration.getJavaTypeRegistry().getDescriptor( BigDecimal.class );
    }

Update 3

I found that setting scale to 34 (number of digits to the right of decimal point) is easy using JDBC:

 cs.registerOutParameter(3, Types.DECIMAL, 34);

But still can't figure out how to do this using Hibernate. Is it not possible with Hibernate?


问:
How to implement Custom user defined At Least One from dynamic checkboxlist required Validation mvc
I have a dynamic checkbox list coming from sql database,
and my model to fill this dynamic checkboxes is :

```<code>public class TestModel
{
    public List<CheckboxList_model> DynamicCheckbox { get; set; }
}

public class CheckboxList_model
{
    public string Text { get; set; }

    public int Value { get; set; }

    public Boolean Selected { get; set; }

}
</code>```

after I fill DynamicCheckbox

this is my view

```<code>@for (int i = 0; i < Model.DynamicCheckbox.Count(); i++)
                            {
                                @Html.CheckBoxFor(m => m.DynamicCheckbox [i].Selected, new { @class = "flat" })

                                @Html.DisplayFor(m => m.DynamicCheckbox [i].Text)

                                @Html.HiddenFor(m => m.DynamicCheckbox [i].Value)

                            }

                            @Html.ValidationMessageFor(model => model.DynamicCheckbox , "", new { @class = "text-danger" })
</code>```

how can make sure that user select at least one checkbox server and client validation.

Thanks

Body:
I have a dynamic checkbox list coming from sql database,
and my model to fill this dynamic checkboxes is :

public class TestModel
{
    public List<CheckboxList_model> DynamicCheckbox { get; set; }
}

public class CheckboxList_model
{
    public string Text { get; set; }

    public int Value { get; set; }

    public Boolean Selected { get; set; }

}

after I fill DynamicCheckbox

this is my view

@for (int i = 0; i < Model.DynamicCheckbox.Count(); i++)
                            {
                                @Html.CheckBoxFor(m => m.DynamicCheckbox [i].Selected, new { @class = "flat" })

                                @Html.DisplayFor(m => m.DynamicCheckbox [i].Text)

                                @Html.HiddenFor(m => m.DynamicCheckbox [i].Value)

                            }

                            @Html.ValidationMessageFor(model => model.DynamicCheckbox , "", new { @class = "text-danger" })

how can make sure that user select at least one checkbox server and client validation.

Thanks


问:
Subscript out of range how to solve it
I'm trying to activate a certain sheet in my workbook but I still get the same

error 9 "Subscript out of range"

when trying to run it from the userform. When I use Debug fuction, it says that "materialWorksheet = Nothing"

```<code>Private Sub UserForm_Initialize()

    ' Activate excel sheet to store/extract data
        Set objWorkbook = Excel.workbooks("Aircraft_Final_Master_Design_Table_LITE")
        Set materialWorksheet = objWorkbook.Worksheets.item("Materials")
        materialWorksheet.Activate

</code>```

What I am trying to get as a result is to be able to acquire the values from that Materials sheet and use it for my userform.

Title: Subscript out of range how to solve it

Body:
I'm trying to activate a certain sheet in my workbook but I still get the same

error 9 "Subscript out of range"

when trying to run it from the userform. When I use Debug fuction, it says that "materialWorksheet = Nothing"

Private Sub UserForm_Initialize()

    ' Activate excel sheet to store/extract data
        Set objWorkbook = Excel.workbooks("Aircraft_Final_Master_Design_Table_LITE")
        Set materialWorksheet = objWorkbook.Worksheets.item("Materials")
        materialWorksheet.Activate

What I am trying to get as a result is to be able to acquire the values from that Materials sheet and use it for my userform.


问:
add custom key => value in rest api wordpres (/search endpoint)
I have a problem with WordPress APIs. If I add custom key => value in /search endpoint doesn't work. If I try with another endpoint like example /post it works fine, why?

```<code>add_action('rest_api_init', function () {

    register_rest_field('search', 'excerpt', array(

        'get_callback' => function ($post_arr) {

            $post_obj = get_post($post_arr['post']);

            return $post_obj->post_excerpt;

        },

        'update_callback' => function ($excerpt, $post_obj) {

            $ret = wp_update_post(array(
                'post_ID' => $post_obj->post_ID,
                'post_excerpt' => $excerpt
            ));

            if (!$ret) {
                return new WP_Error(
                    'rest_comment_karma_failed',
                    __('Failed to update comment karma.'),
                    array('status' => 500)
                );
            }
            return true;

        },
        'schema' => array(
            'description' => __('Excerpt'),
            'type' => 'string'
        ),

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

I would like to add custom key => value in /search endpoint

Body:
I have a problem with WordPress APIs. If I add custom key => value in /search endpoint doesn't work. If I try with another endpoint like example /post it works fine, why?

add_action('rest_api_init', function () {

    register_rest_field('search', 'excerpt', array(

        'get_callback' => function ($post_arr) {

            $post_obj = get_post($post_arr['post']);

            return $post_obj->post_excerpt;

        },

        'update_callback' => function ($excerpt, $post_obj) {

            $ret = wp_update_post(array(
                'post_ID' => $post_obj->post_ID,
                'post_excerpt' => $excerpt
            ));

            if (!$ret) {
                return new WP_Error(
                    'rest_comment_karma_failed',
                    __('Failed to update comment karma.'),
                    array('status' => 500)
                );
            }
            return true;

        },
        'schema' => array(
            'description' => __('Excerpt'),
            'type' => 'string'
        ),

    ));
});

I would like to add custom key => value in /search endpoint


问:
How can I get the content inside

 using Python?
I'm trying to gather the text of all the stories in League of Legends lore. I'm webscraping the page where all the short stories are listed in order to find their links and then going to those pages and saving the text.

I encountered a problem when using:

```<code>URL = "https://universe.leagueoflegends.com/es_ES/explore/short-stories/oldest/"
page = requests.get(URL)
html = page.content
champion_soup = BeautifulSoup(html, "html.parser")
</code>```

The resulting HTML file shows this at lines 233-235:

```<code><div id="App"></div>
<div id="Preloader"></div>
<div id="Footer"></div>
</code>```

However, when I inspect the page, it is inside that "App"
 where all the information I need is located. If I download the webpage directly from Chrome, that part of the HTML shows up in the file, but not when using requests.

I've read it has something to do with it being javascript code and being rendered by the client (I don't know anything about javascript so I might be completely wrong). I want to be able to open that "complete" HTML file from my Python script.

Body:
I'm trying to gather the text of all the stories in League of Legends lore. I'm webscraping the page where all the short stories are listed in order to find their links and then going to those pages and saving the text.

I encountered a problem when using:

URL = "https://universe.leagueoflegends.com/es_ES/explore/short-stories/oldest/"
page = requests.get(URL)
html = page.content
champion_soup = BeautifulSoup(html, "html.parser")

The resulting HTML file shows this at lines 233-235:

However, when I inspect the page, it is inside that "App"
 where all the information I need is located. If I download the webpage directly from Chrome, that part of the HTML shows up in the file, but not when using requests.

I've read it has something to do with it being javascript code and being rendered by the client (I don't know anything about javascript so I might be completely wrong). I want to be able to open that "complete" HTML file from my Python script.