问:
How do you log previewView.bitmap in Android Kotlin (Jetpack Compose)?
I just want to log live bitmap data from the previewScreen, but the documentation for PreviewView.bitmap says:

"If the preview hasn't started yet, the method may return null or an empty Bitmap. Use getPreviewStreamState() to get the PreviewView.StreamState and wait for PreviewView.StreamState.STREAMING to make sure the preview is started."

I'm just not sure how to implement that. Please help!

Here's my composable:
`

```<code>package com.example.livestreamdemo.screens

import android.Manifest
import android.content.pm.PackageManager
import android.util.Log
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.camera.core.CameraSelector
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.view.PreviewView
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.viewinterop.AndroidView
import androidx.core.content.ContextCompat
import com.example.livestreamdemo.util.Common.REQUIRED_PERMISSIONS

@Composable
fun CameraPreviewScreen() {
    val lifecycleOwner = LocalLifecycleOwner.current
    val context = LocalContext.current
    val cameraProviderNext = remember { ProcessCameraProvider.getInstance(context) }

    var hasCamPermission by remember {
        mutableStateOf(
            REQUIRED_PERMISSIONS.all {
                ContextCompat.checkSelfPermission(context, it) ==
                        PackageManager.PERMISSION_GRANTED
            })
    }

    val launcher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.RequestMultiplePermissions(),
        onResult = { granted ->
            hasCamPermission = granted.size == 2
        }
    )

    LaunchedEffect(key1 = true) {
        launcher.launch(
            arrayOf(
                Manifest.permission.CAMERA,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            )
        )
    }
    if(hasCamPermission) {
        AndroidView(
            factory = { ctx ->
                val previewView = PreviewView(ctx)
                val exec = ContextCompat.getMainExecutor(ctx)
                cameraProviderNext.addListener({

                    val cameraProvider = cameraProviderNext.get()
                    val preview = Preview.Builder().build()
                        .also {
                            it.setSurfaceProvider(previewView.surfaceProvider)
                        }
                    val cameraSelector = CameraSelector.Builder()
                        .requireLensFacing(CameraSelector.LENS_FACING_BACK)
                        .build()

                    cameraProvider.unbindAll()
                    cameraProvider.bindToLifecycle(
                        lifecycleOwner,
                        cameraSelector,
                        preview
                    )

                }, exec)
                previewView
            },
            modifier = Modifier.fillMaxSize(),
        )
    }
}
</code>```

`

I've tried logging previewView.bitmap but it's returned null so I just need to know how to wait for PreviewView.StreamState.STREAMING somehow. Any help would be much appreciated!

Body:
I just want to log live bitmap data from the previewScreen, but the documentation for PreviewView.bitmap says:

"If the preview hasn't started yet, the method may return null or an empty Bitmap. Use getPreviewStreamState() to get the PreviewView.StreamState and wait for PreviewView.StreamState.STREAMING to make sure the preview is started."

I'm just not sure how to implement that. Please help!

Here's my composable:
`

package com.example.livestreamdemo.screens

import android.Manifest
import android.content.pm.PackageManager
import android.util.Log
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.camera.core.CameraSelector
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.view.PreviewView
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.viewinterop.AndroidView
import androidx.core.content.ContextCompat
import com.example.livestreamdemo.util.Common.REQUIRED_PERMISSIONS

@Composable
fun CameraPreviewScreen() {
    val lifecycleOwner = LocalLifecycleOwner.current
    val context = LocalContext.current
    val cameraProviderNext = remember { ProcessCameraProvider.getInstance(context) }

    var hasCamPermission by remember {
        mutableStateOf(
            REQUIRED_PERMISSIONS.all {
                ContextCompat.checkSelfPermission(context, it) ==
                        PackageManager.PERMISSION_GRANTED
            })
    }

    val launcher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.RequestMultiplePermissions(),
        onResult = { granted ->
            hasCamPermission = granted.size == 2
        }
    )

    LaunchedEffect(key1 = true) {
        launcher.launch(
            arrayOf(
                Manifest.permission.CAMERA,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            )
        )
    }
    if(hasCamPermission) {
        AndroidView(
            factory = { ctx ->
                val previewView = PreviewView(ctx)
                val exec = ContextCompat.getMainExecutor(ctx)
                cameraProviderNext.addListener({

                    val cameraProvider = cameraProviderNext.get()
                    val preview = Preview.Builder().build()
                        .also {
                            it.setSurfaceProvider(previewView.surfaceProvider)
                        }
                    val cameraSelector = CameraSelector.Builder()
                        .requireLensFacing(CameraSelector.LENS_FACING_BACK)
                        .build()

                    cameraProvider.unbindAll()
                    cameraProvider.bindToLifecycle(
                        lifecycleOwner,
                        cameraSelector,
                        preview
                    )

                }, exec)
                previewView
            },
            modifier = Modifier.fillMaxSize(),
        )
    }
}

`

I've tried logging previewView.bitmap but it's returned null so I just need to know how to wait for PreviewView.StreamState.STREAMING somehow. Any help would be much appreciated!


来源: stackexchange

问:
Why do transitions between two `GoRoute`s with `pageBuilder` transitions not work in Flutter?

Summary

I want to set up entry and exit transitions in flutter. I'm using the go_router package and navigate via context.go. I have set up a working transition on GoRoute. However, setting up a transition on another GoRoute and navigating between the two causes the transition to break. I need help understanding why.

Full

I have two views, ViewA and ViewB like this:

class ViewA extends StatelessWidget {
  const ViewA({super.key});

  @override
  Widget build(BuildContext context) {
    Future.delayed(const Duration(seconds: 5), () {
      context.go("/B");
    });
    return /* ... */;
  }
}

class ViewB extends StatelessWidget {
  const ViewB({super.key});

  @override
  Widget build(BuildContext context) {
    Future.delayed(const Duration(seconds: 5), () {
      context.go("/A");
    });
    return /* ... */;
  }
}
```
<p>I have set up routes for these views like this:</p>
<pre class="lang-dart prettyprint-override"><code>final routes = GoRouter(routes: <RouteBase>[
  GoRoute(
    path: "/A",
    pageBuilder: (context, state) => CustomTransitionPage(
      child: const ViewA(),
      transitionDuration: const Duration(seconds: 2),
      transitionsBuilder: (context, animation, secondaryAnimation, child) =>
          FadeTransition(
              opacity:
                  CurveTween(curve: Curves.easeInOutCirc).animate(animation),
              child: child),
    ),
  ),
  GoRoute(
    path: "/B",
    pageBuilder: (context, state) => CustomTransitionPage(
        child: const ViewB(),
        transitionDuration: const Duration(seconds: 2),
        transitionsBuilder: (context, animation, secondaryAnimation, child) =>
            FadeTransition(
              opacity:
                  CurveTween(curve: Curves.easeInOutCirc).animate(animation),
              child: child,
            ),
    ),
  ),
]);
</code>```

However, this results in no transition at all. If I instead change the second route to

GoRoute(
  path: "/B",
  builder: (context, state) => const ViewB(),
),
```

The animation from "B" -> "A" uses a fade transition as expected whereas "A" -> "B" falls back on the default transition animation.

How can I get a fade transition both ways between A and B?

Why do the transitions stop working if I define one for each route?

ContentLicense: CC BY-SA 4.0

Body:
Summary

I want to set up entry and exit transitions in flutter. I'm using the go_router package and navigate via context.go. I have set up a working transition on GoRoute. However, setting up a transition on another GoRoute and navigating between the two causes the transition to break. I need help understanding why.

Full

I have two views, ViewA and ViewB like this:

class ViewA extends StatelessWidget {
  const ViewA({super.key});

  @override
  Widget build(BuildContext context) {
    Future.delayed(const Duration(seconds: 5), () {
      context.go("/B");
    });
    return /* ... */;
  }
}

class ViewB extends StatelessWidget {
  const ViewB({super.key});

  @override
  Widget build(BuildContext context) {
    Future.delayed(const Duration(seconds: 5), () {
      context.go("/A");
    });
    return /* ... */;
  }
}

I have set up routes for these views like this:

final routes = GoRouter(routes: <RouteBase>[
  GoRoute(
    path: "/A",
    pageBuilder: (context, state) => CustomTransitionPage(
      child: const ViewA(),
      transitionDuration: const Duration(seconds: 2),
      transitionsBuilder: (context, animation, secondaryAnimation, child) =>
          FadeTransition(
              opacity:
                  CurveTween(curve: Curves.easeInOutCirc).animate(animation),
              child: child),
    ),
  ),
  GoRoute(
    path: "/B",
    pageBuilder: (context, state) => CustomTransitionPage(
        child: const ViewB(),
        transitionDuration: const Duration(seconds: 2),
        transitionsBuilder: (context, animation, secondaryAnimation, child) =>
            FadeTransition(
              opacity:
                  CurveTween(curve: Curves.easeInOutCirc).animate(animation),
              child: child,
            ),
    ),
  ),
]);

However, this results in no transition at all. If I instead change the second route to

GoRoute(
  path: "/B",
  builder: (context, state) => const ViewB(),
),

The animation from "B" -> "A" uses a fade transition as expected whereas "A" -> "B" falls back on the default transition animation.

How can I get a fade transition both ways between A and B?

Why do the transitions stop working if I define one for each route?


问:
How do I make the p-value stationary even after transforming it?
I've tried diff.1:, diff.2: np.log, np.sqrt, np.cbrt but the p-value won't decrease.

diff seems to increase the p-values and np.sqrt and np.cbrt barely decreases the p-value.

is there a way to transform non-stationary values that don't become stationary even after transforming using the previously stated methods?

Here is the multivariate table:

Time Period
EMT
DTS
BG

01/04/2021
7.41
7.25
7.53

01/07/2021
7.71
7.52
7.46

01/10/2021
7.99
7.75
7.66

01/01/2022
8.10
7.83
7.73

01/04/2022
8.13
7.81
7.85

01/07/2022
7.70
7.50
7.50

```<code>data = pd.read_csv(inputfilepath, parse_dates=["Time Period"], index_col = "Time Period")

emtdata = data["EMT"]
dtsdata = data["DTS"]
bgdata = data["Bord Gais"]

    ad_fuller_result_4 = adfuller(bgdata)#.diff()[1:]

    print('BG')
    print(f'ADF Statistic: {ad_fuller_result_4[0]}')
    print(f'p-value: {ad_fuller_result_4[1]}')

    ad_fuller_result_7 = adfuller(dtsdata)#.diff()[1:])

    print('DTS')
    print(f'ADF Statistic: {ad_fuller_result_7[0]}')
    print(f'p-value: {ad_fuller_result_7[1]}')

    ad_fuller_result_8 = adfuller(emtdata)#.diff()[1:])

    print('EMT')
    print(f'ADF Statistic: {ad_fuller_result_8[0]}')
    print(f'p-value: {ad_fuller_result_8[1]}')
</code>```

Here are the results:

```<code>EM&T
ADF Statistic: -0.15394452831058553
p-value: 0.9437932628988958

DTS
ADF Statistic: -0.0951392833474996
p-value: 0.9499205326778699

BG
ADF Statistic: -1.5425205176459476
p-value: 0.5123820913571207
</code>```

Body:
I've tried diff.1:, diff.2: np.log, np.sqrt, np.cbrt but the p-value won't decrease.

diff seems to increase the p-values and np.sqrt and np.cbrt barely decreases the p-value.

is there a way to transform non-stationary values that don't become stationary even after transforming using the previously stated methods?

Here is the multivariate table:

Time Period
EMT
DTS
BG

01/04/2021
7.41
7.25
7.53

01/07/2021
7.71
7.52
7.46

01/10/2021
7.99
7.75
7.66

01/01/2022
8.10
7.83
7.73

01/04/2022
8.13
7.81
7.85

01/07/2022
7.70
7.50
7.50

data = pd.read_csv(inputfilepath, parse_dates=["Time Period"], index_col = "Time Period")

emtdata = data["EMT"]
dtsdata = data["DTS"]
bgdata = data["Bord Gais"]

    ad_fuller_result_4 = adfuller(bgdata)#.diff()[1:]

    print('BG')
    print(f'ADF Statistic: {ad_fuller_result_4[0]}')
    print(f'p-value: {ad_fuller_result_4[1]}')

    ad_fuller_result_7 = adfuller(dtsdata)#.diff()[1:])

    print('DTS')
    print(f'ADF Statistic: {ad_fuller_result_7[0]}')
    print(f'p-value: {ad_fuller_result_7[1]}')

    ad_fuller_result_8 = adfuller(emtdata)#.diff()[1:])

    print('EMT')
    print(f'ADF Statistic: {ad_fuller_result_8[0]}')
    print(f'p-value: {ad_fuller_result_8[1]}')

Here are the results:

EM&T
ADF Statistic: -0.15394452831058553
p-value: 0.9437932628988958

DTS
ADF Statistic: -0.0951392833474996
p-value: 0.9499205326778699

BG
ADF Statistic: -1.5425205176459476
p-value: 0.5123820913571207


问:
Where is `lv_style_copy` in the lvgl repository?
I am currently trying out LVGL and ran into the following issue:
I found that with the function lv_style_copy(...) I can copy one style into the other. I need this to base my styles off of each other.
It is explicitly stated in the documentation here.

I downloaded the Visual Studio test solution from this repository and was able to get some GUI going on my pc.

Now I wanted to use the above mentioned function, however it is not being found by the linker. A search in the sources and the solution didnt yield any results: The function is defined nowhere. Even in the official LVGL repo, I wasnt able to find this function. Using the lgvl/lv_apps repo, I can find the function, but only the calling of the function. Here, too, the function is nowhere declared nor defined.

Where can I find this function? What do I need to include?
Why is it mentioned in the documentation and then not implemented? How should I handle the copying of styles? Simply assigning the struct values results in a runtime error.


问:
Robot Framework: "Argument got value that cannot be converted to None"
Has anybody run into this problem? I have a test that is working just fine, and I was adding the DataDriver Library for Robot Framework inside of PyCharm. I decided to go a different direction with my tests. When I came back to run them again, I got this error message.

```<code>python -m robot -t "Logins" Logins.robot
==============================================================================
PRCLogins :: Login tests
==============================================================================
Logins                                                           | FAIL |
ValueError: Argument 'url' got value 'https://<URL>' that cannot be converted to None.
------------------------------------------------------------------------------
PRCLogins :: Login tests                                              | FAIL |
1 test, 0 passed, 1 failed
==============================================================================
Output:  C:\Automation\TestSuite\output.xml
Log:     C:\Automation\TestSuite\log.html
Report:  C:\Automation\TestSuite\report.html

Process finished with exit code 1
</code>```

And now, NONE of my tests will run. Not even the tests that had nothing to do with this test suite. I'm fully blocked somehow and now cannot run ANY of my tests. Has anybody seen this error before? Please help!

Body:
Has anybody run into this problem? I have a test that is working just fine, and I was adding the DataDriver Library for Robot Framework inside of PyCharm. I decided to go a different direction with my tests. When I came back to run them again, I got this error message.

python -m robot -t "Logins" Logins.robot
==============================================================================
PRCLogins :: Login tests
==============================================================================
Logins                                                           | FAIL |
ValueError: Argument 'url' got value 'https://<URL>' that cannot be converted to None.
------------------------------------------------------------------------------
PRCLogins :: Login tests                                              | FAIL |
1 test, 0 passed, 1 failed
==============================================================================
Output:  C:\Automation\TestSuite\output.xml
Log:     C:\Automation\TestSuite\log.html
Report:  C:\Automation\TestSuite\report.html

Process finished with exit code 1

And now, NONE of my tests will run. Not even the tests that had nothing to do with this test suite. I'm fully blocked somehow and now cannot run ANY of my tests. Has anybody seen this error before? Please help!


问:
getting an error snapshot.data is not a function
Tech stack: React, Firebase, Next.js

My website runs like this; when a user registers, a document (in 'User' collection), a 'vote' subcollection containing 2 documents, is created. And right after that user registers, the website should call 2 functions: getUserInfo() and getUserVotes from useEffect(), which basically read all the documents which was created earlier.

Now. The problem is, when a user first registered, and this getUserVotes is called, there was an error saying threadSnap.data is not a function even though threadSnap is supposed to be document snapshot not querySnapshot (which is why this should work properly). But after refreshing a page, this error just disappears.

```<code>const getUserVotes = async (user) => {
    const uid = user.uid;
    if (user) {
      Promise.allSettled([
        getDoc(doc(db, "users", uid, "votes", "threads")),
        getDoc(doc(db, "users", uid, "votes", "replies"))
      ]).then(([threadSnap, replySnap]) => {
        setUserVotes({
          threads: threadSnap.data(),
          replies: replySnap.data()
        })
      })
    }
  }
</code>```

At first, I tried calling getDoc two times like this

```<code>threadSnap = await getDoc(doc(db, "users", uid, "votes", "threads")),
replySnap = await getDoc(doc(db, "users", uid, "votes", "replies"))
setUserVotes({
  threads: threadSnap.data(),
  replies: replySnap.data()
})
</code>```

But it seems like JS calls setUserVotes evenn before two promises complete. Then, I use Promise.all on two getDoc but then the state both becomes undefined (for some reason). Finally, I land on Promise.allSettled which seems to work normally except when the user registers for the first time that the error threadSnap.data is not a function. I expect my program to wait for two getDoc to resolve before setting my state through setUserVotes. Can you guys help?

Body:
Tech stack: React, Firebase, Next.js

My website runs like this; when a user registers, a document (in 'User' collection), a 'vote' subcollection containing 2 documents, is created. And right after that user registers, the website should call 2 functions: getUserInfo() and getUserVotes from useEffect(), which basically read all the documents which was created earlier.

Now. The problem is, when a user first registered, and this getUserVotes is called, there was an error saying threadSnap.data is not a function even though threadSnap is supposed to be document snapshot not querySnapshot (which is why this should work properly). But after refreshing a page, this error just disappears.

const getUserVotes = async (user) => {
    const uid = user.uid;
    if (user) {
      Promise.allSettled([
        getDoc(doc(db, "users", uid, "votes", "threads")),
        getDoc(doc(db, "users", uid, "votes", "replies"))
      ]).then(([threadSnap, replySnap]) => {
        setUserVotes({
          threads: threadSnap.data(),
          replies: replySnap.data()
        })
      })
    }
  }

At first, I tried calling getDoc two times like this

threadSnap = await getDoc(doc(db, "users", uid, "votes", "threads")),
replySnap = await getDoc(doc(db, "users", uid, "votes", "replies"))
setUserVotes({
  threads: threadSnap.data(),
  replies: replySnap.data()
})

But it seems like JS calls setUserVotes evenn before two promises complete. Then, I use Promise.all on two getDoc but then the state both becomes undefined (for some reason). Finally, I land on Promise.allSettled which seems to work normally except when the user registers for the first time that the error threadSnap.data is not a function. I expect my program to wait for two getDoc to resolve before setting my state through setUserVotes. Can you guys help?


问:
Using Python Gitlab API to search for all public repositories
I want to identify all public repositories in Gitlab with a specific condition. For example, I want to identify all Java projects that has "AndoridManifest.xml" file and contains the word "app" in the repository title or the readme file.

I could do this task with GitHub, but I find it difficult to use the Gitlab search API using python gitlab.

Below is my code

account = Gitlab('Private token') for item in account.search(gitlab.const.SearchScope.PROJECTS, 'regression', iterator=True):       print(item)

I expected that I get an iterator that traverses for all open-source (public) repositories in Gitlab. So, I can filter such repositories if they contain the "AndoridManifest.xml"

But I get  MissingSchema error. Anyone knows how to solve this error and how I can use python to traverse all Gitlab projects with a specific criteria.


问:
Allowing access to a PyFilesystem fs over a network, e.g. via FTP
I am attempting to build an application that will allow multiple users to maintain personal, sandboxed file systems on a server, but access them via a client application.

I've determined that I can use PyFilesystem to store these file systems as single files, probably as TarFS or ZipFS instances, and the server can reference them as mutable within memory alone rather than extracting the archive.

Ideally, I would prefer to provide a given user access to their corresponding personal filesystem via an FTP so that the user can mount it as a drive, rather than having the user download/upload the entire archive each time they want to access their data.

What I need to make this happen is a way to open the FS on the server side, then spawn an FTP server that points to the mounted FS.

I am currently able to create the necessary archives, open the archives and store them in-memory as file systems, store the memory-resident file systems as archives, spawn an FTP server, and mount an open FTP server as a drive on the client side.  Only part I'm missing is a way to direct that FTP server to the memory-resident file system instead of the OS file system.


问:
Trouble with using more than one JwtBearer authentication providers
I am trying to add the ability to use two different JwtBearer providers for authentication. One being Auth0 and the other being a custom one. I am testing the implementation with Postman, but I keep getting a Parse Error: Invalid character in chunk size.

Postman error screenshot

I was using this post as a reference for how to do this. I was also looking at this Microsoft doc which also shows how to do this as well. Below is what my implementation looks like.

```<code>builder.Services
    .AddAuthentication()
    .AddJwtBearer("Auth0", options =>
    {
        options.Authority = builder.Configuration["Auth0:Domain"];
        options.Audience = builder.Configuration["Auth0:Audience"];
        options.Events = new JwtBearerEvents
        {
            OnAuthenticationFailed = context =>
            {
                context.Response.OnStarting(async () =>
                {
                    await context.Response.WriteAsync("You are not authorized to be here. Go away.");
                });
                return Task.CompletedTask;
            },
            OnForbidden = context =>
            {
                context.Response.OnStarting(async () =>
                {
                    await context.Response.WriteAsync("You are a valid user, but Forbidden to use this resource");
                });
                return Task.CompletedTask;
            }
        };
        options.TokenValidationParameters = new TokenValidationParameters
        {
            NameClaimType = ClaimTypes.NameIdentifier
        };
    })
    .AddJwtBearer("Custom", options =>
    {
        options.Events = new JwtBearerEvents
        {
            OnAuthenticationFailed = context =>
            {
                context.Response.OnStarting(async () =>
                {
                    await context.Response.WriteAsync("You are not authorized to be here. Go Away.");
                });
                return Task.CompletedTask;
            }
        };
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = false,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = builder.Configuration["JwtIssuer"],
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["JwtSecretKey"])),
            ClockSkew = TimeSpan.Zero
        };
    });
</code>```
```<code>builder.Services.AddAuthorization(options =>
{
    options.DefaultPolicy = new AuthorizationPolicyBuilder()
     .RequireAuthenticatedUser()
     .AddAuthenticationSchemes("Custom", "Auth0")
     .Build();
});
</code>```

I am currently testing with the custom implementation and it seems to work as intended, the JWT token get validated and allows the request to continue to the controller.

The controller endpoint implementation is below.

```<code>    [Authorize]
    [HttpGet("byid/{id?}")]
    public ActionResult<IEnumerable<EdgeDevice>> GetEdgeById(Guid? id)
    {
        if(id.HasValue)
        {
            return Ok(_edgeDeviceRepo.GetSingle(id.Value));
        }
        return BadRequest();
    }
</code>```

It successfully gets into the controller and has a value for the id and the repo returns a device from the database but then the error mentioned above appears within Postman. I have been doing some debugging and I was able to determine that when I don't set the default policy in builder.Services.AddAuthorization(); everything works and the response get send back to Postman.

Am I missing something here? Do I not need to specify a default policy? Thank you for any and all help in advance!

Body:
I am trying to add the ability to use two different JwtBearer providers for authentication. One being Auth0 and the other being a custom one. I am testing the implementation with Postman, but I keep getting a Parse Error: Invalid character in chunk size.

Postman error screenshot

I was using this post as a reference for how to do this. I was also looking at this Microsoft doc which also shows how to do this as well. Below is what my implementation looks like.

builder.Services
    .AddAuthentication()
    .AddJwtBearer("Auth0", options =>
    {
        options.Authority = builder.Configuration["Auth0:Domain"];
        options.Audience = builder.Configuration["Auth0:Audience"];
        options.Events = new JwtBearerEvents
        {
            OnAuthenticationFailed = context =>
            {
                context.Response.OnStarting(async () =>
                {
                    await context.Response.WriteAsync("You are not authorized to be here. Go away.");
                });
                return Task.CompletedTask;
            },
            OnForbidden = context =>
            {
                context.Response.OnStarting(async () =>
                {
                    await context.Response.WriteAsync("You are a valid user, but Forbidden to use this resource");
                });
                return Task.CompletedTask;
            }
        };
        options.TokenValidationParameters = new TokenValidationParameters
        {
            NameClaimType = ClaimTypes.NameIdentifier
        };
    })
    .AddJwtBearer("Custom", options =>
    {
        options.Events = new JwtBearerEvents
        {
            OnAuthenticationFailed = context =>
            {
                context.Response.OnStarting(async () =>
                {
                    await context.Response.WriteAsync("You are not authorized to be here. Go Away.");
                });
                return Task.CompletedTask;
            }
        };
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = false,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = builder.Configuration["JwtIssuer"],
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["JwtSecretKey"])),
            ClockSkew = TimeSpan.Zero
        };
    });

builder.Services.AddAuthorization(options =>
{
    options.DefaultPolicy = new AuthorizationPolicyBuilder()
     .RequireAuthenticatedUser()
     .AddAuthenticationSchemes("Custom", "Auth0")
     .Build();
});

I am currently testing with the custom implementation and it seems to work as intended, the JWT token get validated and allows the request to continue to the controller.

The controller endpoint implementation is below.

    [Authorize]
    [HttpGet("byid/{id?}")]
    public ActionResult<IEnumerable<EdgeDevice>> GetEdgeById(Guid? id)
    {
        if(id.HasValue)
        {
            return Ok(_edgeDeviceRepo.GetSingle(id.Value));
        }
        return BadRequest();
    }

It successfully gets into the controller and has a value for the id and the repo returns a device from the database but then the error mentioned above appears within Postman. I have been doing some debugging and I was able to determine that when I don't set the default policy in builder.Services.AddAuthorization(); everything works and the response get send back to Postman.

Am I missing something here? Do I not need to specify a default policy? Thank you for any and all help in advance!


问:
JNI is destroyed the first time it is instantiated
I have a project that I run in a T2 terminal, when I restart and/or shut down the T2 terminal and install the project for the first time, it crashes, but it only happens once, then everything works fine. I am using an sdk for a honeywell model 1950g barcode scanner that will connect to the T2 terminal.

I already tried using the coroutines but it still fails, with asynctask too. The idea is to check the connected usb devices and then be able to control whether to connect or disconnect this device.


问:
Best markov chain's order for discrete data
I would like to know if there is a way to get the AIC and BIC of the different orders of the markov chain derived by the command:

fitHigherOrder() from the markovchain package.

What I am looking for is something like:

```<code>maxOrder <- 5
result <- data.frame()
for (k in 1:maxOrder) {
  skip_to_next <- FALSE
  mc <- tryCatch(fitMarkovChain(clickstreamList = mydata, order = k), error = function(e) {skip_to_next <<- TRUE})
  if(skip_to_next){
    next
  }else{
    result <- rbind(result, c(k, summary(mc)$aic, summary(mc)$bic))
  }
}
</code>```

Use for clickstreams https://bookdown.org/gubiithefish/test/403-Clickstream-application.html

I have tried the same function with fitHigherOrder and fitHigherOrder()$aic but they didn't work.

Does it exist a command like assessOrder() that allows to choose the optimal order when orders are greater than two?

Body:
I would like to know if there is a way to get the AIC and BIC of the different orders of the markov chain derived by the command:

fitHigherOrder() from the markovchain package.

What I am looking for is something like:

maxOrder <- 5
result <- data.frame()
for (k in 1:maxOrder) {
  skip_to_next <- FALSE
  mc <- tryCatch(fitMarkovChain(clickstreamList = mydata, order = k), error = function(e) {skip_to_next <<- TRUE})
  if(skip_to_next){
    next
  }else{
    result <- rbind(result, c(k, summary(mc)$aic, summary(mc)$bic))
  }
}

Use for clickstreams https://bookdown.org/gubiithefish/test/403-Clickstream-application.html

I have tried the same function with fitHigherOrder and fitHigherOrder()$aic but they didn't work.

Does it exist a command like assessOrder() that allows to choose the optimal order when orders are greater than two?


问:
How to connect two tables by month slicer in excel?
I have two tables,

Transaction table- [Category Type,  Category, Sub-Category, Amount, Date(dd-mm-yy), Time, Transaction Method]

2)Budget Table - [Month(mmm-yyy), Category, Budget, Sum]

I want to connect the two by month with a slicer
and also want to create a table having all the categories from two table along with its respective total amount from table 1 and total budget from table 2?

I have tried with relationships. I will appreciate if solution could be in simple excel, if there could not be any other solution power pivot and vba is accepted .

Thanks in advance


问:
Flutter recourses (Execution failed for task ':app:processDebugResources'.)
```<code>Execution failed for task ':app:processDebugResources'.
> A failure occurred while executing com.android.build.gradle.internal.res.LinkApplicationAndroidResourcesTask$TaskAction
   > Android resource linking failed
     ERROR:D:\PROGRAMING\Flutter Project\dicee\android\app\src\main\res\mipmap-anydpi-v26\ic_launcher_round.xml:3: AAPT: error: resource drawable/ic_launcher_background (aka kunjshingala.com.dicee:drawable/ic_launcher_background) not found.
</code>```
<p>the given files and detail
And resource files are </p>

Body:
Execution failed for task ':app:processDebugResources'.
> A failure occurred while executing com.android.build.gradle.internal.res.LinkApplicationAndroidResourcesTask$TaskAction
   > Android resource linking failed
     ERROR:D:\PROGRAMING\Flutter Project\dicee\android\app\src\main\res\mipmap-anydpi-v26\ic_launcher_round.xml:3: AAPT: error: resource drawable/ic_launcher_background (aka kunjshingala.com.dicee:drawable/ic_launcher_background) not found.

the given files and detail
And resource files are


问:
Adding JS Tag in Android Studio?
I am using a service called Anytrack for postback url purpose and it requires to add an js tag in the header section of a website as i  have a application, my question is how can I add the js tag into my app for tracking purpose.

If yes where should I add it or i have to built the website for it please help

Title: Adding JS Tag in Android Studio?


问:
Ruby: if condition in attributes to handle missing key-value
I have a resource class that I use as intermediate DTO for mapping from my model to my API response. I would like to prevent any situation in which any part of the response payload might be delivered as nil. This is what I have

```<code>attr_reader :json_block, :element

def initialize(attributes = {})
 @json_block = attributes['some_json']
 @element = attributes['some_json']['element']
 ....
</code>```

I thought I could have an something along these lines:

```<code>if attributes['json_block'].exists?
  @json_block = attributes['json_block']
  @element = attributes['element']
end
</code>```

Is this the correct approach? I would like a solution whereby if it comes in nil, we can ignore it and unmarshall the payload.

Thank you

Body:
I have a resource class that I use as intermediate DTO for mapping from my model to my API response. I would like to prevent any situation in which any part of the response payload might be delivered as nil. This is what I have

attr_reader :json_block, :element

def initialize(attributes = {})
 @json_block = attributes['some_json']
 @element = attributes['some_json']['element']
 ....

I thought I could have an something along these lines:

if attributes['json_block'].exists?
  @json_block = attributes['json_block']
  @element = attributes['element']
end

Is this the correct approach? I would like a solution whereby if it comes in nil, we can ignore it and unmarshall the payload.

Thank you


问:
Positioning a slide relative to a grandparent whilst moving the parent slider (Image carousel)
Edit: I've added a solution that uses JS to get the grandparent's width and then sets the slide width (which allows the slide and the slider to be positioned absolutely), but I'm still interested if this can be done with css

Original question

So I'm trying to make an image carousel. I've absolutely positioned the slides in relation to their grandparent (the white .dummy-page), so that I can make sure that the correct number of slides (and margins) are visible. It looks like this:

The problem is that to move the .slider (the parent with the red border) that contains the .slidess I need to position it absolutely. But this breaks the sizing of each .slide, which are set to 30% of .dummy-page, but become 30% of the .slider.

I thought using transform might help (as I don't have to then position the parent absolutely), but the same happens (uncomment line 9 in the JS to see the effect)

Would appreciate other ideas on how to position/size the slides, because I think my approach is fundamentally flawed

Thanks!

Codepen link

const moveLeft = () => {
  const slider = document.querySelector('.slider');
  const slide = document.querySelector('.slide');
  const slideWidth = slide.offsetWidth;
  const slideLeft = parseFloat(getComputedStyle(slide).left);
  const offset = slideWidth + slideLeft;

  // addStyle(slider, {'left': `${offset}px`});
  // slider.style.transform = `translateX(${30}px)`;
}

const addStyle = (element, style) => {
    for (const property in style) element.style[property] = style[property];
}

moveLeft();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  margin: 0;
  padding: 0;
}

:root {
  --slide-width: 30%;
  --slide-height: 15rem;
  --num-slides: 5;
  --visible-slides: 3;
  --slide-margin: calc( (100% - var(--visible-slides) * var(--slide-width)) / (var(--visible-slides) + 1) );
}

.container {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100vh;
  background-color: grey;
}

.dummy-page {
  position: relative;
  width: 60%;
  height: 90%;
  background-color: white;
}

.slider {
  display: inline-flex;

  /*   Each slide has width and a margin-right, + 1 LHS margin */
  width: calc(var(--num-slides) * (var(--slide-width) + var(--slide-margin)) + var(--slide-margin));
  height: var(--slide-height);

  margin-top: 2rem;

  border: 1px solid red;
}

.slide {
  position: absolute;
  height: var(--slide-height);
  width: var(--slide-width);
  background-color: lightgrey;
  border: 1px solid grey;
}

.slide-1 {
  left: var(--slide-margin);
}
.slide-2 {
  left: calc(var(--slide-margin) * 2 + var(--slide-width))
}
.slide-3 {
  left: calc(var(--slide-margin) * 3 + var(--slide-width) * 2);
}

.slide-4 {
  left: calc(var(--slide-margin) * 4 + var(--slide-width) * 3);
}

.slide-5 {
  left: calc(var(--slide-margin) * 5 + var(--slide-width) * 4);
}

.btn-container {
  display: flex;
  justify-content: center;
  width: 100%;
}
.btn {
  display: inline-flex;
  margin: .5rem;
  padding: .8rem 1.5rem;
  border: 1px solid lightgrey;
}</code>```

Left

Right

```
</div>
</div>
</p>
<hr />
<p><strong>JS (almost working) solution</strong></p>
<p>I added an additional slider container here for ease of use later, but I'm grabbing the grandparent element's width using JS (which is annoyingly out by 10px), and then setting the slide width. This means that both the slide and the slider can be positioned absolutely</p>
<p>codepen</p>
```const initSlider = () => {
  const pageWidth = document.querySelector('.slider-container').offsetWidth;

  const numSlides = parseInt(getCssVariable('--num-slides'));
  const slideWidth = pageWidth / numSlides;

  setCssVariable('--slide-width', `${slideWidth}px`);

}

const getCssVariable = (name) => {
  return getComputedStyle(document.documentElement).getPropertyValue(name);
}

const setCssVariable = (name, value) => {
  document.documentElement.style.setProperty(name, value);
}

window.addEventListener('DOMContentLoaded', initSlider());
```

Body:
Edit: I've added a solution that uses JS to get the grandparent's width and then sets the slide width (which allows the slide and the slider to be positioned absolutely), but I'm still interested if this can be done with css

Original question

So I'm trying to make an image carousel. I've absolutely positioned the slides in relation to their grandparent (the white .dummy-page), so that I can make sure that the correct number of slides (and margins) are visible. It looks like this:

The problem is that to move the .slider (the parent with the red border) that contains the .slidess I need to position it absolutely. But this breaks the sizing of each .slide, which are set to 30% of .dummy-page, but become 30% of the .slider.

I thought using transform might help (as I don't have to then position the parent absolutely), but the same happens (uncomment line 9 in the JS to see the effect)

Would appreciate other ideas on how to position/size the slides, because I think my approach is fundamentally flawed

Thanks!

Codepen link

const moveLeft = () => {
  const slider = document.querySelector('.slider');
  const slide = document.querySelector('.slide');
  const slideWidth = slide.offsetWidth;
  const slideLeft = parseFloat(getComputedStyle(slide).left);
  const offset = slideWidth + slideLeft;

  // addStyle(slider, {'left': `${offset}px`});
  // slider.style.transform = `translateX(${30}px)`;
}

const addStyle = (element, style) => {
    for (const property in style) element.style[property] = style[property];
}

moveLeft();

* {
  margin: 0;
  padding: 0;
}

:root {
  --slide-width: 30%;
  --slide-height: 15rem;
  --num-slides: 5;
  --visible-slides: 3;
  --slide-margin: calc( (100% - var(--visible-slides) * var(--slide-width)) / (var(--visible-slides) + 1) );
}

.container {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100vh;
  background-color: grey;
}

.dummy-page {
  position: relative;
  width: 60%;
  height: 90%;
  background-color: white;
}

.slider {
  display: inline-flex;

  /*   Each slide has width and a margin-right, + 1 LHS margin */
  width: calc(var(--num-slides) * (var(--slide-width) + var(--slide-margin)) + var(--slide-margin));
  height: var(--slide-height);

  margin-top: 2rem;

  border: 1px solid red;
}

.slide {
  position: absolute;
  height: var(--slide-height);
  width: var(--slide-width);
  background-color: lightgrey;
  border: 1px solid grey;
}

.slide-1 {
  left: var(--slide-margin);
}
.slide-2 {
  left: calc(var(--slide-margin) * 2 + var(--slide-width))
}
.slide-3 {
  left: calc(var(--slide-margin) * 3 + var(--slide-width) * 2);
}

.slide-4 {
  left: calc(var(--slide-margin) * 4 + var(--slide-width) * 3);
}

.slide-5 {
  left: calc(var(--slide-margin) * 5 + var(--slide-width) * 4);
}

.btn-container {
  display: flex;
  justify-content: center;
  width: 100%;
}
.btn {
  display: inline-flex;
  margin: .5rem;
  padding: .8rem 1.5rem;
  border: 1px solid lightgrey;
}

Left

Right

JS (almost working) solution

I added an additional slider container here for ease of use later, but I'm grabbing the grandparent element's width using JS (which is annoyingly out by 10px), and then setting the slide width. This means that both the slide and the slider can be positioned absolutely

codepen

const initSlider = () => {
  const pageWidth = document.querySelector('.slider-container').offsetWidth;

  const numSlides = parseInt(getCssVariable('--num-slides'));
  const slideWidth = pageWidth / numSlides;

  setCssVariable('--slide-width', `${slideWidth}px`);

}

const getCssVariable = (name) => {
  return getComputedStyle(document.documentElement).getPropertyValue(name);
}

const setCssVariable = (name, value) => {
  document.documentElement.style.setProperty(name, value);
}

window.addEventListener('DOMContentLoaded', initSlider());


问:
how to prevent duplicate files from being added to sate React <input type="file" >?
how to prevent duplicate files from being added to the state?

Is there an option to compare them somehow, and then write them to the state?


问:
Should I use double quotes? (Shell Script)
I have a block of C Shell script like this:

```<code>set scriptname="`basename $0`"
set lockfile=/var/run/$scriptname.pid
set overridefile=/var/tmp/$scriptname.override
set logdir=/var/log/myapp

umask 022

set hostname=`/bin/hostname`

if (-e $overridefile) then
   ...
   exit 1
endif

if (-r $lockfile) then
   ...
endif

...

/bin/rm -f $lockfile
exit 0

</code>```

I am not sure about the line

```<code>set scriptname="`basename $0`"
</code>```

I want to get the name of the current script. Do I need the double quotes here? Is this the correct way to do so?

Body:
I have a block of C Shell script like this:

set scriptname="`basename $0`"
set lockfile=/var/run/$scriptname.pid
set overridefile=/var/tmp/$scriptname.override
set logdir=/var/log/myapp

umask 022

set hostname=`/bin/hostname`

if (-e $overridefile) then
   ...
   exit 1
endif

if (-r $lockfile) then
   ...
endif

...

/bin/rm -f $lockfile
exit 0

I am not sure about the line

set scriptname="`basename $0`"

I want to get the name of the current script. Do I need the double quotes here? Is this the correct way to do so?


问:
Libgdx 3d particle error on initialization
I'm having a rendering issue for 3d particles created with the flame particle editor in libgdx.

I'm using a particle system to render 3d particles created with flame, I followed the tutorial in the libgdx' official site: code taken from: , but when I try to render them, I get the following error:

Cannot invoke "com.badlogic.gdx.graphics.g3d.particles.batches.ParticleBatch.draw(com.badlogic.gdx.graphics.g3d.particles.renderers.ParticleControllerRenderData)" because "this.batch" is null
```
<p>Here's my code:</p>
```    class MyGame : ApplicationAdapter(){
    //3d stuff
    lateinit var cam: PerspectiveCamera
    lateinit var camController: CameraInputController
    lateinit var modelBatch: ModelBatch
    lateinit var environment: Environment
    lateinit var model: Model
    lateinit var mb:ModelBuilder
    //lateinit var ground:ModelInstance

    lateinit var ecs:World
    //creating the bullet world
    lateinit var broadphase: btBroadphaseInterface
    lateinit var dynamicsWorld: btDynamicsWorld
    lateinit var constraintSolver: btConstraintSolver
    lateinit var collisionConfig: btCollisionConfiguration
    lateinit var dispatcher: btDispatcher
    lateinit var contactListener: MyContactListener
    //debug drawer
    lateinit var debugDrawer: DebugDrawer
    //particle effects
    lateinit var particleSystem:ParticleSystem
    lateinit var pointSpriteBatch:PointSpriteParticleBatch

    override fun create() {
        Bullet.init()
        //initializing 3d stuff
        mb = ModelBuilder()
        initializeWorld()
        initializeBullet()
        ecs= world {
            injectables {
                add(mb)
                add(modelBatch)
                add(cam)
                add(camController)
                add(environment)
                add(dynamicsWorld)
                add(debugDrawer)
                add(contactListener)
            }
            components {
                onAdd(BulletComponent, BulletComponent.onAdd)
                onRemove(BulletComponent, BulletComponent.onRemove)
            }
            systems {
                //the model system works just fine!
                add(ModelSystems())
                //this is going to be fun
                add(BulletSystem())
            }
        }
        with(ecs){//creating the ground
            mb.begin()
            //ok so for every model you create you giv it an id (makes everything more flexible)
            mb.node().id="ground"
            mb.part(
                "ground",
                GL20.GL_TRIANGLES,
                (VertexAttributes.Usage.Position or VertexAttributes.Usage.Normal).toLong(),
                Material(
                    ColorAttribute.createDiffuse(Color.RED)
                )
            )
                .box(0f, 0f, 0f, 5f, 1f, 5f)
            model=mb.end()

            var motionState=MotionState(ModelInstance(model).transform)

            val ground=entity {
                //it+=ModelComponent(ModelInstance(model))
                it+=BulletComponent(motionState, btBoxShape(Vector3(2.5f, 0.5f, 2.5f)),0f)
            }

        }

    }

    private fun initializeBullet() {
        collisionConfig = btDefaultCollisionConfiguration()
        dispatcher = btCollisionDispatcher(collisionConfig)
        broadphase = btDbvtBroadphase()
        //setting the dynamic world
        constraintSolver= btSequentialImpulseConstraintSolver()
        dynamicsWorld= btDiscreteDynamicsWorld(dispatcher,broadphase, constraintSolver, collisionConfig)
        dynamicsWorld.gravity= Vector3(0f, -1.8f, 0f)

        contactListener = MyContactListener()

        debugDrawer=DebugDrawer().apply {
            debugMode= btIDebugDraw.DebugDrawModes.DBG_DrawWireframe
        }
        dynamicsWorld.debugDrawer=debugDrawer
    }

    fun initializeWorld(){
        modelBatch = ModelBatch()
        environment = Environment()
        environment.set(ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f))
        environment.add(DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f))
        cam = PerspectiveCamera(
            67f, Gdx.graphics.width.toFloat(), Gdx.graphics.height
                .toFloat()
        )
        cam.position[3f, 7f] = 10f
        cam.lookAt(0f, 4f, 0f)
        cam.near = 1f
        cam.far = 300f
        cam.update()
        camController = CameraInputController(cam)
        Gdx.input.inputProcessor = camController
        //initializing particle effects
        particleSystem=ParticleSystem()
        pointSpriteBatch = PointSpriteParticleBatch()
        pointSpriteBatch.setCamera(cam)
        particleSystem.add(pointSpriteBatch)
        //adding the particle effect to an asset manager
        var assets=AssetManager()
        var loadParam=ParticleEffectLoader.ParticleEffectLoadParameter(particleSystem.batches)
        assets.load("myfirst3dparticles.pfx",
            ParticleEffect::class.java, loadParam)
        assets.finishLoading()
        //passing the particle effect from the asset manager to the particle system
        val originalEffect: ParticleEffect = assets.get("myfirst3dparticles.pfx")
// we cannot use the originalEffect, we must make a copy each time we create new particle effect
        val effect = originalEffect.copy()
        effect.init()
        effect.start() // optional: particle will begin playing immediately

        particleSystem.add(effect)

    }

    override fun render() {
        Gdx.gl.glClearColor(0f, 0f, 0f, 1f)
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT or GL20.GL_DEPTH_BUFFER_BIT)
        Gdx.gl.glEnable(GL20.GL_TEXTURE_2D)

        //always update the camera if you're gonna make changes to it
        //cam.update()
        camController.update()

        modelBatch.begin(cam)
        //modelBatch.render(ground, environment)
        //setting particles to be rendered
        particleSystem.update()
        particleSystem.begin()
        particleSystem.draw()
        particleSystem.end()
        modelBatch.render(particleSystem)

        ecs.update(Gdx.graphics.deltaTime)
        modelBatch.end()
    }
```

Body:
I'm having a rendering issue for 3d particles created with the flame particle editor in libgdx.

I'm using a particle system to render 3d particles created with flame, I followed the tutorial in the libgdx' official site: code taken from: , but when I try to render them, I get the following error:

Cannot invoke "com.badlogic.gdx.graphics.g3d.particles.batches.ParticleBatch.draw(com.badlogic.gdx.graphics.g3d.particles.renderers.ParticleControllerRenderData)" because "this.batch" is null

Here's my code:

    class MyGame : ApplicationAdapter(){
    //3d stuff
    lateinit var cam: PerspectiveCamera
    lateinit var camController: CameraInputController
    lateinit var modelBatch: ModelBatch
    lateinit var environment: Environment
    lateinit var model: Model
    lateinit var mb:ModelBuilder
    //lateinit var ground:ModelInstance

    lateinit var ecs:World
    //creating the bullet world
    lateinit var broadphase: btBroadphaseInterface
    lateinit var dynamicsWorld: btDynamicsWorld
    lateinit var constraintSolver: btConstraintSolver
    lateinit var collisionConfig: btCollisionConfiguration
    lateinit var dispatcher: btDispatcher
    lateinit var contactListener: MyContactListener
    //debug drawer
    lateinit var debugDrawer: DebugDrawer
    //particle effects
    lateinit var particleSystem:ParticleSystem
    lateinit var pointSpriteBatch:PointSpriteParticleBatch

    override fun create() {
        Bullet.init()
        //initializing 3d stuff
        mb = ModelBuilder()
        initializeWorld()
        initializeBullet()
        ecs= world {
            injectables {
                add(mb)
                add(modelBatch)
                add(cam)
                add(camController)
                add(environment)
                add(dynamicsWorld)
                add(debugDrawer)
                add(contactListener)
            }
            components {
                onAdd(BulletComponent, BulletComponent.onAdd)
                onRemove(BulletComponent, BulletComponent.onRemove)
            }
            systems {
                //the model system works just fine!
                add(ModelSystems())
                //this is going to be fun
                add(BulletSystem())
            }
        }
        with(ecs){//creating the ground
            mb.begin()
            //ok so for every model you create you giv it an id (makes everything more flexible)
            mb.node().id="ground"
            mb.part(
                "ground",
                GL20.GL_TRIANGLES,
                (VertexAttributes.Usage.Position or VertexAttributes.Usage.Normal).toLong(),
                Material(
                    ColorAttribute.createDiffuse(Color.RED)
                )
            )
                .box(0f, 0f, 0f, 5f, 1f, 5f)
            model=mb.end()

            var motionState=MotionState(ModelInstance(model).transform)

            val ground=entity {
                //it+=ModelComponent(ModelInstance(model))
                it+=BulletComponent(motionState, btBoxShape(Vector3(2.5f, 0.5f, 2.5f)),0f)
            }

        }

    }

    private fun initializeBullet() {
        collisionConfig = btDefaultCollisionConfiguration()
        dispatcher = btCollisionDispatcher(collisionConfig)
        broadphase = btDbvtBroadphase()
        //setting the dynamic world
        constraintSolver= btSequentialImpulseConstraintSolver()
        dynamicsWorld= btDiscreteDynamicsWorld(dispatcher,broadphase, constraintSolver, collisionConfig)
        dynamicsWorld.gravity= Vector3(0f, -1.8f, 0f)

        contactListener = MyContactListener()

        debugDrawer=DebugDrawer().apply {
            debugMode= btIDebugDraw.DebugDrawModes.DBG_DrawWireframe
        }
        dynamicsWorld.debugDrawer=debugDrawer
    }

    fun initializeWorld(){
        modelBatch = ModelBatch()
        environment = Environment()
        environment.set(ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f))
        environment.add(DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f))
        cam = PerspectiveCamera(
            67f, Gdx.graphics.width.toFloat(), Gdx.graphics.height
                .toFloat()
        )
        cam.position[3f, 7f] = 10f
        cam.lookAt(0f, 4f, 0f)
        cam.near = 1f
        cam.far = 300f
        cam.update()
        camController = CameraInputController(cam)
        Gdx.input.inputProcessor = camController
        //initializing particle effects
        particleSystem=ParticleSystem()
        pointSpriteBatch = PointSpriteParticleBatch()
        pointSpriteBatch.setCamera(cam)
        particleSystem.add(pointSpriteBatch)
        //adding the particle effect to an asset manager
        var assets=AssetManager()
        var loadParam=ParticleEffectLoader.ParticleEffectLoadParameter(particleSystem.batches)
        assets.load("myfirst3dparticles.pfx",
            ParticleEffect::class.java, loadParam)
        assets.finishLoading()
        //passing the particle effect from the asset manager to the particle system
        val originalEffect: ParticleEffect = assets.get("myfirst3dparticles.pfx")
// we cannot use the originalEffect, we must make a copy each time we create new particle effect
        val effect = originalEffect.copy()
        effect.init()
        effect.start() // optional: particle will begin playing immediately

        particleSystem.add(effect)

    }

    override fun render() {
        Gdx.gl.glClearColor(0f, 0f, 0f, 1f)
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT or GL20.GL_DEPTH_BUFFER_BIT)
        Gdx.gl.glEnable(GL20.GL_TEXTURE_2D)

        //always update the camera if you're gonna make changes to it
        //cam.update()
        camController.update()

        modelBatch.begin(cam)
        //modelBatch.render(ground, environment)
        //setting particles to be rendered
        particleSystem.update()
        particleSystem.begin()
        particleSystem.draw()
        particleSystem.end()
        modelBatch.render(particleSystem)

        ecs.update(Gdx.graphics.deltaTime)
        modelBatch.end()
    }


问:
Why can't we implicitly convert a noconst-elements array to a full-const-elements array?
Here is an example of what I mean (I am using VS 2022 with C++11):

```<code>// Printing function: does not modify any array member, so everything should be const
void PrintArray(int const*const (&ct)[3])
{
    printf("ct: x%p, {%u, %u, %u}\n",
           &ct, ct[0] ? *ct[0] : 0, ct[1] ? *ct[1] : 0, ct[2] ? *ct[2] : 0);
}
</code>```
```<code>int main(int argc, unsigned short* argv[])
{
    // At some point: declare (and use) a modifiable array
    int a = 1, b = 2, c = 3;
    int* t[3] = {&a, &b, &c};

    // At some later point: want to use the array without modifying it,
    // then lets try some conversions
    int* (&u)[3] = t;           // OK - Same type conversion
    int*const (&v)[3] = t;      // OK - adding first constness on array elements
    int const*const (&w)[3] = t;    // FAIL: adding both constnesses on elements:
                        // error C2440 "cannot convert from 'int *[3]' to
                                        //'const int *const (&)[3]"  (ON VS 2022 C++ 11)
    int const*const (&x)[3] = const_cast<int const*const(&)[3]>(t);
                                        // FAIL: same error C2440
    int const*const (&y)[3] = reinterpret_cast<int const*const(&)[3]>(t);
                                        // OK - but annoyingly verbose and source of casting
                                        // errors

    // Of course the same problem happens for passing through functions call
    PrintArray(t);                      // FAIL
    PrintArray(reinterpret_cast<int const*const(&)[3]>(t));     // OK... but still annoying !

    return 0;
}
</code>```

OK, we know that reinterpret_cast is working, so I have a workaround here. So my question is more theoritical about C++ language:

Does someone know if the implicit conversion compiles on other compilers, like gcc ?

Does someone know if the C++ standard forbid this failing implicit conversion ?

And mostly, if the standard does forbid it, WHY ??? I KNOW that const conversions can lead to const/unconst inconsistencies sometimes. E.g. would have been the case if converting t to int const* (&)[3] because we could have added a const int into an array that is not const at the begining. But, in my example above, everything is const so I cannot find any weakness. Does someone see one ? Or is it just because it was too complex at the time for compilers to assert the rightness of the conversion ?

(Additional question for the braves: why cons_cast is failing here while it is only a constness casting ?)

These questions are for my C++ culture, I am open to all your analysis :)
Kind regards to everybody.

Body:
Here is an example of what I mean (I am using VS 2022 with C++11):

// Printing function: does not modify any array member, so everything should be const
void PrintArray(int const*const (&ct)[3])
{
    printf("ct: x%p, {%u, %u, %u}\n",
           &ct, ct[0] ? *ct[0] : 0, ct[1] ? *ct[1] : 0, ct[2] ? *ct[2] : 0);
}

int main(int argc, unsigned short* argv[])
{
    // At some point: declare (and use) a modifiable array
    int a = 1, b = 2, c = 3;
    int* t[3] = {&a, &b, &c};

    // At some later point: want to use the array without modifying it,
    // then lets try some conversions
    int* (&u)[3] = t;           // OK - Same type conversion
    int*const (&v)[3] = t;      // OK - adding first constness on array elements
    int const*const (&w)[3] = t;    // FAIL: adding both constnesses on elements:
                        // error C2440 "cannot convert from 'int *[3]' to
                                        //'const int *const (&)[3]"  (ON VS 2022 C++ 11)
    int const*const (&x)[3] = const_cast<int const*const(&)[3]>(t);
                                        // FAIL: same error C2440
    int const*const (&y)[3] = reinterpret_cast<int const*const(&)[3]>(t);
                                        // OK - but annoyingly verbose and source of casting
                                        // errors

    // Of course the same problem happens for passing through functions call
    PrintArray(t);                      // FAIL
    PrintArray(reinterpret_cast<int const*const(&)[3]>(t));     // OK... but still annoying !

    return 0;
}

OK, we know that reinterpret_cast is working, so I have a workaround here. So my question is more theoritical about C++ language:

Does someone know if the implicit conversion compiles on other compilers, like gcc ?

Does someone know if the C++ standard forbid this failing implicit conversion ?

And mostly, if the standard does forbid it, WHY ??? I KNOW that const conversions can lead to const/unconst inconsistencies sometimes. E.g. would have been the case if converting t to int const* (&)[3] because we could have added a const int into an array that is not const at the begining. But, in my example above, everything is const so I cannot find any weakness. Does someone see one ? Or is it just because it was too complex at the time for compilers to assert the rightness of the conversion ?

(Additional question for the braves: why cons_cast is failing here while it is only a constness casting ?)

These questions are for my C++ culture, I am open to all your analysis :)
Kind regards to everybody.


问:
How to generate JavaScript DocFX documentation in an MVC project?
I've successfully generated a documentation website with DocFX for C# of apps written with .NET Core MVC and Razor Pages. The DocFX guide says it also supports generating API documentation for JavaScript. I want to do that for files in wwwroot folder of my MVC projects.

Right now, I'm just trying to generate the YAML files mentioned in section 2.2 General Metadata of the linked documentation. I created the node2doxfx.json file:

```<code>{
  "source": {
    "include": [ "C:/Users/username/Source/Repos/Tracker/Scan/wwwroot/js" ]
  },
  "destination": "C:/Users/username/source/repos/Tracker/Documentation"
}
</code>```

Then I ran the following command in the terminal:

```<code>node 'C:\Users\username\source\repos\Tracker\Scan\wwwroot\js\site.js' node2docfx.json
</code>```

I get no error in the terminal when executing this command, but I don't see any files generated in .../Tracker/Documentation destination folder.

Where is my mistake and how can I get this to work?

Body:
I've successfully generated a documentation website with DocFX for C# of apps written with .NET Core MVC and Razor Pages. The DocFX guide says it also supports generating API documentation for JavaScript. I want to do that for files in wwwroot folder of my MVC projects.

Right now, I'm just trying to generate the YAML files mentioned in section 2.2 General Metadata of the linked documentation. I created the node2doxfx.json file:

{
  "source": {
    "include": [ "C:/Users/username/Source/Repos/Tracker/Scan/wwwroot/js" ]
  },
  "destination": "C:/Users/username/source/repos/Tracker/Documentation"
}

Then I ran the following command in the terminal:

node 'C:\Users\username\source\repos\Tracker\Scan\wwwroot\js\site.js' node2docfx.json

I get no error in the terminal when executing this command, but I don't see any files generated in .../Tracker/Documentation destination folder.

Where is my mistake and how can I get this to work?


问:
.NET MAUI equivalent of Xamarin.Android.Support.V7 packages?
So I'm trying to migrate a Xamarin.Forms app to .NET MAUI, but I noticed that the Android.Support.V7 namespace isn't available in in the latter, though Xamarin.Forms has the Xamarin.Android.Support.V7 packages available.  Does .NET MAUI have anything similar that I can use?

If you would like to duplicate this yourself, simply add the following line anywhere in a .NET MAUI app:
private Android.Support.V7.Widget.Toolbar toolbar;


问:
How to update whole column of Google sheet with Mnemonic Seed words using python
I am generating mnemonic seeds with HDWallet and I want to store all those 12 words seed in a google sheet

I have connected my google sheet API to python and its working

But I want data to go from B2 to B till the end but when I run it, It keeps on updating B2 only

```<code>import gspread
from hdwallet.utils import generate_mnemonic
# Create the Client
sa = gspread.service_account("my_google_sheet_api.json")

# opens a spreadsheet by its name/title
sh = sa.open("Data")
wks = sh.worksheet("Sheet1")

while True:
    mnemonic1: str = generate_mnemonic(language="english", strength=128)
    wks.update_cells('B2:B', mnemonic1)
    print("m1=", mnemonic1)
</code>```

Body:
I am generating mnemonic seeds with HDWallet and I want to store all those 12 words seed in a google sheet

I have connected my google sheet API to python and its working

But I want data to go from B2 to B till the end but when I run it, It keeps on updating B2 only

import gspread
from hdwallet.utils import generate_mnemonic
# Create the Client
sa = gspread.service_account("my_google_sheet_api.json")

# opens a spreadsheet by its name/title
sh = sa.open("Data")
wks = sh.worksheet("Sheet1")

while True:
    mnemonic1: str = generate_mnemonic(language="english", strength=128)
    wks.update_cells('B2:B', mnemonic1)
    print("m1=", mnemonic1)


问:
Nuxt.js + Vue.js + Javascript Hackernews API displaying comments (nested kids also)
I have following code in my project:

```<code><template>
  <div>
    <Head>
    <Title>{{ story.title}}</Title>
    <Meta name="description" content="product.description" />
  </Head>

    <StoryDetails :story="story" />
    <button class="btn">
        <NuxtLink to="/">Back to home</NuxtLink>
    </button>
  </div>
</template>
</code>```

scripts:

```<code><script setup>
  definePageMeta({
    layout: "stories"
  })
    const { id } = useRoute().params
  const uri = 'https://hacker-news.firebaseio.com/v0/item/'+ id +'.json?print=pretty'
  const { data: story } = await useFetch(uri, { key:id })
  const { data: comments} = []
  if(!this.story.value) {
    throw createError({ statusCode: 404, statusMessage: 'Story not found!', fatal: true })
  }
    this.story.kids.forEach(id => {
      $fetch('https://hacker-news.firebaseio.com/v0/item/'+ id +'.json?print=pretty')
          .then((response) => {
              this.comments.push(response)
              console.log(this.comments)
          })
          .catch(err=> {q
            this.err = err
          })
      })
  console.log(this.comments)
</script>
</code>```

Please, help. How can I display comments (nested kids also) ?

I am getting this error for code above:
GET http://localhost:3000/_nuxt/pages/[id].vue?vue&type=style&index=0&scoped=dd4001d8&lang.css net::ERR_ABORTED 404 (Page not found: /_nuxt/pages/[id].vue?vue&type=style&index=0&scoped=dd4001d8&lang.css)

My github repo: https://github.com/AzizxonZufarov/newsnuxt2/blob/main/pages/%5Bid%5D.vue

PS: Also I am getting this error:

```<code>[plugin:vite:css] [postcss] C:/Users/Acer/Desktop/newsnuxt/pages/[id].vue?vue&type=style&index=0&scoped=dd4001d8&lang.css:4:15: Unknown word
C:/Users/Acer/Desktop/newsnuxt/pages/[id].vue:4:15
2  |    <div>
3  |      <Head>
4  |      <Title>{{ story.title}}</Title>
   |                 ^
5  |      <Meta name="description" content="product.description" />
6  |    </Head>
</code>```

Body:
I have following code in my project:

<template>

    <Title>{{ story.title}}</Title>
    <Meta name="description" content="product.description" />

    <StoryDetails :story="story" />
    <button class="btn">
        <NuxtLink to="/">Back to home</NuxtLink>
    </button>

</template>

scripts:

Please, help. How can I display comments (nested kids also) ?

I am getting this error for code above:
GET http://localhost:3000/_nuxt/pages/[id].vue?vue&type=style&index=0&scoped=dd4001d8&lang.css net::ERR_ABORTED 404 (Page not found: /_nuxt/pages/[id].vue?vue&type=style&index=0&scoped=dd4001d8&lang.css)

My github repo: https://github.com/AzizxonZufarov/newsnuxt2/blob/main/pages/%5Bid%5D.vue

PS: Also I am getting this error:

[plugin:vite:css] [postcss] C:/Users/Acer/Desktop/newsnuxt/pages/[id].vue?vue&type=style&index=0&scoped=dd4001d8&lang.css:4:15: Unknown word
C:/Users/Acer/Desktop/newsnuxt/pages/[id].vue:4:15
2  |

3  |
4  |      <Title>{{ story.title}}</Title>
   |                 ^
5  |      <Meta name="description" content="product.description" />
6  |


问:
C++ error C2676: binary '==': 'const _Ty' does not define this operator or a conversion to a type acceptable to the predefined operator
I am trying to compile my code for a student grading app, this is the exact error I keep getting.  Visual Studio 2019 C++ console app.

C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.27.29110\include\list(1603,65):error C2676: binary '==': 'const _Ty' does not define this operator or a conversion to a type acceptable to the predefined operatorwith[_Ty=Assignment]1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.27.29110\include\list(1602): message : while compiling class template member function 'auto std::list<Assignment,std::allocator<Assignment>>::remove(const _Ty &)'with[_Ty=Assignment]

The error is somewhere inside this part of the code, and I believe somewhere in removing from the list.  But I am not exactly sure where, any help is appreciated.

```<code>#include <iostream>
#include <list>
#include <algorithm>
#include <iterator>
using namespace std;

class Assignment {
public:
    std::string clas;
    std::string type;
    double grade;

    Assignment(std::string c, std::string t, double g) {
        clas = c;
        type = t;
        grade = g;
    }

    double getGrade() {
        return grade;
    }
    string getType() {
        return type;
    }
    //Check to see if user input is valid
    bool isGradeValid() {
        if (0 > grade || grade > 100)
            return false;
        return true;
    }
};

class Student {
private:
    std::string name;
    double HW_grade;
    double Test_grade;
    double overallgrade;
    std::string lettergrade;

public:

    list<Assignment> allAssignments;
    list<Assignment>::iterator it = allAssignments.begin();

    void editAssignment() {
        print(allAssignments);
        std::cout << "You are editng an assingment. ";
        std::string clas;
        std::cout << "Enter class: ";
        std::cin >> clas;
        std::string type;
        std::cout << "Enter type (HW or test): ";
        std::cin >> type;
        double grade;
        std::cout << "Enter grade (0-100): ";
        std::cin >> grade;
        Assignment editAssignment = Assignment(clas, type, grade);
        it = std::find(allAssignments.begin(), allAssignments.end(), editAssignment);
        if (it != allAssignments.end())
        {
            std::cout << "This is the new edited assignment. ";
            std::string clas;
            std::cout << "Enter class: ";
            std::cin >> clas;
            std::string type;
            std::cout << "Enter type (HW or test): ";
            std::cin >> type;
            double grade;
            std::cout << "Enter grade (0-100): ";
            std::cin >> grade;
            Assignment newAssignment = Assignment(clas, type, grade);
            if (editAssignment.isGradeValid() == false)
            {
                std::cout << "Assignment is not valid.\n";
            }
            allAssignments.insert(it, newAssignment);
        }
        else {
            std::cout << "That assignment does not exist.\n";
            return;
        }

    }

    void deleteAssignment(){
        print(allAssignments);
        std::cout << "You are deleting an assingment. ";
        std::string clas;
        std::cout << "Enter class: ";
        std::cin >> clas;
        std::string type;
        std::cout << "Enter type (HW or test): ";
        std::cin >> type;
        double grade;
        std::cout << "Enter grade (0-100): ";
        std::cin >> grade;
        Assignment delAssignment = Assignment(clas, type, grade);
        it = std::find(allAssignments.begin(), allAssignments.end(), delAssignment);
        if (it != allAssignments.end())
        {
            allAssignments.remove(delAssignment);
        }
        else {
            std::cout << "That assignment does not exist.\n";
            return;
        }
    }

    void setName(string n) {
        name = n;
    }
    string getName() {
        return name;
    }
    void setHWGrade(double hw) {
        HW_grade = hw;
    }
    double getHWGrade() {
        return HW_grade;
    }
    void setTestGrade(double t) {
        Test_grade = t;
    }
    double getTestGrade() {
        return Test_grade;
    }
    void setOverallGrade(double o) {
        overallgrade = o;
    }
    double getOverallGrade() {
        return overallgrade;
    }
    void setLetterGrade(string LG) {
        lettergrade = LG;
    }
    string getLetterGrade() {
        return lettergrade;
    }

    void print(std::list<Assignment> const& list)
    {
        std::copy(list.begin(),
            list.end(),
            std::ostream_iterator<Assignment>(std::cout, "\n"));
    }
};
</code>```

Body:
I am trying to compile my code for a student grading app, this is the exact error I keep getting.  Visual Studio 2019 C++ console app.

C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.27.29110\include\list(1603,65):error C2676: binary '==': 'const _Ty' does not define this operator or a conversion to a type acceptable to the predefined operatorwith[_Ty=Assignment]1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.27.29110\include\list(1602): message : while compiling class template member function 'auto std::list<Assignment,std::allocator<Assignment>>::remove(const _Ty &)'with[_Ty=Assignment]

The error is somewhere inside this part of the code, and I believe somewhere in removing from the list.  But I am not exactly sure where, any help is appreciated.

#include <iostream>
#include <list>
#include <algorithm>
#include <iterator>
using namespace std;

class Assignment {
public:
    std::string clas;
    std::string type;
    double grade;

    Assignment(std::string c, std::string t, double g) {
        clas = c;
        type = t;
        grade = g;
    }

    double getGrade() {
        return grade;
    }
    string getType() {
        return type;
    }
    //Check to see if user input is valid
    bool isGradeValid() {
        if (0 > grade || grade > 100)
            return false;
        return true;
    }
};

class Student {
private:
    std::string name;
    double HW_grade;
    double Test_grade;
    double overallgrade;
    std::string lettergrade;

public:

    list<Assignment> allAssignments;
    list<Assignment>::iterator it = allAssignments.begin();

    void editAssignment() {
        print(allAssignments);
        std::cout << "You are editng an assingment. ";
        std::string clas;
        std::cout << "Enter class: ";
        std::cin >> clas;
        std::string type;
        std::cout << "Enter type (HW or test): ";
        std::cin >> type;
        double grade;
        std::cout << "Enter grade (0-100): ";
        std::cin >> grade;
        Assignment editAssignment = Assignment(clas, type, grade);
        it = std::find(allAssignments.begin(), allAssignments.end(), editAssignment);
        if (it != allAssignments.end())
        {
            std::cout << "This is the new edited assignment. ";
            std::string clas;
            std::cout << "Enter class: ";
            std::cin >> clas;
            std::string type;
            std::cout << "Enter type (HW or test): ";
            std::cin >> type;
            double grade;
            std::cout << "Enter grade (0-100): ";
            std::cin >> grade;
            Assignment newAssignment = Assignment(clas, type, grade);
            if (editAssignment.isGradeValid() == false)
            {
                std::cout << "Assignment is not valid.\n";
            }
            allAssignments.insert(it, newAssignment);
        }
        else {
            std::cout << "That assignment does not exist.\n";
            return;
        }

    }

    void deleteAssignment(){
        print(allAssignments);
        std::cout << "You are deleting an assingment. ";
        std::string clas;
        std::cout << "Enter class: ";
        std::cin >> clas;
        std::string type;
        std::cout << "Enter type (HW or test): ";
        std::cin >> type;
        double grade;
        std::cout << "Enter grade (0-100): ";
        std::cin >> grade;
        Assignment delAssignment = Assignment(clas, type, grade);
        it = std::find(allAssignments.begin(), allAssignments.end(), delAssignment);
        if (it != allAssignments.end())
        {
            allAssignments.remove(delAssignment);
        }
        else {
            std::cout << "That assignment does not exist.\n";
            return;
        }
    }

    void setName(string n) {
        name = n;
    }
    string getName() {
        return name;
    }
    void setHWGrade(double hw) {
        HW_grade = hw;
    }
    double getHWGrade() {
        return HW_grade;
    }
    void setTestGrade(double t) {
        Test_grade = t;
    }
    double getTestGrade() {
        return Test_grade;
    }
    void setOverallGrade(double o) {
        overallgrade = o;
    }
    double getOverallGrade() {
        return overallgrade;
    }
    void setLetterGrade(string LG) {
        lettergrade = LG;
    }
    string getLetterGrade() {
        return lettergrade;
    }

    void print(std::list<Assignment> const& list)
    {
        std::copy(list.begin(),
            list.end(),
            std::ostream_iterator<Assignment>(std::cout, "\n"));
    }
};


问:
Is it possible to change default line spacing of the single text line?
I faced with such issue. When I try to change line spacing on Android it doesn't work correctly in case of single text line. In case of two or more text lines it is working.

So, is it possible to make it with the single line?(

I've tried to use lineSpacingExtra, but it doesn't work correctly


问:
How to test element onClick function with cypress on react?
I have a component which, when clicked, it expands and shows more information. I'm trying to test that action of expanding when I click at the component, but cypress returns me code error but there's no code error when running on development and testing by myself.

My attempt was click the component, and check if the new information appears, if so, then it would be the correct behavior.

Component:

```<code>...

export const MaterialCard: React.FC<IMaterialCard> = ({ material }) => {

  const [isExpanded, setIsExpanded] = useState<boolean>(false)

  return (

    *<Container data-cy='container' onClick={() => setIsExpanded(!isExpanded)} style={isExpanded ? { maxWidth: 635 } : { maxWidth: 320 }}>*

        {isExpanded && (
          <>
            <Row style={{ marginTop: 16 }}>
              <Col><h6 style={{ color: "#606060", fontSize: 16, fontWeight: 700 }}>Ementa</h6></Col>
            </Row>
            <Row style={{ marginTop: 16 }}>
              <Col >
                <span style={{ fontSize: 14, color: "#333" }}>
                  {material.resume}
                </span>
              </Col>
            </Row>
            <Row style={{ marginTop: 16 }}>
              <Col style={{ textAlign: 'center' }}>
                *<Link data-cy='toDetail' to={'/detail'} >Ver material completo</Link>*
              </Col>
            </Row>
          </>

        )}
    </Container>
</code>```

Test:

```<code>describe('Material Card', () => {

  beforeEach(() => {
    cy.mount(<MaterialCard material={material} />)
  })

  it('should expand when clicked', () => {

    cy.get('[data-cy=container]').click()
    cy.get('[data-cy=toDetail]').should('have.text', 'Ver material completo')
  })

})
</code>```

Error:

The following error originated from your application code, not from Cypress.

Invariant failed

When Cypress detects uncaught errors originating from your application it will automatically fail the current test.

Body:
I have a component which, when clicked, it expands and shows more information. I'm trying to test that action of expanding when I click at the component, but cypress returns me code error but there's no code error when running on development and testing by myself.

My attempt was click the component, and check if the new information appears, if so, then it would be the correct behavior.

Component:

...

export const MaterialCard: React.FC<IMaterialCard> = ({ material }) => {

  const [isExpanded, setIsExpanded] = useState<boolean>(false)

  return (

    *<Container data-cy='container' onClick={() => setIsExpanded(!isExpanded)} style={isExpanded ? { maxWidth: 635 } : { maxWidth: 320 }}>*

        {isExpanded && (
          <>
            <Row style={{ marginTop: 16 }}>
              <Col>
Ementa
</Col>
            </Row>
            <Row style={{ marginTop: 16 }}>
              <Col >

                  {material.resume}

              </Col>
            </Row>
            <Row style={{ marginTop: 16 }}>
              <Col style={{ textAlign: 'center' }}>
                *<Link data-cy='toDetail' to={'/detail'} >Ver material completo</Link>*
              </Col>
            </Row>
          </>

        )}
    </Container>

Test:

describe('Material Card', () => {

  beforeEach(() => {
    cy.mount(<MaterialCard material={material} />)
  })

  it('should expand when clicked', () => {

    cy.get('[data-cy=container]').click()
    cy.get('[data-cy=toDetail]').should('have.text', 'Ver material completo')
  })

})

Error:

The following error originated from your application code, not from Cypress.

Invariant failed

When Cypress detects uncaught errors originating from your application it will automatically fail the current test.


问:
Fab is not working show Clicking Runtime Error
Fab is not working show Clicking Runtime Error. every time when i click on it it show runtime error. If anyone identify problem please comment.

```<code>datas.removeEventListener(_datas_child_listener);
_changeActivityFont("en_light");
_NavStatusBarColor("#4CAF50", "#FFFFFF");
_DARK_ICONS();
_FabColourchange("#800000");
View cv = getLayoutInflater().inflate(R.layout.custom_fabs_view, null);

linFab1 = (LinearLayout)cv.findViewById(R.id.lin1);
linFab2 = (LinearLayout)cv.findViewById(R.id.lin2);
/*linFab3 = (LinearLayout)cv.findViewById(R.id.lin3);*/

textFab1 = (TextView)cv.findViewById(R.id.textview1);
textFab2 = (TextView)cv.findViewById(R.id.textview2);
/*textFab3 = (TextView)cv.findViewById(R.id.textview3);*/

imgFab1 = (ImageView)cv.findViewById(R.id.imageview1);
imgFab2 = (ImageView)cv.findViewById(R.id.imageview2);
/*imgFab3 = (ImageView)cv.findViewById(R.id.imageview3);*/

final LinearLayout l1 = (LinearLayout)cv.findViewById(R.id.linear1);

_removeView(l1);

((ViewGroup)_fab.getParent()).addView(l1);
_setup(textFab1, "#2196F3");
_setup(textFab2, "#00BCD4");
/*_setup(textFab3, "#4CAF50");*/

_setup(imgFab1, "#2196F3");
_setup(imgFab2, "#00BCD4");
/*_setup(imgFab3, "#4CAF50");*/
textFab1.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View v) {

  intent.setClass(getApplicationContext(), AddActivity.class);
  startActivity(intent);

 }
});

imgFab1.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View v) {

  intent.setClass(getApplicationContext(), AddActivity.class);
  startActivity(intent);
 }
});
textFab2.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View v) {

  intent.setClass(getApplicationContext(), HomeActivity.class);
  startActivity(intent);

 }
});

imgFab2.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View v) {

  intent.setClass(getApplicationContext(), HomeActivity.class);
  startActivity(intent);

 }
});
/*textFab3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showMessage("Add Text clicked");
}
});

imgFab3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showMessage("Add Text clicked");
}
});*/
linFab1.setTranslationY(getDip(50));
linFab1.setAlpha(0);
linFab2.setTranslationY(getDip(50));
linFab2.setAlpha(0);
/*linFab3.setTranslationY(getDip(50));
linFab3.setAlpha(0);*/
data_path = FirebaseAuth.getInstance().getCurrentUser().getUid();
datas = _firebase.getReference(data_path);
datas.addChildEventListener(_datas_child_listener);
colorList.add("#66BFFB");
colorList.add("#F3779C");
colorList.add("#F2BC64");
colorList.add("#76C74E");
colorList.add("#bb86fc");
colorList.add("#0057E3");
colorList.add("#502ADB");
colorList.add("#2AACDB");
colorList.add("#1C34E8");
colorList.add("#BDE300");
edittext1.setVisibility(View.GONE);
edittext1.setBackground(new GradientDrawable() { public GradientDrawable getIns(int a, int b, int c, int d) { this.setCornerRadius(a); this.setStroke(b, c); this.setColor(d); return this; } }.getIns((int)20, (int)2, 0xFF37474F, Color.TRANSPARENT));
</code>```

Fab is not working show Clicking Runtime Error. every time when i click on it it show runtime error. If anyone identify problem please comment.My problem is that when I open the app, the fab button in the first tab is showing runtime error

Body:
Fab is not working show Clicking Runtime Error. every time when i click on it it show runtime error. If anyone identify problem please comment.

datas.removeEventListener(_datas_child_listener);
_changeActivityFont("en_light");
_NavStatusBarColor("#4CAF50", "#FFFFFF");
_DARK_ICONS();
_FabColourchange("#800000");
View cv = getLayoutInflater().inflate(R.layout.custom_fabs_view, null);

linFab1 = (LinearLayout)cv.findViewById(R.id.lin1);
linFab2 = (LinearLayout)cv.findViewById(R.id.lin2);
/*linFab3 = (LinearLayout)cv.findViewById(R.id.lin3);*/

textFab1 = (TextView)cv.findViewById(R.id.textview1);
textFab2 = (TextView)cv.findViewById(R.id.textview2);
/*textFab3 = (TextView)cv.findViewById(R.id.textview3);*/

imgFab1 = (ImageView)cv.findViewById(R.id.imageview1);
imgFab2 = (ImageView)cv.findViewById(R.id.imageview2);
/*imgFab3 = (ImageView)cv.findViewById(R.id.imageview3);*/

final LinearLayout l1 = (LinearLayout)cv.findViewById(R.id.linear1);

_removeView(l1);

((ViewGroup)_fab.getParent()).addView(l1);
_setup(textFab1, "#2196F3");
_setup(textFab2, "#00BCD4");
/*_setup(textFab3, "#4CAF50");*/

_setup(imgFab1, "#2196F3");
_setup(imgFab2, "#00BCD4");
/*_setup(imgFab3, "#4CAF50");*/
textFab1.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View v) {

  intent.setClass(getApplicationContext(), AddActivity.class);
  startActivity(intent);

 }
});

imgFab1.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View v) {

  intent.setClass(getApplicationContext(), AddActivity.class);
  startActivity(intent);
 }
});
textFab2.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View v) {

  intent.setClass(getApplicationContext(), HomeActivity.class);
  startActivity(intent);

 }
});

imgFab2.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View v) {

  intent.setClass(getApplicationContext(), HomeActivity.class);
  startActivity(intent);

 }
});
/*textFab3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showMessage("Add Text clicked");
}
});

imgFab3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showMessage("Add Text clicked");
}
});*/
linFab1.setTranslationY(getDip(50));
linFab1.setAlpha(0);
linFab2.setTranslationY(getDip(50));
linFab2.setAlpha(0);
/*linFab3.setTranslationY(getDip(50));
linFab3.setAlpha(0);*/
data_path = FirebaseAuth.getInstance().getCurrentUser().getUid();
datas = _firebase.getReference(data_path);
datas.addChildEventListener(_datas_child_listener);
colorList.add("#66BFFB");
colorList.add("#F3779C");
colorList.add("#F2BC64");
colorList.add("#76C74E");
colorList.add("#bb86fc");
colorList.add("#0057E3");
colorList.add("#502ADB");
colorList.add("#2AACDB");
colorList.add("#1C34E8");
colorList.add("#BDE300");
edittext1.setVisibility(View.GONE);
edittext1.setBackground(new GradientDrawable() { public GradientDrawable getIns(int a, int b, int c, int d) { this.setCornerRadius(a); this.setStroke(b, c); this.setColor(d); return this; } }.getIns((int)20, (int)2, 0xFF37474F, Color.TRANSPARENT));

Fab is not working show Clicking Runtime Error. every time when i click on it it show runtime error. If anyone identify problem please comment.My problem is that when I open the app, the fab button in the first tab is showing runtime error


问:
Why is Chrome Console returning a stringifyed object?
I've never seen this before and there's nothing on the internet that I could find.

I have a submit button and when I click it it's accessing the Clarifai API and returning the output which is an object, but instead of it being a normal object that is organized in chrome console, it's a stringifyed object.

This is fine and all, just makes it harder to find the path I need to get the info I need.

Here is my code:

```<code>onButtonSubmit = () => {
  console.log('click');
    const USER_ID = 'realvicandy';
    const PAT = '33c27a0a3f2547f789bc36bbdec57dcc';
    const APP_ID = 'my-first-application';
    // Change these to whatever model and image URL you want to use
    const MODEL_ID = 'color-recognition';
    const MODEL_VERSION_ID = 'dd9458324b4b45c2be1a7ba84d27cd04';
    const IMAGE_URL = 'https://samples.clarifai.com/metro-north.jpg';

    const raw = JSON.stringify({
        "user_app_id": {
            "user_id": USER_ID,
            "app_id": APP_ID
        },
        "inputs": [
            {
                "data": {
                    "image": {
                        "url": IMAGE_URL
                    }
                }
            }
        ]
    });

    const requestOptions = {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Authorization': 'Key ' + PAT
        },
        body: raw
    };

    // NOTE: MODEL_VERSION_ID is optional, you can also call prediction with the MODEL_ID only
    // https://api.clarifai.com/v2/models/{YOUR_MODEL_ID}/outputs
    // this will default to the latest version_id

    fetch("https://api.clarifai.com/v2/models/" + 'color-recognition' + "/versions/" + MODEL_VERSION_ID + "/outputs", requestOptions)
        .then(response => response.text())
        .then(result => console.log(result))
        .catch(error => console.log('error', error));
</code>```

Here is the object in chrome:

```<code>{"status":{"code":10000,"description":"Ok","req_id":"368a54d959cc2cd826ad08d7caa28fac"},"outputs":[{"id":"91e04fc631014d8b804a88859a62ee7b","status":{"code":10000,"description":"Ok"},"created_at":"2022-12-07T18:00:03.033519292Z","model":{"id":"color-recognition","name":"color","created_at":"2016-05-11T18:05:45.924367Z","modified_at":"2022-11-01T19:45:15.089623Z","app_id":"main","output_info":{"message":"Show output_info with: GET /models/{model_id}/output_info"},"model_version":{"id":"dd9458324b4b45c2be1a7ba84d27cd04","created_at":"2016-07-13T01:19:12.147644Z","status":{"code":21100,"description":"Model is trained and ready"},"visibility":{"gettable":50},"app_id":"main","user_id":"clarifai","metadata":{},"output_info":{"message":"Show output_info with: GET /models/{model_id}/output_info"},"input_info":{},"train_info":{},"import_info":{}},"user_id":"clarifai","input_info":{},"train_info":{},"model_type_id":"image-color-recognizer","visibility":{"gettable":50},"metadata":null,"presets":{},"languages":[],"import_info":{},"workflow_recommended":false},"input":{"id":"845ed7176680401cbcefe9e4dd70a19b","data":{"image":{"url":"https://samples.clarifai.com/metro-north.jpg"}}},"data":{"colors":[{"raw_hex":"#513f2c","w3c":{"hex":"#696969","name":"DimGray"},"value":0.14725},{"raw_hex":"#7298e2","w3c":{"hex":"#6495ed","name":"CornflowerBlue"},"value":0.31575},{"raw_hex":"#1e181b","w3c":{"hex":"#000000","name":"Black"},"value":0.20175},{"raw_hex":"#8f714b","w3c":{"hex":"#d2b48c","name":"Tan"},"value":0.1125},{"raw_hex":"#d2c275","w3c":{"hex":"#bdb76b","name":"DarkKhaki"},"value":0.017},{"raw_hex":"#141b3c","w3c":{"hex":"#000000","name":"Black"},"value":0.12},{"raw_hex":"#404b84","w3c":{"hex":"#483d8b","name":"DarkSlateBlue"},"value":0.0705},{"raw_hex":"#e5e1cc","w3c":{"hex":"#faebd7","name":"AntiqueWhite"},"value":0.01525}]}}]}
</code>```

Expect result: return an organized object in chrome console.

Actual Result: return a stringifyed object in chrome console.

Body:
I've never seen this before and there's nothing on the internet that I could find.

I have a submit button and when I click it it's accessing the Clarifai API and returning the output which is an object, but instead of it being a normal object that is organized in chrome console, it's a stringifyed object.

This is fine and all, just makes it harder to find the path I need to get the info I need.

Here is my code:

onButtonSubmit = () => {
  console.log('click');
    const USER_ID = 'realvicandy';
    const PAT = '33c27a0a3f2547f789bc36bbdec57dcc';
    const APP_ID = 'my-first-application';
    // Change these to whatever model and image URL you want to use
    const MODEL_ID = 'color-recognition';
    const MODEL_VERSION_ID = 'dd9458324b4b45c2be1a7ba84d27cd04';
    const IMAGE_URL = 'https://samples.clarifai.com/metro-north.jpg';

    const raw = JSON.stringify({
        "user_app_id": {
            "user_id": USER_ID,
            "app_id": APP_ID
        },
        "inputs": [
            {
                "data": {
                    "image": {
                        "url": IMAGE_URL
                    }
                }
            }
        ]
    });

    const requestOptions = {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Authorization': 'Key ' + PAT
        },
        body: raw
    };

    // NOTE: MODEL_VERSION_ID is optional, you can also call prediction with the MODEL_ID only
    // https://api.clarifai.com/v2/models/{YOUR_MODEL_ID}/outputs
    // this will default to the latest version_id

    fetch("https://api.clarifai.com/v2/models/" + 'color-recognition' + "/versions/" + MODEL_VERSION_ID + "/outputs", requestOptions)
        .then(response => response.text())
        .then(result => console.log(result))
        .catch(error => console.log('error', error));

Here is the object in chrome:

{"status":{"code":10000,"description":"Ok","req_id":"368a54d959cc2cd826ad08d7caa28fac"},"outputs":[{"id":"91e04fc631014d8b804a88859a62ee7b","status":{"code":10000,"description":"Ok"},"created_at":"2022-12-07T18:00:03.033519292Z","model":{"id":"color-recognition","name":"color","created_at":"2016-05-11T18:05:45.924367Z","modified_at":"2022-11-01T19:45:15.089623Z","app_id":"main","output_info":{"message":"Show output_info with: GET /models/{model_id}/output_info"},"model_version":{"id":"dd9458324b4b45c2be1a7ba84d27cd04","created_at":"2016-07-13T01:19:12.147644Z","status":{"code":21100,"description":"Model is trained and ready"},"visibility":{"gettable":50},"app_id":"main","user_id":"clarifai","metadata":{},"output_info":{"message":"Show output_info with: GET /models/{model_id}/output_info"},"input_info":{},"train_info":{},"import_info":{}},"user_id":"clarifai","input_info":{},"train_info":{},"model_type_id":"image-color-recognizer","visibility":{"gettable":50},"metadata":null,"presets":{},"languages":[],"import_info":{},"workflow_recommended":false},"input":{"id":"845ed7176680401cbcefe9e4dd70a19b","data":{"image":{"url":"https://samples.clarifai.com/metro-north.jpg"}}},"data":{"colors":[{"raw_hex":"#513f2c","w3c":{"hex":"#696969","name":"DimGray"},"value":0.14725},{"raw_hex":"#7298e2","w3c":{"hex":"#6495ed","name":"CornflowerBlue"},"value":0.31575},{"raw_hex":"#1e181b","w3c":{"hex":"#000000","name":"Black"},"value":0.20175},{"raw_hex":"#8f714b","w3c":{"hex":"#d2b48c","name":"Tan"},"value":0.1125},{"raw_hex":"#d2c275","w3c":{"hex":"#bdb76b","name":"DarkKhaki"},"value":0.017},{"raw_hex":"#141b3c","w3c":{"hex":"#000000","name":"Black"},"value":0.12},{"raw_hex":"#404b84","w3c":{"hex":"#483d8b","name":"DarkSlateBlue"},"value":0.0705},{"raw_hex":"#e5e1cc","w3c":{"hex":"#faebd7","name":"AntiqueWhite"},"value":0.01525}]}}]}

Expect result: return an organized object in chrome console.

Actual Result: return a stringifyed object in chrome console.