问:
How To Use VLOOKUP function with xlsxwriter data_validation method
I have an excel file that contains two worksheets A and B, Inside sheet A, there is a column "product" which is a dropdown list whose value is coming from sheet B, I want the excel file to be configured such that, when I select a value in "product" column, I want all the other columns (they are also dropdowns) in sheet A to be populated with the values in that same column in sheet B.

How can I achieve this with Xlsxwriter and perhaps Vlookup?.

I have tried:

```<code>sheetA.data_validation(
            "M2:M10000", {
                'validate': 'list',
                'source': '=VLOOKUP(D2, SheetB!B2:P10000,5,FALSE)',
            }
        )
</code>```

I also tried using the .write_formula method but it didn't work. I cannot click on the drop down list on cell M (one of the dropdown columns I want to autofill) and when I choose a value from cell D in sheet A, the other columns are not autofilled.

```<code>savings_account_sheet.write_formula(
                f'M2', f'=VLOOKUP(D2, Products!B2:P10000,5,FALSE)'
            )

</code>```

I was expecting the dropdown of other columns to be clickable and that when I choose a value from cell D, the other columns should be autopopulated

Body:
I have an excel file that contains two worksheets A and B, Inside sheet A, there is a column "product" which is a dropdown list whose value is coming from sheet B, I want the excel file to be configured such that, when I select a value in "product" column, I want all the other columns (they are also dropdowns) in sheet A to be populated with the values in that same column in sheet B.

How can I achieve this with Xlsxwriter and perhaps Vlookup?.

I have tried:

sheetA.data_validation(
            "M2:M10000", {
                'validate': 'list',
                'source': '=VLOOKUP(D2, SheetB!B2:P10000,5,FALSE)',
            }
        )

I also tried using the .write_formula method but it didn't work. I cannot click on the drop down list on cell M (one of the dropdown columns I want to autofill) and when I choose a value from cell D in sheet A, the other columns are not autofilled.

savings_account_sheet.write_formula(
                f'M2', f'=VLOOKUP(D2, Products!B2:P10000,5,FALSE)'
            )

I was expecting the dropdown of other columns to be clickable and that when I choose a value from cell D, the other columns should be autopopulated


来源: stackexchange

问:
Upgrade from Infinispan 8 to 12
I am upgrading my project from infinispan cache version 8 to 12. After upgrading to infinispan 12 it is no longer possible to serialize a GregorianCalendar java type , resulting in the following error:

```<code>ERROR c.m.DemonAlimDatasManagerCourant - Erreur lors de l'alimentation des caches: ISPN000615: Unable to unmarshall 'java.util.GregorianCalendar' as a marshaller is not present in the user or global SerializationContext
org.infinispan.commons.marshall.MarshallingException: ISPN000615: Unable to unmarshall 'java.util.GregorianCalendar' as a marshaller is not present in the user or global SerializationContext
    at org.infinispan.encoding.ProtostreamTranscoder.getCtxForMarshalling(ProtostreamTranscoder.java:198)
    at org.infinispan.encoding.ProtostreamTranscoder.marshall(ProtostreamTranscoder.java:127)
    at org.infinispan.encoding.ProtostreamTranscoder.transcode(ProtostreamTranscoder.java:68)
    at org.infinispan.encoding.DataConversion.toStorage(DataConversion.java:227)
    at org.infinispan.cache.impl.EncoderCache.valueToStorage(EncoderCache.java:105)
    at org.infinispan.cache.impl.EncoderCache.put(EncoderCache.java:698)
    at com.manager.DemonAlimDatasManagerCourant.alimenterData(DemonAlimDatasManagerCourant.java:180)
    at com.manager.DemonAlimDatasManagerCourant.alimenterInstance(DemonAlimDatasManagerCourant.java:127)
    at com.manager.DemonAlimDatasManagerCourant$$FastClassBySpringCGLIB$$a48662da.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:793)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:763)
    at net.bull.javamelody.MonitoringSpringInterceptor.invoke(MonitoringSpringInterceptor.java:76)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:763)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:708)
    at com.manager.DemonAlimDatasManagerCourant$$EnhancerBySpringCGLIB$$de1659e7.alimenterInstance(<generated>)
    at com.manager.DemonAlimDatasCourantService.enterDaemon(DemonAlimDatasCourantService.java:53)
    at com.manager.DemonAlimDatasCourantService$$FastClassBySpringCGLIB$$723f4b20.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:793)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:763)
    at net.bull.javamelody.MonitoringSpringInterceptor.invoke(MonitoringSpringInterceptor.java:76)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:763)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:708)
    at com.manager.DemonAlimDatasCourantService$$EnhancerBySpringCGLIB$$ea996e79.enterDaemon(<generated>)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:84)
    at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54)
    at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
    at java.base/java.util.concurrent.FutureTask.runAndReset(FutureTask.java:305)
    at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:305)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.base/java.lang.Thread.run(Thread.java:834)
</code>```

I tried with adding  to my config file but it didin't give me a result

```<code><?xml version="1.0" encoding="UTF-8"?>
<infinispan
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="urn:infinispan:config:12.1 http://infinispan.org/schemas/infinispan-config-12.1.xsd"
    xmlns="urn:infinispan:config:12.1">

<cache-container default-cache="default" shutdown-hook="REGISTER">
    <transport stack="tcp" node-name="ecr-dec-cache-light" cluster="ecr-cluster"/>
    <serialization marshaller="org.infinispan.commons.marshall.JavaSerializationMarshaller">
        <allow-list>
            <class>java.util.GregorianCalendar</class>
        </allow-list>
    </serialization>
    <jmx/>

    <distributed-cache name="default" />

    <distributed-cache name="parametrage" statistics="true" mode="SYNC" owners="1" remote-timeout="3600000">
        <locking acquire-timeout="60000" />
        <state-transfer enabled="false" />
    </distributed-cache>
</code>```

Is there any other solution?

ContentLicense: CC BY-SA 4.0

Title: Upgrade from Infinispan 8 to 12

Body:
I am upgrading my project from infinispan cache version 8 to 12. After upgrading to infinispan 12 it is no longer possible to serialize a GregorianCalendar java type , resulting in the following error:

ERROR c.m.DemonAlimDatasManagerCourant - Erreur lors de l'alimentation des caches: ISPN000615: Unable to unmarshall 'java.util.GregorianCalendar' as a marshaller is not present in the user or global SerializationContext
org.infinispan.commons.marshall.MarshallingException: ISPN000615: Unable to unmarshall 'java.util.GregorianCalendar' as a marshaller is not present in the user or global SerializationContext
    at org.infinispan.encoding.ProtostreamTranscoder.getCtxForMarshalling(ProtostreamTranscoder.java:198)
    at org.infinispan.encoding.ProtostreamTranscoder.marshall(ProtostreamTranscoder.java:127)
    at org.infinispan.encoding.ProtostreamTranscoder.transcode(ProtostreamTranscoder.java:68)
    at org.infinispan.encoding.DataConversion.toStorage(DataConversion.java:227)
    at org.infinispan.cache.impl.EncoderCache.valueToStorage(EncoderCache.java:105)
    at org.infinispan.cache.impl.EncoderCache.put(EncoderCache.java:698)
    at com.manager.DemonAlimDatasManagerCourant.alimenterData(DemonAlimDatasManagerCourant.java:180)
    at com.manager.DemonAlimDatasManagerCourant.alimenterInstance(DemonAlimDatasManagerCourant.java:127)
    at com.manager.DemonAlimDatasManagerCourant$$FastClassBySpringCGLIB$$a48662da.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:793)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:763)
    at net.bull.javamelody.MonitoringSpringInterceptor.invoke(MonitoringSpringInterceptor.java:76)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:763)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:708)
    at com.manager.DemonAlimDatasManagerCourant$$EnhancerBySpringCGLIB$$de1659e7.alimenterInstance(<generated>)
    at com.manager.DemonAlimDatasCourantService.enterDaemon(DemonAlimDatasCourantService.java:53)
    at com.manager.DemonAlimDatasCourantService$$FastClassBySpringCGLIB$$723f4b20.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:793)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:763)
    at net.bull.javamelody.MonitoringSpringInterceptor.invoke(MonitoringSpringInterceptor.java:76)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:763)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:708)
    at com.manager.DemonAlimDatasCourantService$$EnhancerBySpringCGLIB$$ea996e79.enterDaemon(<generated>)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:84)
    at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54)
    at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
    at java.base/java.util.concurrent.FutureTask.runAndReset(FutureTask.java:305)
    at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:305)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.base/java.lang.Thread.run(Thread.java:834)

I tried with adding  to my config file but it didin't give me a result

<?xml version="1.0" encoding="UTF-8"?>
<infinispan
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="urn:infinispan:config:12.1 http://infinispan.org/schemas/infinispan-config-12.1.xsd"
    xmlns="urn:infinispan:config:12.1">

<cache-container default-cache="default" shutdown-hook="REGISTER">
    <transport stack="tcp" node-name="ecr-dec-cache-light" cluster="ecr-cluster"/>
    <serialization marshaller="org.infinispan.commons.marshall.JavaSerializationMarshaller">
        <allow-list>
            <class>java.util.GregorianCalendar</class>
        </allow-list>
    </serialization>
    <jmx/>

    <distributed-cache name="default" />

    <distributed-cache name="parametrage" statistics="true" mode="SYNC" owners="1" remote-timeout="3600000">
        <locking acquire-timeout="60000" />
        <state-transfer enabled="false" />
    </distributed-cache>

Is there any other solution?


问:
Script (jquery) not working in html document when hosted
I made a script (jquery) in an html document, which does a search in a list (li) what was typed in a box (input). It happens that when the file is saved locally (localhost), the script is executed and works normally. However, when I send the page to remote hosting, the script stops working, not performing the search and not showing the expected result. Does anyone know what could be causing this problem?</p>
```<code><script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
$(function(){
    $("#txtBusca").keyup(function(){
        var texto = $(this).val();

        $("#ulItens li").css("display", "block");
        $("#ulItens li").each(function(){
            if($(this).text().toUpperCase().indexOf(texto.toUpperCase()) < 0)
                $(this).css("display", "none");
        });
    });
});
</script>
</code>```


问:
how to exclude multiple files using cppcheck with command line
I'm using cppcheck to analyse C source code

Using this command : cppcheck --enable=warning inputpath1 inputpath2 inputpath3 -iexcludepath1 excludepath2 --xml -U_DEBUG 2> .\CppCheckReport.xml

I'm able to generate an XMl report which contains the analyse results of the three input files with the exclusion of the exclude file1 only.
I need to exclude the two files using the -i option one time that's mean that I don't want to use this command : cppcheck --enable=warning inputpath1 inputpath2 inputpath3 -iexcludepath1 -iexcludepath2 --xml -U_DEBUG 2> .\CppCheckReport.xml

Is there any other method to exclude multiple files using cppcheck command ?


问:
How to resolve Arcpy ExecuteError: ERROR 010005: Unable to allocate memory. Failed to Execute (ExtractByMask)
I am running arcpy (using Spyder IDE to run script) and using a for loop which undertakes a number of geoprocessing activities in each loop, as I iterate through a table of inputs. I am using a surface pro laptop (16GB memory) to run the script.

After I've looped through a few hundred times, I get the ExecuteError: ERROR 010005: Unable to allocate memory. Failed to Execute (ExtractByMask). It seems to follow an ExtractByMask step each time (see image).

When I first run the script in Spyder, I get get through about 1000 iterations with no problems. But when I try again straight after this, it terminates with the error after a few hundred more loops at most. I could restart Spyder each time and work in smaller data batches (of say 1000), but this is quite teadious if I am trying to get through about 20,000 iterations.

When i check my laptop system memory, it only appears to be at 30% usage when the arcpy program is running - so I don't think it is this. I had read a few posts which suggest it could be an environment setting associated with ArcGIS. Has anyone encountered this and found a solution to it?

Only work around so far is to quit the Spyder IDE application and reopen, running the loop for smaller batches of data.


问:
How to listen to single tap on OSMDroid's ground overlay?
I simply want to listen to single tap on ground overlay from OSMDroid to show view on screen. We have OnGroundOverlayClickListener in Google Maps. But can we listen in the same way in OSM?

I'm creating ground overlay this way:

```<code>val overlay = GroundOverlay()
overlay.transparency = 0.5f
overlay.image = bitmap
overlay.setPosition(GeoPoint(50.0,-127.5), GeoPoint( 21.0, -66.5))
mapView.overlayManager.add(overlay)
</code>```

Body:
I simply want to listen to single tap on ground overlay from OSMDroid to show view on screen. We have OnGroundOverlayClickListener in Google Maps. But can we listen in the same way in OSM?

I'm creating ground overlay this way:

val overlay = GroundOverlay()
overlay.transparency = 0.5f
overlay.image = bitmap
overlay.setPosition(GeoPoint(50.0,-127.5), GeoPoint( 21.0, -66.5))
mapView.overlayManager.add(overlay)


问:
Flutter : Get value of pressed numbers in Home widget with number buttons
I am using this package with customisation home_widget and trying to build a home widget with number buttons like this image.

I am trying to achieve it by the following code
My WidgetProvider.kt

```<code>override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray, widgetData: SharedPreferences) {
        appWidgetIds.forEach { widgetId ->
            val views = RemoteViews(context.packageName, R.layout.widget_layout).apply {

                // Open App on Widget Click
                val pendingIntent = HomeWidgetLaunchIntent.getActivity(context,
                    MainActivity::class.java)
                setOnClickPendingIntent(R.id.widget_root, pendingIntent)

                val counter = widgetData.getString("_number", "")
                Log.i("onMethodCall", "onMethodCall: $counter")
                print("onMethodCall: $counter")
                var counterText = "$counter"

                setTextViewText(R.id.tv_counter, counterText)
                val pendingIntent2 = HomeWidgetLaunchIntent.getActivity(context,
                    MainActivity::class.java)
                setOnClickPendingIntent(R.id.bt_update, pendingIntent2)

                val backgroundIntent = HomeWidgetBackgroundIntent.getBroadcast(context, Uri.parse("myAppWidget://onNumberBtnClick"))
                setOnClickPendingIntent(R.id.bt_one, backgroundIntent)
            }
            appWidgetManager.updateAppWidget(widgetId, views)
        }
    }
</code>```

I am passing intent as "onNumberBtnClick" and this is my broadcast function

```<code>fun getBroadcast(context: Context, uri: Uri? = null): PendingIntent {
        val intent = Intent(context, HomeWidgetBackgroundReceiver::class.java)
        intent.data = uri
        intent.action = HOME_WIDGET_BACKGROUND_ACTION

        var flags = PendingIntent.FLAG_UPDATE_CURRENT
        if (Build.VERSION.SDK_INT >= 23) {
            flags = flags or PendingIntent.FLAG_IMMUTABLE
        }

        return PendingIntent.getBroadcast(context, 0, intent, flags)
    }
</code>```

in my "HomeWidgetPlugin" class I have set that value in shared preference.

```<code>"onNumberBtnClick" -> {
                if (call.hasArgument("id") && call.hasArgument("data")) {
                    Log.i("onMethodCallHere", "onMethodCallHere: ")
                    print("onMethodCallHere")
                    val id = call.argument<String>("id")
                    val data = call.argument<Any>("data")
                    val prefs = context.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE).edit()
                    if(data != null) {
                        when (data) {
                            is Boolean -> prefs.putBoolean(id, data)
                            is Float -> prefs.putFloat(id, data)
                            is String -> prefs.putString(id, data)
                            is Double -> prefs.putLong(id, java.lang.Double.doubleToRawLongBits(data))
                            is Int -> prefs.putInt(id, data)
                            else -> result.error("-10", "Invalid Type ${data!!::class.java.simpleName}. Supported types are Boolean, Float, String, Double, Long", IllegalArgumentException())
                        }
                    } else {
                        prefs.remove(id);
                    }
                    result.success(prefs.commit())
                }else {
                    result.error("-1", "InvalidArguments saveWidgetData must be called with id and data", IllegalArgumentException())
                }
            }
</code>```

In main.dart I handled callback with workmanager plugin as in the example of the home widget plugin

```<code>Future<void> backgroundCallback(Uri? uri) async {
  if (uri?.host == 'onNumberBtnClick') {
    await HomeWidget.getWidgetData<String>('_number', defaultValue: "1").then((value) {
      print("num:$value");
    });
    await HomeWidget.saveWidgetData<String>('_number', "13");
    await HomeWidget.updateWidget(name: 'AppWidgetProvider', iOSName: 'AppWidgetProvider');
  }
}
</code>```

Can someone please help me with what I am missing or how can I achieve this?

Body:
I am using this package with customisation home_widget and trying to build a home widget with number buttons like this image.

I am trying to achieve it by the following code
My WidgetProvider.kt

override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray, widgetData: SharedPreferences) {
        appWidgetIds.forEach { widgetId ->
            val views = RemoteViews(context.packageName, R.layout.widget_layout).apply {

                // Open App on Widget Click
                val pendingIntent = HomeWidgetLaunchIntent.getActivity(context,
                    MainActivity::class.java)
                setOnClickPendingIntent(R.id.widget_root, pendingIntent)

                val counter = widgetData.getString("_number", "")
                Log.i("onMethodCall", "onMethodCall: $counter")
                print("onMethodCall: $counter")
                var counterText = "$counter"

                setTextViewText(R.id.tv_counter, counterText)
                val pendingIntent2 = HomeWidgetLaunchIntent.getActivity(context,
                    MainActivity::class.java)
                setOnClickPendingIntent(R.id.bt_update, pendingIntent2)

                val backgroundIntent = HomeWidgetBackgroundIntent.getBroadcast(context, Uri.parse("myAppWidget://onNumberBtnClick"))
                setOnClickPendingIntent(R.id.bt_one, backgroundIntent)
            }
            appWidgetManager.updateAppWidget(widgetId, views)
        }
    }

I am passing intent as "onNumberBtnClick" and this is my broadcast function

fun getBroadcast(context: Context, uri: Uri? = null): PendingIntent {
        val intent = Intent(context, HomeWidgetBackgroundReceiver::class.java)
        intent.data = uri
        intent.action = HOME_WIDGET_BACKGROUND_ACTION

        var flags = PendingIntent.FLAG_UPDATE_CURRENT
        if (Build.VERSION.SDK_INT >= 23) {
            flags = flags or PendingIntent.FLAG_IMMUTABLE
        }

        return PendingIntent.getBroadcast(context, 0, intent, flags)
    }

in my "HomeWidgetPlugin" class I have set that value in shared preference.

"onNumberBtnClick" -> {
                if (call.hasArgument("id") && call.hasArgument("data")) {
                    Log.i("onMethodCallHere", "onMethodCallHere: ")
                    print("onMethodCallHere")
                    val id = call.argument<String>("id")
                    val data = call.argument<Any>("data")
                    val prefs = context.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE).edit()
                    if(data != null) {
                        when (data) {
                            is Boolean -> prefs.putBoolean(id, data)
                            is Float -> prefs.putFloat(id, data)
                            is String -> prefs.putString(id, data)
                            is Double -> prefs.putLong(id, java.lang.Double.doubleToRawLongBits(data))
                            is Int -> prefs.putInt(id, data)
                            else -> result.error("-10", "Invalid Type ${data!!::class.java.simpleName}. Supported types are Boolean, Float, String, Double, Long", IllegalArgumentException())
                        }
                    } else {
                        prefs.remove(id);
                    }
                    result.success(prefs.commit())
                }else {
                    result.error("-1", "InvalidArguments saveWidgetData must be called with id and data", IllegalArgumentException())
                }
            }

In main.dart I handled callback with workmanager plugin as in the example of the home widget plugin

Future<void> backgroundCallback(Uri? uri) async {
  if (uri?.host == 'onNumberBtnClick') {
    await HomeWidget.getWidgetData<String>('_number', defaultValue: "1").then((value) {
      print("num:$value");
    });
    await HomeWidget.saveWidgetData<String>('_number', "13");
    await HomeWidget.updateWidget(name: 'AppWidgetProvider', iOSName: 'AppWidgetProvider');
  }
}

Can someone please help me with what I am missing or how can I achieve this?


问:
Electron fetch is not defined when calling function from global shortcuts
I'm getting an error that fetch is not defined when calling my electron code from a global shortcut handler but not when calling it via IPC from the renderer.

Here's my code:

```<code>[utils/api.ts]
export const callAPI = async (inputText: string) => {

  const data = {
    input_text: inputText,
  };

  const res = await fetch(`${backendUrl()}/api/x`, {
    method: 'post',
    headers: jsonHeaders,
    body: JSON.stringify(data),
  });

</code>```
```<code>[main.ts]
app
  .whenReady()
  .then(() => {
    createWindow();
    registerGlobalShortcuts(); // registering here
    app.on('activate', () => {
      if (mainWindow === null) createWindow();
    });
  })
  .catch(console.log);

</code>```
```<code>[globalShortcuts.ts]
import { callAPI } from './utils/api.ts';

const { globalShortcut } = require('electron');
const { clipboard } = require('electron');

const generateOutput = () => {
  const text = clipboard.readText();
  console.log('text', text);
  callAPI(text);
};

export const registerGlobalShortcuts = () => {
  globalShortcut.register('Control+CommandOrControl+C', () => {
    console.log('shortcut hit');
    generateOutput();
  });
};

</code>```

When I run this, and hit the keyboard shortcut, I get this error in the terminal:

```<code>(node:23565) UnhandledPromiseRejectionWarning: ReferenceError: fetch is not defined
    at callOpenAI (/Users/hima/Workspace/general-desktop-agent/desktop-electron/src/main/lib
/textManipulation.ts:38:15)
    at generateTextContinuationPrediction (/Users/hima/Workspace/general-desktop-agent/deskt
op-electron/src/main/globalShortcuts.ts:11:13)
    at Function.<anonymous> (/Users/hima/Workspace/general-desktop-agent/desktop-electron/sr
c/main/globalShortcuts.ts:17:5)

</code>```

But also in my code, in my renderer, I also call window.electron.callAPI(text) there as well, and fetch is found when doing that and the call works perfectly.

So I don't understand why when making the API call from the global shortcut that it says fetch is not defined?

Body:
I'm getting an error that fetch is not defined when calling my electron code from a global shortcut handler but not when calling it via IPC from the renderer.

Here's my code:

[utils/api.ts]
export const callAPI = async (inputText: string) => {

  const data = {
    input_text: inputText,
  };

  const res = await fetch(`${backendUrl()}/api/x`, {
    method: 'post',
    headers: jsonHeaders,
    body: JSON.stringify(data),
  });

[main.ts]
app
  .whenReady()
  .then(() => {
    createWindow();
    registerGlobalShortcuts(); // registering here
    app.on('activate', () => {
      if (mainWindow === null) createWindow();
    });
  })
  .catch(console.log);

[globalShortcuts.ts]
import { callAPI } from './utils/api.ts';

const { globalShortcut } = require('electron');
const { clipboard } = require('electron');

const generateOutput = () => {
  const text = clipboard.readText();
  console.log('text', text);
  callAPI(text);
};

export const registerGlobalShortcuts = () => {
  globalShortcut.register('Control+CommandOrControl+C', () => {
    console.log('shortcut hit');
    generateOutput();
  });
};

When I run this, and hit the keyboard shortcut, I get this error in the terminal:

(node:23565) UnhandledPromiseRejectionWarning: ReferenceError: fetch is not defined
    at callOpenAI (/Users/hima/Workspace/general-desktop-agent/desktop-electron/src/main/lib
/textManipulation.ts:38:15)
    at generateTextContinuationPrediction (/Users/hima/Workspace/general-desktop-agent/deskt
op-electron/src/main/globalShortcuts.ts:11:13)
    at Function.<anonymous> (/Users/hima/Workspace/general-desktop-agent/desktop-electron/sr
c/main/globalShortcuts.ts:17:5)

But also in my code, in my renderer, I also call window.electron.callAPI(text) there as well, and fetch is found when doing that and the call works perfectly.

So I don't understand why when making the API call from the global shortcut that it says fetch is not defined?


问:
react js app not opening for 20% of users
I deploy react js app on shared cpanel host with "npm run build".
for 40% of users app just showing blank page with connection_error and then chunk.js error.

I changed shared hosting service and then it's improve and now 20% of users has problem yet.
I am sure about this new hosting performance.
what is the problem?


问:
Strapi issue /i18n/locales 404

Bug report

Required System information

Node.js version: v16.17.1

NPM version: 8.15.0

Strapi version: 4

Database: mysql

Operating system: o2switch

Describe the bug

I'm trying to deploy a strapi app on o2switch using Nodejs (and Mysql) for a Nextjs app.

Steps to reproduce the behavior

Each time I connect to my admin panel this error appears

Screenshots

Before log in

Code snippets

.env :

```<code>APP_HOST=127.0.0.1
PORT=1338
</code>```

./config/server.js:

module.exports = ({ env }) => ({   host: env('APP_HOST', '0.0.0.0'),   port: env.int('PORT', 1337),   app: {     keys: env.array('APP_KEYS'),   }, });
```

I've tried to configure server.js and .env but nothing changed

Title: Strapi issue /i18n/locales 404

Body:
Bug report

Required System information

Node.js version: v16.17.1

NPM version: 8.15.0

Strapi version: 4

Database: mysql

Operating system: o2switch

Describe the bug

I'm trying to deploy a strapi app on o2switch using Nodejs (and Mysql) for a Nextjs app.

Steps to reproduce the behavior

Each time I connect to my admin panel this error appears

Screenshots

Before log in

Code snippets

.env :

APP_HOST=127.0.0.1
PORT=1338

./config/server.js:

module.exports = ({ env }) => ({   host: env('APP_HOST', '0.0.0.0'),   port: env.int('PORT', 1337),   app: {     keys: env.array('APP_KEYS'),   }, });

I've tried to configure server.js and .env but nothing changed


问:
Should we authenticate every single event emitted by the client in a web sockets connection (socket.io)
I want to know the best practice/approach to handle authentication of events in a web sockets connection. At the moment, I authenticate the client with my middleware once when they want to form the connection with the server's websockets. Only after this one-time authentication, I allow the client to form the TCP Handshake and go on the with web socket flow. Now, the client is emitting various events. Before responding to these events, Should I authenticate each and every event ?

I am using JWT Refresh Token Rotation system on the backend.


问:
How to remove login page from moded apk?
i can't access directly on moded apps it because i need a key to access

i try to remove this line on classes dex

```<code>move-object v5, v0

invoke-static {v5}, Lcom/wpa/MainActivity;->Login(Landroid/content/Context;)V
</code>```

invoke-virtual {v8}, Landroid/app/AlertDialog;->dismiss()V

Body:
i can't access directly on moded apps it because i need a key to access

i try to remove this line on classes dex

move-object v5, v0

invoke-static {v5}, Lcom/wpa/MainActivity;->Login(Landroid/content/Context;)V

invoke-virtual {v8}, Landroid/app/AlertDialog;->dismiss()V


问:
How to target #text element with CSS
Given that I have this div

```<code><div class="icon-text">
    <span class="icon-star"></span>
    Mytext
</div>
</code>```

The "Mytext" is given automatically the id #text

Since I'm not able to change the DOM, how can I target the "Mytext" value with CSS?

Title: How to target #text element with CSS

Body:
Given that I have this div

    Mytext

The "Mytext" is given automatically the id #text

Since I'm not able to change the DOM, how can I target the "Mytext" value with CSS?


问:
fetching data returns undefined in useEffect
```<code>  async function fetchName() {
    const api = "https://jsonplaceholder.typicode.com/users";

    const response = await axios.get(api);
    setUserData(
      response.data.map((e) => {
        return {
          id: e.id,
          name: e.name,
          username: e.username,
        };
      })
    );
    let random = Math.floor(Math.random() * userData.length);
    setName(userData[random].username);
    missedLet(userData[random].username);
    setHintName(userData[random].name);
    console.log("nickname is ", userData[random].username);
  }

  useEffect(() => {
    fetchName();
  }, []);
</code>```

When I call the fetName() function separately, it works correctly, but in useEffect it returns initial state of each state variable.

Also in console its:

```<code>Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'username')
    at getName
</code>```

Body:
  async function fetchName() {
    const api = "https://jsonplaceholder.typicode.com/users";

    const response = await axios.get(api);
    setUserData(
      response.data.map((e) => {
        return {
          id: e.id,
          name: e.name,
          username: e.username,
        };
      })
    );
    let random = Math.floor(Math.random() * userData.length);
    setName(userData[random].username);
    missedLet(userData[random].username);
    setHintName(userData[random].name);
    console.log("nickname is ", userData[random].username);
  }

  useEffect(() => {
    fetchName();
  }, []);

When I call the fetName() function separately, it works correctly, but in useEffect it returns initial state of each state variable.

Also in console its:

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'username')
    at getName


问:
How to use dynamic routing in react?
I've looked at a few answers here and see that none solve my problem. When I run dynamic routing on my PC, on the URL bar on my browser I see:

http://localhost:3000/Users/$%7BAuthorsDB[2].Id%7D

Instead of seeing the corresponding ID, which is 2 in this case, like so:

http://localhost:3000/Users/2

It is rendering the page correctly with my components intact, I'm just not sure if the route is correct. This is the code:

```<code>function Author(props){

  let AuthorsDB = [{
    'Id': 1,
    'Author': "One",
    'Upvotes': 1,
    'Description': '1st Place'
    },
    {
    'Id': 2,
    'Author': "Two",
    'Upvotes': 2,
    'Description': '2nd Place'
    },
    {
    'Id': 3,
    'Author': "Three",
    'Upvotes': 3,
    'Description': '3rd Place'
    },
    {
    'Id': 4,
    'Author': "Four",
    'Upvotes': 4,
    'Description': '4th Place'
    },
    {
    'Id': 5,
    'Author': "Five",
    'Upvotes': 5,
    'Description': '5th Place'
    }
    ]

  const linkStyle = {
    textDecoration: 'none',
    color: 'inherit',
  };

    return(
        <div className="Author">
        <div className="AvatarImg">
            <Avatar alt="R"  sx={{ width: 35, height: 35 }}/>
        </div>
            <Link to={"/Users/${AuthorsDB[2].Id}"} style={linkStyle}>{AuthorsDB[props.Index].Author}</Link>
            <h3> {AuthorsDB[props.Index].Description} </h3>
            <h3> {AuthorsDB[props.Index].Upvotes} </h3>
        </div>
        )
}
</code>```

Title: How to use dynamic routing in react?

Body:
I've looked at a few answers here and see that none solve my problem. When I run dynamic routing on my PC, on the URL bar on my browser I see:

http://localhost:3000/Users/$%7BAuthorsDB[2].Id%7D

Instead of seeing the corresponding ID, which is 2 in this case, like so:

http://localhost:3000/Users/2

It is rendering the page correctly with my components intact, I'm just not sure if the route is correct. This is the code:

function Author(props){

  let AuthorsDB = [{
    'Id': 1,
    'Author': "One",
    'Upvotes': 1,
    'Description': '1st Place'
    },
    {
    'Id': 2,
    'Author': "Two",
    'Upvotes': 2,
    'Description': '2nd Place'
    },
    {
    'Id': 3,
    'Author': "Three",
    'Upvotes': 3,
    'Description': '3rd Place'
    },
    {
    'Id': 4,
    'Author': "Four",
    'Upvotes': 4,
    'Description': '4th Place'
    },
    {
    'Id': 5,
    'Author': "Five",
    'Upvotes': 5,
    'Description': '5th Place'
    }
    ]

  const linkStyle = {
    textDecoration: 'none',
    color: 'inherit',
  };

    return(

            <Avatar alt="R"  sx={{ width: 35, height: 35 }}/>

            <Link to={"/Users/${AuthorsDB[2].Id}"} style={linkStyle}>{AuthorsDB[props.Index].Author}</Link>

 {AuthorsDB[props.Index].Description}

 {AuthorsDB[props.Index].Upvotes}

        )
}


问:
How to get the exact world coordinates of mouse click position
I have a mesh loaded (assimp) in 3D environment in OpenGL. I want to move it along the mouse click (dragging) from one point to another. My present solution is behaving weirdly, the unprojected location is not correct and also I need to find a good way to move mesh along the mouse drag.

I am using unproject method as below:

```<code>glm::vec3 unProject(glm::vec3 win, glm::mat4 model, glm::mat4 proj, glm::vec4 viewport)
{
    glm::mat4 Inverse = glm::inverse(proj * model);
    glm::vec4 tmp = glm::vec4(win, 1);
    tmp.x = (tmp.x - (viewport[0])) / (viewport[2]);
    tmp.y = (tmp.y - (viewport[1])) / (viewport[3]);
    tmp.x = tmp.x * (2) - (1);
    tmp.y = tmp.y * (2) - (1);
    glm::vec4 obj = Inverse * tmp;
    obj /= obj.w;
    return glm::vec3(obj);
}
</code>```

along with a mouse callback

```<code>void mouse_callback(GLFWwindow* window, int button, int action, int mods)
{
    if (button == GLFW_MOUSE_BUTTON_LEFT) {
        if(GLFW_PRESS == action){

            int screen_w, screen_h;
            int pixel_w, pixel_h;
            double xpos,ypos,zpos;

            glfwGetWindowSize(window, &screen_w, &screen_h);
            glfwGetFramebufferSize(window, &pixel_w, &pixel_h);
            glfwGetCursorPos(window, &xpos, &ypos);

            glm::vec2 screen_pos=glm::vec2(xpos, ypos);
            glm::vec2 pixel_pos=screen_pos * glm::vec2(pixel_w, pixel_h) / glm::vec2(screen_w, screen_h);

            glm::vec3 win=glm::vec3(pixel_pos.x, pixel_h-pixel_pos.y, 0.0f);

            glReadPixels((GLint)win.x, (GLint)win.y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &win.z);

            //Fix
            pixel_pos = pixel_pos + glm::vec2(0.5f, 0.5f);  //Test
            win = glm::vec3(pixel_pos.x, pixel_h-pixel_pos.y, win.z);

            glm::vec4 viewport(0.0f,0.0f,(float)screen_w, (float)screen_h);
            glm::mat4 transformMatrix = glm::mat4(1.0);
            clickLocInWorld = unProject(win, camera.calculateViewMatrix() * transformMatrix, projection, viewport);

    //clamp z-axis
    if(clickLocInWorld.z > 10.0f)
        clickLocInWorld.z = 10.0f;
    if(clickLocInWorld.z < -10.0f)
        clickLocInWorld.z = -10.0f;

            std::cout << "screen " << xpos << " " << ypos << " " << zpos << std::endl;
            std::cout << "world " << clickLocInWorld.x << " " << clickLocInWorld.y << " " << clickLocInWorld.z << std::endl;
        }
    }
}
</code>```

I am trying to clamp z-axis, but need a proper way.

Also, I am trying to translate the model in 3D using

```<code>        presentSpawnLoc = clickLocInWorld - presentSpawnLoc;
    model = glm::translate(model, presentSpawnLoc);
    model = glm::scale(model, glm::vec3(2.f, 2.f, 2.f));
    glUniformMatrix4fv(uniformModel, 1, GL_FALSE, glm::value_ptr(model));

        glBindVertexArray(VAO);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO);
    glDrawElements(GL_TRIANGLES, indexCount, GL_UNSIGNED_INT, 0);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
    glBindVertexArray(0);

</code>```

Body:
I have a mesh loaded (assimp) in 3D environment in OpenGL. I want to move it along the mouse click (dragging) from one point to another. My present solution is behaving weirdly, the unprojected location is not correct and also I need to find a good way to move mesh along the mouse drag.

I am using unproject method as below:

glm::vec3 unProject(glm::vec3 win, glm::mat4 model, glm::mat4 proj, glm::vec4 viewport)
{
    glm::mat4 Inverse = glm::inverse(proj * model);
    glm::vec4 tmp = glm::vec4(win, 1);
    tmp.x = (tmp.x - (viewport[0])) / (viewport[2]);
    tmp.y = (tmp.y - (viewport[1])) / (viewport[3]);
    tmp.x = tmp.x * (2) - (1);
    tmp.y = tmp.y * (2) - (1);
    glm::vec4 obj = Inverse * tmp;
    obj /= obj.w;
    return glm::vec3(obj);
}

along with a mouse callback

void mouse_callback(GLFWwindow* window, int button, int action, int mods)
{
    if (button == GLFW_MOUSE_BUTTON_LEFT) {
        if(GLFW_PRESS == action){

            int screen_w, screen_h;
            int pixel_w, pixel_h;
            double xpos,ypos,zpos;

            glfwGetWindowSize(window, &screen_w, &screen_h);
            glfwGetFramebufferSize(window, &pixel_w, &pixel_h);
            glfwGetCursorPos(window, &xpos, &ypos);

            glm::vec2 screen_pos=glm::vec2(xpos, ypos);
            glm::vec2 pixel_pos=screen_pos * glm::vec2(pixel_w, pixel_h) / glm::vec2(screen_w, screen_h);

            glm::vec3 win=glm::vec3(pixel_pos.x, pixel_h-pixel_pos.y, 0.0f);

            glReadPixels((GLint)win.x, (GLint)win.y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &win.z);

            //Fix
            pixel_pos = pixel_pos + glm::vec2(0.5f, 0.5f);  //Test
            win = glm::vec3(pixel_pos.x, pixel_h-pixel_pos.y, win.z);

            glm::vec4 viewport(0.0f,0.0f,(float)screen_w, (float)screen_h);
            glm::mat4 transformMatrix = glm::mat4(1.0);
            clickLocInWorld = unProject(win, camera.calculateViewMatrix() * transformMatrix, projection, viewport);

    //clamp z-axis
    if(clickLocInWorld.z > 10.0f)
        clickLocInWorld.z = 10.0f;
    if(clickLocInWorld.z < -10.0f)
        clickLocInWorld.z = -10.0f;

            std::cout << "screen " << xpos << " " << ypos << " " << zpos << std::endl;
            std::cout << "world " << clickLocInWorld.x << " " << clickLocInWorld.y << " " << clickLocInWorld.z << std::endl;
        }
    }
}

I am trying to clamp z-axis, but need a proper way.

Also, I am trying to translate the model in 3D using

        presentSpawnLoc = clickLocInWorld - presentSpawnLoc;
    model = glm::translate(model, presentSpawnLoc);
    model = glm::scale(model, glm::vec3(2.f, 2.f, 2.f));
    glUniformMatrix4fv(uniformModel, 1, GL_FALSE, glm::value_ptr(model));

        glBindVertexArray(VAO);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO);
    glDrawElements(GL_TRIANGLES, indexCount, GL_UNSIGNED_INT, 0);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
    glBindVertexArray(0);


问:
Getting all the events from a remote computer
I have a problem with getting all the events from a remote computer.

```<code>try
{
    string queryString = "*[System/Level=1 or System/Level=2 or System/Level=3 or System/Level=4 or System/Level=5]";
    SecureString password = new NetworkCredential("", getPassword()).SecurePassword;
    EventLogSession session = new("RemoteComputer", getDomainName(), getAdminName(), password, SessionAuthentication.Default);
    password.Dispose();
    EventLogQuery query = new("Application", PathType.LogName, queryString);
    query.Session = session;
    EventLogReader logReader = new(query);
    EventRecord eventRecord;

    while ((eventRecord = logReader.ReadEvent()) != null)
    {
        eventRecords.Add(eventRecord);    //save records
    }

    //display records
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
</code>```

The program is getting only some part of events from the remote computer and displays them, but then it throws an exception with message "Cannot find the specified file".

What's the problem and how can I get all the events?

Body:
I have a problem with getting all the events from a remote computer.

try
{
    string queryString = "*[System/Level=1 or System/Level=2 or System/Level=3 or System/Level=4 or System/Level=5]";
    SecureString password = new NetworkCredential("", getPassword()).SecurePassword;
    EventLogSession session = new("RemoteComputer", getDomainName(), getAdminName(), password, SessionAuthentication.Default);
    password.Dispose();
    EventLogQuery query = new("Application", PathType.LogName, queryString);
    query.Session = session;
    EventLogReader logReader = new(query);
    EventRecord eventRecord;

    while ((eventRecord = logReader.ReadEvent()) != null)
    {
        eventRecords.Add(eventRecord);    //save records
    }

    //display records
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

The program is getting only some part of events from the remote computer and displays them, but then it throws an exception with message "Cannot find the specified file".

What's the problem and how can I get all the events?


问:
How to set a maximum number of files for imagePicker in flutter
let me explain How can I set a maximum number of files to pick for filepicker so that I can limit the pick of file so it does not overload the server.</p>
```<code>List<XFile>? imageFileList = [];
  final ImagePicker _picker = ImagePicker();
  void selectedImages() async {
    final List<XFile> selectedImages =
        await _picker.pickMultiImage(imageQuality: 10);
    if (selectedImages!.isNotEmpty && selectedImages.length < 10) {
      imageFileList?.addAll(selectedImages);
    }
    setState(() {});
  }
</code>```

Body:
let me explain How can I set a maximum number of files to pick for filepicker so that I can limit the pick of file so it does not overload the server.

List<XFile>? imageFileList = [];
  final ImagePicker _picker = ImagePicker();
  void selectedImages() async {
    final List<XFile> selectedImages =
        await _picker.pickMultiImage(imageQuality: 10);
    if (selectedImages!.isNotEmpty && selectedImages.length < 10) {
      imageFileList?.addAll(selectedImages);
    }
    setState(() {});
  }


问:
Typescript and Express: are query parameters always of type string?
I'm trying to use typed query parameters with typescript, express and @types/express:

import express, { Request, Response } from "express";

const app = express();

app.get('/', (request: Request<{}, {}, {}, { page: number }>, response: Response) =>
{
    response.send(`value: ${request.query.page}, type: ${typeof request.query.page}\n`);
});

app.listen(3000);
```
<p>Inside my <code>app.get()</code> method, the query properties are always of type <code>string</code>, regardless of how I defined them:</p>
<pre class="lang-bash prettyprint-override"><code>$ curl "http://localhost:3000/?page=7"
value: 7, type: string
</code>```

I could cast the properties to the desired type, like number in this case. But that's the kind of thing I'm trying to avoid in the first place, by using the type system.

Is there a way to have query parameters of the type as defined in the method's signature?

Package versions used:

```<code>typescript 4.9.4
express: 4.18.2
@types/express: 4.17.15
</code>```

And in tsconfig.json, this is enabled:

"strict": true,
```

Body:
I'm trying to use typed query parameters with typescript, express and @types/express:

import express, { Request, Response } from "express";

const app = express();

app.get('/', (request: Request<{}, {}, {}, { page: number }>, response: Response) =>
{
    response.send(`value: ${request.query.page}, type: ${typeof request.query.page}\n`);
});

app.listen(3000);

Inside my app.get() method, the query properties are always of type string, regardless of how I defined them:

$ curl "http://localhost:3000/?page=7"
value: 7, type: string

I could cast the properties to the desired type, like number in this case. But that's the kind of thing I'm trying to avoid in the first place, by using the type system.

Is there a way to have query parameters of the type as defined in the method's signature?

Package versions used:

typescript 4.9.4
express: 4.18.2
@types/express: 4.17.15

And in tsconfig.json, this is enabled:

"strict": true,


问:
Laravel - Check if the user id is present in a hasMany relation
I have a postmodel with several relations: comment, tag and poll. A poll is a survey and has a relation to the Answer model.
Post hasOne Poll, Poll belongsTo Post , Poll hasMany Answer Answer belongsTo Poll
Here are the migrations:

// poll migration
Schema::create('polls', function (Blueprint $table) {
    $table->id();
    $table->integer('post_id');
    $table->integer('user_id');
    $table->string('question');
    $table->string('options');
    $table->timestamps();
});

// answer migration
Schema::create('answers', function (Blueprint $table) {
    $table->id();
    $table->integer('poll_id');
    $table->string('user_id');
    $table->integer('choice'); // index from answer array
    $table->timestamps();
});
```
<p><strong>PostController</strong></p>
<pre class="lang-php prettyprint-override"><code>$post = Post::with('comments', 'tags', 'poll.answears')->find($post->id);
</code>```

My goal is to show the poll and at the same time the user selected option (answer) in a post.show. I could now pull all the answers of the poll and iterate to check if the user_id of the current user is in the collection for this post. But I don't think this is a good way and a huge overhead when you have a lot of answers.

Could it be easier without losing a lot of performance?

Body:
I have a postmodel with several relations: comment, tag and poll. A poll is a survey and has a relation to the Answer model.
Post hasOne Poll, Poll belongsTo Post , Poll hasMany Answer Answer belongsTo Poll
Here are the migrations:

// poll migration
Schema::create('polls', function (Blueprint $table) {
    $table->id();
    $table->integer('post_id');
    $table->integer('user_id');
    $table->string('question');
    $table->string('options');
    $table->timestamps();
});

// answer migration
Schema::create('answers', function (Blueprint $table) {
    $table->id();
    $table->integer('poll_id');
    $table->string('user_id');
    $table->integer('choice'); // index from answer array
    $table->timestamps();
});

PostController

$post = Post::with('comments', 'tags', 'poll.answears')->find($post->id);

My goal is to show the poll and at the same time the user selected option (answer) in a post.show. I could now pull all the answers of the poll and iterate to check if the user_id of the current user is in the collection for this post. But I don't think this is a good way and a huge overhead when you have a lot of answers.

Could it be easier without losing a lot of performance?


问:
Getting "Error running 'App': Default Activity not found" error just after adding an adView in my app in Android Studio
enter image description here

I wanted to add an adView in my app but running my app just after adding the adView, I am getting this error, and once I get this error I can't get out of this even after deleting the adView.
Before adView this app runs so smoothly.

First I thought that this error may be because of uncomplete code of adView, then I coded the the whole code of adView and nothing happened except this error.

I just wanted to add the adView and my app work smoothly.


问:
Thunderbird agenda native system notification?
I've been looking for an answer to this for weeks and figured I might just ask the question directly.

I'm using Thunderbird 102.6.1 on Windows 10. I'm looking to replace the "standard" Thunderbird agenda popups (see screenshot below) with a "native" system notification such as for Windows 10 Calendar (see 2nd screenshot below). This is mainly because the TB agenda popup steals focus from other apps and I often end up typing on that window instead of the one I was previously writing on, which is frustrating.

I know this is possible for email notifications and I've already enabled that in the TB options, however I couldn't find the equivalent for agenda alerts.

Thanks in advance for your help!
Cheers


问:
i want to use sscanf_s to read time from a file and use loops c++
I want to read time from a file and separate minutes from seconds using sscanf_s but I can read only the first line and the loop is not working  c++

i tried while loop and for loop and still the first line is the only line that is read

```<code> int min, sec;
    string phone;
    char time[100];

    ifstream file("calls.txt");
    if (!file)
        cout << "Can't open file!!!\n";
    while (file.good())
    {
        if (file.read((char*)time, sizeof(time)))
        {
            {
                sscanf_s(time, "%03d:%02d", &min, &sec);
                int* minutes = new int, * seconds = new int;
                *minutes = min;
                *seconds = sec;
                cout << "min: " << *minutes << endl;
                cout << "sec: " << *seconds << endl;
            }
        }
    }
    file.close();
</code>```

here is the code

Body:
I want to read time from a file and separate minutes from seconds using sscanf_s but I can read only the first line and the loop is not working  c++

i tried while loop and for loop and still the first line is the only line that is read

 int min, sec;
    string phone;
    char time[100];

    ifstream file("calls.txt");
    if (!file)
        cout << "Can't open file!!!\n";
    while (file.good())
    {
        if (file.read((char*)time, sizeof(time)))
        {
            {
                sscanf_s(time, "%03d:%02d", &min, &sec);
                int* minutes = new int, * seconds = new int;
                *minutes = min;
                *seconds = sec;
                cout << "min: " << *minutes << endl;
                cout << "sec: " << *seconds << endl;
            }
        }
    }
    file.close();

here is the code


Title: SERVER_ERROR when calling a Polygon smart contract method with ethers.js

Body:
I have a smart contract deployed on Polygon and I'm calling one of its methods from a Dockerized NodeJS using the ethers library.

Locally it works fine 100% of the time, but in production on AKS I often but randomly get the following exception:

Error: processing response error (body="{\"jsonrpc\":\"2.0\",\"id\":55,\"error\":{\"code\":-32603,\"message\":\"Internal error\"}}", error={"code":-32603}, requestBody="{\"method\":\"eth_sendRawTransaction\",\"params\":[\"0x02f901b4818979850cce416600850cce416600830f424094c84b484555e721066d50d4057f33728cf444a95480b90144de81dc160000000000000000000000001d651fc22aca998a1dfc9bc273d85a0540a6563a0000000000000000000000008f3cf7ad23cd3cadbd9735aff958023239c6a06300000000000000000000000000000000000000000000000030927f74c9de00000000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000041d1d48667cea4619188cbcf57ce246f3589a47c627c8cae7e77cd6b97853ad6dd365c7e87fe56c7c4284651f4ffef98a49d92c2c792a71e6d6c3f6f1b3ec9d1ce1b00000000000000000000000000000000000000000000000000000000000000c001a00b7b92fce20544a335b9f883a2efbd89459eab54b0c92c25d82273b92f143776a00a31fb3ad8dc4a5ac742476b4569dd7a3fc17972621b0ef95a753fa27c08aa6d\"],\"id\":55,\"jsonrpc\":\"2.0\"}", requestMethod="POST", url="https://polygon-rpc.com/", code=SERVER_ERROR, version=web/5.7.1)
    at Logger.makeError (/app/src/server/node_modules/@ethersproject/logger/lib/index.js:238:21)
    at Logger.throwError (/app/src/server/node_modules/@ethersproject/logger/lib/index.js:247:20)
    at /app/src/server/node_modules/@ethersproject/web/lib/index.js:313:32
    at step (/app/src/server/node_modules/@ethersproject/web/lib/index.js:33:23)
    at Object.next (/app/src/server/node_modules/@ethersproject/web/lib/index.js:14:53)
    at fulfilled (/app/src/server/node_modules/@ethersproject/web/lib/index.js:5:58)
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  reason: 'processing response error',
  code: 'SERVER_ERROR',
  body: '{"jsonrpc":"2.0","id":55,"error":{"code":-32603,"message":"Internal error"}}',
  error: Error: Internal error
      at getResult (/app/src/server/node_modules/@ethersproject/providers/lib/json-rpc-provider.js:191:21)
      at processJsonFunc (/app/src/server/node_modules/@ethersproject/web/lib/index.js:356:22)
      at /app/src/server/node_modules/@ethersproject/web/lib/index.js:288:46
      at step (/app/src/server/node_modules/@ethersproject/web/lib/index.js:33:23)
      at Object.next (/app/src/server/node_modules/@ethersproject/web/lib/index.js:14:53)
      at fulfilled (/app/src/server/node_modules/@ethersproject/web/lib/index.js:5:58)
      at runMicrotasks (<anonymous>)
      at processTicksAndRejections (node:internal/process/task_queues:96:5) {
    code: -32603,
    data: undefined
  },
  requestBody: '{"method":"eth_sendRawTransaction","params":["0x02f901b4818979850cce416600850cce416600830f424094c84b484555e721066d50d4057f33728cf444a95480b90144de81dc160000000000000000000000001d651fc22aca998a1dfc9bc273d85a0540a6563a0000000000000000000000008f3cf7ad23cd3cadbd9735aff958023239c6a06300000000000000000000000000000000000000000000000030927f74c9de00000000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000041d1d48667cea4619188cbcf57ce246f3589a47c627c8cae7e77cd6b97853ad6dd365c7e87fe56c7c4284651f4ffef98a49d92c2c792a71e6d6c3f6f1b3ec9d1ce1b00000000000000000000000000000000000000000000000000000000000000c001a00b7b92fce20544a335b9f883a2efbd89459eab54b0c92c25d82273b92f143776a00a31fb3ad8dc4a5ac742476b4569dd7a3fc17972621b0ef95a753fa27c08aa6d"],"id":55,"jsonrpc":"2.0"}',
  requestMethod: 'POST',
  url: 'https://polygon-rpc.com/',
  transaction: {
    type: 2,
    chainId: 137,
    nonce: 121,
    maxPriorityFeePerGas: BigNumber { _hex: '0x0cce416600', _isBigNumber: true },
    maxFeePerGas: BigNumber { _hex: '0x0cce416600', _isBigNumber: true },
    gasPrice: null,
    gasLimit: BigNumber { _hex: '0x0f4240', _isBigNumber: true },
    to: '0xC84B484555e721066D50D4057F33728cF444a954',
    value: BigNumber { _hex: '0x00', _isBigNumber: true },
    data: '0xde81dc160000000000000000000000001d651fc22aca998a1dfc9bc273d85a0540a6563a0000000000000000000000008f3cf7ad23cd3cadbd9735aff958023239c6a06300000000000000000000000000000000000000000000000030927f74c9de00000000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000041d1d48667cea4619188cbcf57ce246f3589a47c627c8cae7e77cd6b97853ad6dd365c7e87fe56c7c4284651f4ffef98a49d92c2c792a71e6d6c3f6f1b3ec9d1ce1b00000000000000000000000000000000000000000000000000000000000000',
    accessList: [],
    hash: '0xeb478bbdf27697fa287a3a5e9fdcc9df3bfb8ec57230975c1fa756d7b5877617',
    v: 1,
    r: '0x0b7b92fce20544a335b9f883a2efbd89459eab54b0c92c25d82273b92f143776',
    s: '0x0a31fb3ad8dc4a5ac742476b4569dd7a3fc17972621b0ef95a753fa27c08aa6d',
    from: '0x99F873ec743ba31FE2F22Db011F2e7e1F2AF502c',
    confirmations: 0
  },
  transactionHash: '0xeb478bbdf27697fa287a3a5e9fdcc9df3bfb8ec57230975c1fa756d7b5877617'
}

I find errors returned by ethers a bit cryptic and in this case I'm unable to understand what's the issue (and why it isn't systematic). Is it an issue with the RPC or with Polygon itself ("SERVER_ERROR")?

Thanks for helping me shed light on this!


问:
Changing scss variables in React
so i've got some colors as variables in my scss file

```<code>$primary_background: #1E1E1E;
$primary_button: #F2F2F2;
$primary_sharp: #171717;
$primary_button_active: #9D9D9D;
$primary_sharp_active: #2D2D2D;

$bluish_background: #0C002D;
$bluish_button: #C2C1EF;
$bluish_sharp: #04001E;
$bluish_button_active: #5F52AE;
$bluish_sharp_active: #0C0054;
</code>```

and use them like this

```<code>.button_active {
    background-color: $primary_button_active;
}

.button_text_hidden {
    color: $primary_button;
}
</code>```

is there any way in react i can either replace all 'primary_' with 'bluish_' styles or their values, for example:

```<code>$primary_background: #1E1E1E => $primary_background: #0C002D

</code>```

i acknowledge it's probably not the best practice to change styles directly like that, but manipulating classes is the last resort here i think

Title: Changing scss variables in React

Body:
so i've got some colors as variables in my scss file

$primary_background: #1E1E1E;
$primary_button: #F2F2F2;
$primary_sharp: #171717;
$primary_button_active: #9D9D9D;
$primary_sharp_active: #2D2D2D;

$bluish_background: #0C002D;
$bluish_button: #C2C1EF;
$bluish_sharp: #04001E;
$bluish_button_active: #5F52AE;
$bluish_sharp_active: #0C0054;

and use them like this

.button_active {
    background-color: $primary_button_active;
}

.button_text_hidden {
    color: $primary_button;
}

is there any way in react i can either replace all 'primary_' with 'bluish_' styles or their values, for example:

$primary_background: #1E1E1E => $primary_background: #0C002D

i acknowledge it's probably not the best practice to change styles directly like that, but manipulating classes is the last resort here i think


问:
Google Play Pre-Registration Sign Up number stuck
We opened the pre-registration for our app 2 weeks ago and we quickly received 136 sign ups but despite more people pre-registering the count hasn’t moved for almost 10 days.

Looked online but couldn’t find an answer anywhere.

enter image description here


问:
How to track user/session for Sentry in AWS Lambda golang behind Amazon API Gateway?
I am creating an AWS Lambda with Golang behind API Gateway. I want to track how many sessions / users affected by an errors happened in the Golang code compared to the whole sessions / users.

If the users already authenticated using, I want to track the User-ID for tracking the user. Otherwise, if it's from a browser or app, it will use Session-ID or Device-ID header sent by the client respectively to track the session. Or if it's from a crawler trying to do something, I'll just use header X-AMZN-CF-ID.

I have executed this line in the main golang app.

```<code>sentry.Init(sentry.ClientOptions{
        Environment:      environment,
        Release:          release,
        Debug:            debug,
        TracesSampleRate: traceSampleRate,
        Transport:        sentrySyncTransport,
})
</code>```

and when there is exception, I use

```<code>        sentry.WithScope(func(scope *sentry.Scope) {
            scope.SetLevel(level)
            sentry.CaptureException(err)
        })
</code>```

I couldn't find anything in the Sentry Golang SDK documentation to track the user or session using Golang.

Is it really not doable in Golang or have I missed something?

Body:
I am creating an AWS Lambda with Golang behind API Gateway. I want to track how many sessions / users affected by an errors happened in the Golang code compared to the whole sessions / users.

If the users already authenticated using, I want to track the User-ID for tracking the user. Otherwise, if it's from a browser or app, it will use Session-ID or Device-ID header sent by the client respectively to track the session. Or if it's from a crawler trying to do something, I'll just use header X-AMZN-CF-ID.

I have executed this line in the main golang app.

sentry.Init(sentry.ClientOptions{
        Environment:      environment,
        Release:          release,
        Debug:            debug,
        TracesSampleRate: traceSampleRate,
        Transport:        sentrySyncTransport,
})

and when there is exception, I use

        sentry.WithScope(func(scope *sentry.Scope) {
            scope.SetLevel(level)
            sentry.CaptureException(err)
        })

I couldn't find anything in the Sentry Golang SDK documentation to track the user or session using Golang.

Is it really not doable in Golang or have I missed something?


问:
Not able to get Access Token from Google Api
I am new to GTM+GA.I am trying to display google Analytics(GA4) reports on my webpage. I created Oauth Client Id in google cloud console and also done other settings in Google cloud console. Through javascript code i am trying to get access token from google Api and I am getting below exception.

After successful authentication I will integrate GA repots with my web page. Below is my javascript code for getting access token.

```<code>function main(propertyId = 'YOUR-GA4-PROPERTY-ID') {
propertyId = '347415282';
const {
    OAuth2Client
} = require('google-auth-library');
const {
    grpc
} = require('google-gax');
const http = require('http');
const url = require('url');
const open = require('open');
const destroyer = require('server-destroy');
const keys = require('./oauth2.keys.json');
const SCOPES = ['https://www.googleapis.com/auth/analytics.readonly'];

function getAnalyticsDataClient(authClient) {
    const sslCreds = grpc.credentials.createSsl();
    const credentials = grpc.credentials.combineChannelCredentials(
            sslCreds,
            grpc.credentials.createFromGoogleCredential(authClient));
    return new BetaAnalyticsDataClient({
        sslCreds: credentials,
    });
}

function getOAuth2Client() {
    return new Promise((resolve, reject) => {
        const oAuth2Client = new OAuth2Client(
                keys.web.client_id,
                keys.web.client_secret,
                'http://localhost:3000/oauth2callback');

        const authorizeUrl = oAuth2Client.generateAuthUrl({
            access_type: 'offline',
            scope: SCOPES.join(' '),
        });

        const server = http
            .createServer(async(req, res) => {
                try {
                    if (req.url.indexOf('/oauth2callback') > -1) {

                        const qs = new url.URL(req.url, 'http://localhost:3000')
                            .searchParams;
                        const code = qs.get('code');
                        console.log(`Code is ${code}`);
                        res.end(
                            'Authentication successful! Please return to the console.');
                        server.destroy();

                        const r = await oAuth2Client.getToken(code);

                        oAuth2Client.setCredentials(r.tokens);
                        console.info('Tokens acquired.');
                        resolve(oAuth2Client);
                    }
                } catch (e) {
                    reject(e);
                }
            })
            .listen(3000, () => {
                console.info(`Opening the browser with URL: ${authorizeUrl}`);
                open(authorizeUrl, {
                    wait: false
                }).then(cp => cp.unref());
            });
        destroyer(server);
    });
}

async function runReport() {
    const oAuth2Client = await getOAuth2Client();
    const analyticsDataClient = getAnalyticsDataClient(oAuth2Client);

    const[response] = await analyticsDataClient.runReport({
        property: `properties/${propertyId}`,
        dateRanges: [{
                startDate: '2020-03-31',
                endDate: 'today',
            },
        ],
        dimensions: [{
                name: 'city',
            },
        ],
        metrics: [{
                name: 'activeUsers',
            },
        ],
    });

    console.log('Report result:');
    response.rows.forEach(row => {
        console.log(row.dimensionValues[0], row.metricValues[0]);
    });
}

runReport();

process.on('unhandledRejection', err => {
    console.error(err.message);
    process.exitCode = 1;
});
main(...process.argv.slice(2));
</code>```

Please let me know how to get rid off this issue.

Regards,
Prabhash

Body:
I am new to GTM+GA.I am trying to display google Analytics(GA4) reports on my webpage. I created Oauth Client Id in google cloud console and also done other settings in Google cloud console. Through javascript code i am trying to get access token from google Api and I am getting below exception.

After successful authentication I will integrate GA repots with my web page. Below is my javascript code for getting access token.

function main(propertyId = 'YOUR-GA4-PROPERTY-ID') {
propertyId = '347415282';
const {
    OAuth2Client
} = require('google-auth-library');
const {
    grpc
} = require('google-gax');
const http = require('http');
const url = require('url');
const open = require('open');
const destroyer = require('server-destroy');
const keys = require('./oauth2.keys.json');
const SCOPES = ['https://www.googleapis.com/auth/analytics.readonly'];

function getAnalyticsDataClient(authClient) {
    const sslCreds = grpc.credentials.createSsl();
    const credentials = grpc.credentials.combineChannelCredentials(
            sslCreds,
            grpc.credentials.createFromGoogleCredential(authClient));
    return new BetaAnalyticsDataClient({
        sslCreds: credentials,
    });
}

function getOAuth2Client() {
    return new Promise((resolve, reject) => {
        const oAuth2Client = new OAuth2Client(
                keys.web.client_id,
                keys.web.client_secret,
                'http://localhost:3000/oauth2callback');

        const authorizeUrl = oAuth2Client.generateAuthUrl({
            access_type: 'offline',
            scope: SCOPES.join(' '),
        });

        const server = http
            .createServer(async(req, res) => {
                try {
                    if (req.url.indexOf('/oauth2callback') > -1) {

                        const qs = new url.URL(req.url, 'http://localhost:3000')
                            .searchParams;
                        const code = qs.get('code');
                        console.log(`Code is ${code}`);
                        res.end(
                            'Authentication successful! Please return to the console.');
                        server.destroy();

                        const r = await oAuth2Client.getToken(code);

                        oAuth2Client.setCredentials(r.tokens);
                        console.info('Tokens acquired.');
                        resolve(oAuth2Client);
                    }
                } catch (e) {
                    reject(e);
                }
            })
            .listen(3000, () => {
                console.info(`Opening the browser with URL: ${authorizeUrl}`);
                open(authorizeUrl, {
                    wait: false
                }).then(cp => cp.unref());
            });
        destroyer(server);
    });
}

async function runReport() {
    const oAuth2Client = await getOAuth2Client();
    const analyticsDataClient = getAnalyticsDataClient(oAuth2Client);

    const[response] = await analyticsDataClient.runReport({
        property: `properties/${propertyId}`,
        dateRanges: [{
                startDate: '2020-03-31',
                endDate: 'today',
            },
        ],
        dimensions: [{
                name: 'city',
            },
        ],
        metrics: [{
                name: 'activeUsers',
            },
        ],
    });

    console.log('Report result:');
    response.rows.forEach(row => {
        console.log(row.dimensionValues[0], row.metricValues[0]);
    });
}

runReport();

process.on('unhandledRejection', err => {
    console.error(err.message);
    process.exitCode = 1;
});
main(...process.argv.slice(2));

Please let me know how to get rid off this issue.

Regards,
Prabhash


问:
Mongoose $sort doesn't work when it's before a populate stage in aggregation pipeline
I have the following Author schema, where an author can rate other authors:

{
  name: String,
  birthDate: Date,
  otherAuthorRatings: {
    type:
      [
        {
          author: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "Author",
          },
          rating: {
            type: Number,
          },
        },
      ],
  }
}
```
<p>I have an aggregation pipeline in which I'm populating the <code>author</code> property in the <code>otherAuthorRatings</code>, which goes through 3 stages, <code>unwind</code>, <code>lookup</code> and <code>group</code> according to this documentation.</p>
<p>Along with this, I want to <code>sort</code> the authors based on their <code>birthDate</code>, <code>skip</code> some elements and <code>limit</code> to a particular number of elements.</p>
<p>My question:-
When I add the sort, skip and limit stages after the population stage, the query works perfectly, but the $sort stage does not work correctly(i.e., returns random values instead of sorted values) when the sort, skip and limit stages are before the populate stage.</p>
<p>I specifically want that the sort, skip and limit stages be before the populate stage because I want to limit the populate stage to certain number of documents and also to use an index(which I cannot use if the sort stage is after the unwind, lookup and group stages).</p>
<p>Is there a particular reason why this happens? Any solution to this?</p>
<p><strong>EDIT 1:-</strong>
I'm trying to sort the outer document, not the properties within the populated entries. Sample docs:-</p>
<pre class="lang-js prettyprint-override"><code>{
  _id: 1,
  name: "foo",
  birthDate: "2022-12-24T00:00:00.000+00:00",
  otherAuthorRatings: [
    {
      author: 3,
      rating: 5
    }
  ],
},
{
  _id: 2,
  name: "bar",
  birthDate: "2022-12-25T00:00:00.000+00:00",
  otherAuthorRatings: [
    {
      author: 1,
      rating: 4
    },
    {
      author: 3,
      rating: 5
    },
  ],
},
{
  _id: 3
  name: "baz",
  birthDate: "2022-12-26T00:00:00.000+00:00",
  otherAuthorRatings: [],
},
</code>```

I want that the author with the birthdate of 24th December arrive before the author with the birthdate of 25th December and 26th December(or reverse if I sort it in descending order). I don't use the populated fields within the embedded document for sorting.

Solution:
Turns out that the group stage messes with the order(I believe this is normal) of transactions. So I had to re-sort the result after the group stage. This wasn't very costly because the sort was happening on a limited number of elements.

Body:
I have the following Author schema, where an author can rate other authors:

{
  name: String,
  birthDate: Date,
  otherAuthorRatings: {
    type:
      [
        {
          author: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "Author",
          },
          rating: {
            type: Number,
          },
        },
      ],
  }
}

I have an aggregation pipeline in which I'm populating the author property in the otherAuthorRatings, which goes through 3 stages, unwind, lookup and group according to this documentation.

Along with this, I want to sort the authors based on their birthDate, skip some elements and limit to a particular number of elements.

My question:-
When I add the sort, skip and limit stages after the population stage, the query works perfectly, but the $sort stage does not work correctly(i.e., returns random values instead of sorted values) when the sort, skip and limit stages are before the populate stage.

I specifically want that the sort, skip and limit stages be before the populate stage because I want to limit the populate stage to certain number of documents and also to use an index(which I cannot use if the sort stage is after the unwind, lookup and group stages).

Is there a particular reason why this happens? Any solution to this?

EDIT 1:-
I'm trying to sort the outer document, not the properties within the populated entries. Sample docs:-

{
  _id: 1,
  name: "foo",
  birthDate: "2022-12-24T00:00:00.000+00:00",
  otherAuthorRatings: [
    {
      author: 3,
      rating: 5
    }
  ],
},
{
  _id: 2,
  name: "bar",
  birthDate: "2022-12-25T00:00:00.000+00:00",
  otherAuthorRatings: [
    {
      author: 1,
      rating: 4
    },
    {
      author: 3,
      rating: 5
    },
  ],
},
{
  _id: 3
  name: "baz",
  birthDate: "2022-12-26T00:00:00.000+00:00",
  otherAuthorRatings: [],
},

I want that the author with the birthdate of 24th December arrive before the author with the birthdate of 25th December and 26th December(or reverse if I sort it in descending order). I don't use the populated fields within the embedded document for sorting.

Solution:
Turns out that the group stage messes with the order(I believe this is normal) of transactions. So I had to re-sort the result after the group stage. This wasn't very costly because the sort was happening on a limited number of elements.


问:
How add a grafana data link to the paricular word in table
I want to link the dashboards for each row in the table in my  Grafana dashboard, which has a table visualisation. I tried using a data link, but it is linking to the entire table when I only wanted it for one row.

I tried using a data link, but it inserted the entire table when I only wanted it for one row.

A specific row in the table can be linked to the dashboard.


问:
How can I use &str or an enum as field type?
<Hi I have Postgres table:

```<code>CREATE TABLE persons (
  id SERIAL NOT NULL PRIMARY KEY,
  age INT NOT NULL,
  sex CHAR(1)
);
</code>```

Where sex can be char 'M' or 'F' or null. Unfortunately, migration sex column to postgres enum is not possible in this case.

I am using rust sqlx to load data from this table. I have:

```<code>#[derive(sqlx::FromRow)]
pub struct PersonSql {
  pub age: int,
  pub sex: Option<String>, // TODO improve it
}
</code>```

Everything works perfectly, but I am afraid that using String type is not the most efficient. It would be nice to Option<char>, enum Option<Sex>, or at least Option<&str>, I tried to use enum like:

```<code>#[derive(Copy, Clone, sqlx::Type, Debug)]
#[sqlx(type_name = "VARCHAR")]
pub enum Sex {
  F,
  M,
}
</code>```

compilation is ok, but error is returned when I run app:

mismatched types; Rust type core::option::Option<app::Sex>
(as SQL type VARCHAR) is not compatible with SQL type CHAR',

Body:
<Hi I have Postgres table:

CREATE TABLE persons (
  id SERIAL NOT NULL PRIMARY KEY,
  age INT NOT NULL,
  sex CHAR(1)
);

Where sex can be char 'M' or 'F' or null. Unfortunately, migration sex column to postgres enum is not possible in this case.

I am using rust sqlx to load data from this table. I have:

#[derive(sqlx::FromRow)]
pub struct PersonSql {
  pub age: int,
  pub sex: Option<String>, // TODO improve it
}

Everything works perfectly, but I am afraid that using String type is not the most efficient. It would be nice to Option<char>, enum Option<Sex>, or at least Option<&str>, I tried to use enum like:

#[derive(Copy, Clone, sqlx::Type, Debug)]
#[sqlx(type_name = "VARCHAR")]
pub enum Sex {
  F,
  M,
}

compilation is ok, but error is returned when I run app:

mismatched types; Rust type core::option::Option<app::Sex>
(as SQL type VARCHAR) is not compatible with SQL type CHAR',


问:
autofill of 4 different fields from 1 SMS with a code in flutter
I have a page for code verification, in it I use 4 text fields with 1 character. When one field is filled, the focus moves to another field. But there is one problem when I log in through iOS, when I enter the code, I see an SMS with a code. And when I type in the code, only one column with the first number is filled. The rest are not. How can I fix it so that when I click 1 the number is in the first field 2 - in the second and so on.

return LayoutBuilder(builder: (context, constraints) {
                          return Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              crossAxisAlignment: CrossAxisAlignment.center,
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                _buildCodeCell(
                                  tc1,
                                  error,
                                  f1,
                                  next: f2,
                                  previous: null,
                                ),
                                _buildCodeCell(
                                  tc2,
                                  error,
                                  f2,
                                  next: f3,
                                  previous: f1,
                                ),
                                _buildCodeCell(
                                  tc3,
                                  error,
                                  f3,
                                  next: f4,
                                  previous: f2,
                                ),
                                _buildCodeCell(
                                  tc4,
                                  error,
                                  f4,
                                  next: null,
                                  previous: f3,
                                ),
                              ]);
                        });```


问:
Customize a trait class with AliasLoader::getInstance()?
I have a core trait class. This is integrated into core controllers and various independent modules (nwidart).

How is it possible to add or override functionality to a trait class? Without adjusting the controllers where the traits are integrated?

The goal is to override an existing trait function and I've tried that with "AliasLoader" so far, unfortunately so far without success.

```<code>namespace Modules\MyModule\Providers;

class Main extends Provider
{
 public function register()
 {
   $loader = AliasLoader::getInstance();
   $loader->alias('App\Traits\Documents', 'Modules\MyModule\Overrides\Traits\Documents');
 }
}
</code>```
```<code>namespace Modules\MyModule\Overrides\Traits;

use App\Traits\Documents as TraitTest;

trait Documents
{
 use TraitTest {
    getNextDocumentNumber as getNextDocumentNumber;
 }

 public function getNextDocumentNumber()
 {
    return '123456789';
 }
}
</code>```

The core trait is then integrated into a core controller, for example, and this cannot be adjusted!

```<code>namespace App\Notifications\Docu;

use App\Traits\Documents;

class Docu extends Notification
{
    use Documents;

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     */
    public function toMail($notifiable): MailMessage
    {
        $message->title($this->getNextDocumentNumber($this->docu);

        return $message;
    }
}
</code>```

Body:
I have a core trait class. This is integrated into core controllers and various independent modules (nwidart).

How is it possible to add or override functionality to a trait class? Without adjusting the controllers where the traits are integrated?

The goal is to override an existing trait function and I've tried that with "AliasLoader" so far, unfortunately so far without success.

namespace Modules\MyModule\Providers;

class Main extends Provider
{
 public function register()
 {
   $loader = AliasLoader::getInstance();
   $loader->alias('App\Traits\Documents', 'Modules\MyModule\Overrides\Traits\Documents');
 }
}

namespace Modules\MyModule\Overrides\Traits;

use App\Traits\Documents as TraitTest;

trait Documents
{
 use TraitTest {
    getNextDocumentNumber as getNextDocumentNumber;
 }

 public function getNextDocumentNumber()
 {
    return '123456789';
 }
}

The core trait is then integrated into a core controller, for example, and this cannot be adjusted!

namespace App\Notifications\Docu;

use App\Traits\Documents;

class Docu extends Notification
{
    use Documents;

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     */
    public function toMail($notifiable): MailMessage
    {
        $message->title($this->getNextDocumentNumber($this->docu);

        return $message;
    }
}


问:
I'm having problem figuring why login is working sometimes but sometimes not with Graph and Firebase
So, I have built this way of auth with firebase and graphql using mongo database, the problem is that everything is working, instead trying to login, its the same way of register but sometimes the method works and some times I get apollo client error, which I don't know why.

Here is my code to auth with Firebase and then check if the user exits and call the method and then the oposite.

import { FirebaseAuth } from "../config/Firebase";
import { GoogleAuthProvider, signInWithPopup } from "firebase/auth";
import { Notifier } from "../utils";

import { USER_AUTH_ERROR } from "../config/Responders";

const Google = async (Register, Login, dispatch) => {
  var Provider = new GoogleAuthProvider();
  const data = await signInWithPopup(FirebaseAuth, Provider);

  try {
    if (data) {
      const user = data.user;
      const creationTime = user.metadata.creationTime;
      const lastSignInTime = user.metadata.lastSignInTime;

      if (creationTime === lastSignInTime) {
        const name = user.displayName.split(" ");
        const firstName = name[0] || "";
        const lastName = name[1] || "";

        const config = {
          variables: {
            createUserInput: {
              Name: firstName,
              Surname: lastName,
              Email: user.email,
              Avatar: user.photoURL || null,
              Uid: user.uid,
            },
          },
        };

        Register(config);
      }

      else {
        const config = {
          variables: {
            uid: user.uid,
          },
        };

        Login(config);
      }
    }

    else Notifier(dispatch, USER_AUTH_ERROR, `error`);
  } catch (error) {
    Notifier(dispatch, USER_AUTH_ERROR, `error`);
  }
};

export
 default Google;
```
<p>While here is the place where I manage the functions:</p>
<pre class="lang-js prettyprint-override"><code>const [Register, { data: registerData }] = useMutation(REGISTER);
  const [Login, { data: loginData }] = useLazyQuery(AUTH);

  const Auther = () => Google(Register, Login, dispatch);

  useEffect(() => {
    if (!account.Auth) {
      if (registerData?.hasOwnProperty("UserRegister")) {
        dispatch(Authenticate(registerData.UserRegister));
      }
    }
  }, [registerData]);

  useEffect(() => {
    if (!account.Auth) {
      if (loginData?.hasOwnProperty("UserAuth")) {
        dispatch(Authenticate(loginData.UserAuth));
      }
    }
  }, [loginData]);
</code>```

Here is the error I get:

Body:
So, I have built this way of auth with firebase and graphql using mongo database, the problem is that everything is working, instead trying to login, its the same way of register but sometimes the method works and some times I get apollo client error, which I don't know why.

Here is my code to auth with Firebase and then check if the user exits and call the method and then the oposite.

import { FirebaseAuth } from "../config/Firebase";
import { GoogleAuthProvider, signInWithPopup } from "firebase/auth";
import { Notifier } from "../utils";

import { USER_AUTH_ERROR } from "../config/Responders";

const Google = async (Register, Login, dispatch) => {
  var Provider = new GoogleAuthProvider();
  const data = await signInWithPopup(FirebaseAuth, Provider);

  try {
    if (data) {
      const user = data.user;
      const creationTime = user.metadata.creationTime;
      const lastSignInTime = user.metadata.lastSignInTime;

      if (creationTime === lastSignInTime) {
        const name = user.displayName.split(" ");
        const firstName = name[0] || "";
        const lastName = name[1] || "";

        const config = {
          variables: {
            createUserInput: {
              Name: firstName,
              Surname: lastName,
              Email: user.email,
              Avatar: user.photoURL || null,
              Uid: user.uid,
            },
          },
        };

        Register(config);
      }

      else {
        const config = {
          variables: {
            uid: user.uid,
          },
        };

        Login(config);
      }
    }

    else Notifier(dispatch, USER_AUTH_ERROR, `error`);
  } catch (error) {
    Notifier(dispatch, USER_AUTH_ERROR, `error`);
  }
};

export
 default Google;

While here is the place where I manage the functions:

const [Register, { data: registerData }] = useMutation(REGISTER);
  const [Login, { data: loginData }] = useLazyQuery(AUTH);

  const Auther = () => Google(Register, Login, dispatch);

  useEffect(() => {
    if (!account.Auth) {
      if (registerData?.hasOwnProperty("UserRegister")) {
        dispatch(Authenticate(registerData.UserRegister));
      }
    }
  }, [registerData]);

  useEffect(() => {
    if (!account.Auth) {
      if (loginData?.hasOwnProperty("UserAuth")) {
        dispatch(Authenticate(loginData.UserAuth));
      }
    }
  }, [loginData]);

Here is the error I get:


问:
Can I host web apps made via PySimpleGUIWeb on Github?
Can I host a python build webpage on Github?

I've made many web apps on PySimpleGuiWeb and wondering if I can host some of them on github.


问:
Implementing Dependency Inversion & Dependency Injection both together by defining structure
I have subcategories defined under Vehicle Class as :-
Bike
Car
truck
bus

Further, there are different variants under each four categories

Bike :- sport, standard

Car :- sport, standard, electric
3.Truck :- Mini Truck , Power Truck

Bus:- Mini Bus, AC Bus

We have to calculate the price of each variants defined in each category.

Example 1 : With Constructor overloading

```<code> public interface ivehicle
    {
        public void calculateprice();
    }

    public class calculatprice : ivehicle
    {
        public void calculateprice() {

        }
    }

    public class bike_1
    {
        public readonly ivehicle vehicle;
        public bike_1(string model) {
            if (model == "STANDARD")
            {
                Console.WriteLine("THe price of standard is 1 lac");
            }
            else if (model == "SPORTS")
            {
                Console.WriteLine("The price of sports is 2 lacs");
            }

        }
    }

</code>```

Example 2:- With using overiding function and inheritance

```<code>    public class vehicle_3
    {

    }

    public class bike_3: vehicle_3

    {
        public virtual void Calculateprice_3() { }

    }

    public class sports_3 :bike_3
    {

        public override void Calculateprice_3()
        {
            base.Calculateprice_3();
            Console.WriteLine("The price of Sports is 2 lacs");
        }

    }

    public class standard_3 : bike_3
    {
        public override void Calculateprice_3()
        {
            base.Calculateprice_3();
            Console.WriteLine("The price of standard is 1 lacs");
        }
    }

</code>```

Example 3:- With interface

```<code>    public class vehicle_4
    {

    }

    public interface ivehicle_4
    {
        void CalculatePrice_4();
    }

    public class bike_4 :ivehicle_4

    {
        public virtual void CalculatePrice_4() { }

    }
    public class sports_4 : bike_4
    {

        public override void CalculatePrice_4()
        {
            base.CalculatePrice_4();
            Console.WriteLine("The price of Sports is 2 lacs");
        }

    }

    public class standard_4 : bike_4
    {
        public override void CalculatePrice_4()
        {
            base.CalculatePrice_4();
            Console.WriteLine("The price of standard is 1 lacs");
        }
    }
</code>```

Body:
I have subcategories defined under Vehicle Class as :-
Bike
Car
truck
bus

Further, there are different variants under each four categories

Bike :- sport, standard

Car :- sport, standard, electric
3.Truck :- Mini Truck , Power Truck

Bus:- Mini Bus, AC Bus

We have to calculate the price of each variants defined in each category.

Example 1 : With Constructor overloading

 public interface ivehicle
    {
        public void calculateprice();
    }

    public class calculatprice : ivehicle
    {
        public void calculateprice() {

        }
    }

    public class bike_1
    {
        public readonly ivehicle vehicle;
        public bike_1(string model) {
            if (model == "STANDARD")
            {
                Console.WriteLine("THe price of standard is 1 lac");
            }
            else if (model == "SPORTS")
            {
                Console.WriteLine("The price of sports is 2 lacs");
            }

        }
    }

Example 2:- With using overiding function and inheritance

    public class vehicle_3
    {

    }

    public class bike_3: vehicle_3

    {
        public virtual void Calculateprice_3() { }

    }

    public class sports_3 :bike_3
    {

        public override void Calculateprice_3()
        {
            base.Calculateprice_3();
            Console.WriteLine("The price of Sports is 2 lacs");
        }

    }

    public class standard_3 : bike_3
    {
        public override void Calculateprice_3()
        {
            base.Calculateprice_3();
            Console.WriteLine("The price of standard is 1 lacs");
        }
    }

Example 3:- With interface

    public class vehicle_4
    {

    }

    public interface ivehicle_4
    {
        void CalculatePrice_4();
    }

    public class bike_4 :ivehicle_4

    {
        public virtual void CalculatePrice_4() { }

    }
    public class sports_4 : bike_4
    {

        public override void CalculatePrice_4()
        {
            base.CalculatePrice_4();
            Console.WriteLine("The price of Sports is 2 lacs");
        }

    }

    public class standard_4 : bike_4
    {
        public override void CalculatePrice_4()
        {
            base.CalculatePrice_4();
            Console.WriteLine("The price of standard is 1 lacs");
        }
    }