问:
Problem with installing magenta in Visual Studio
I have a problem with installing magenta via pip install.

I have no idea how to continue. Do you have a solution for this?  What we've found out is, that this issue is only appearing on windows but working on mac OS.  my python version is 3.9.13  Thank you very much!

Here is what I get as an error:

```<code>Building wheels for collected packages: llvmlite
  Building wheel for llvmlite (setup.py): started
  Building wheel for llvmlite (setup.py): finished with status 'error'
  error: subprocess-exited-with-error

  × python setup.py bdist_wheel did not run successfully.
  │ exit code: 1
  ╰─> [40 lines of output]
      running bdist_wheel
      C:\Users\Dell\anaconda3\python.exe C:\Users\Dell\AppData\Local\Temp\pip-install-navixrdn\llvmlite_5570561b56024e2f900181b3a6a221c1\ffi\build.py
      Trying generator 'Visual Studio 14 2015 Win64'
      -- Selecting Windows SDK version  to target Windows 10.0.19044.
      CMake Error at CMakeLists.txt:3 (project):
        Failed to run MSBuild command:

          MSBuild.exe

        to get the value of VCTargetsPath:

          Das System kann die angegebene Datei nicht finden

      -- Configuring incomplete, errors occurred!
      See also "C:/Users/Dell/AppData/Local/Temp/tmpuyuidx7g/CMakeFiles/CMakeOutput.log".
      Trying generator 'Visual Studio 15 2017 Win64'
      CMake Error at CMakeLists.txt:3 (project):
        Generator

          Visual Studio 15 2017 Win64

        could not find any instance of Visual Studio.

      -- Configuring incomplete, errors occurred!
      See also "C:/Users/Dell/AppData/Local/Temp/tmpemzf5k9q/CMakeFiles/CMakeOutput.log".
      Traceback (most recent call last):
        File "C:\Users\Dell\AppData\Local\Temp\pip-install-navixrdn\llvmlite_5570561b56024e2f900181b3a6a221c1\ffi\build.py", line 192, in <module>
          main()
        File "C:\Users\Dell\AppData\Local\Temp\pip-install-navixrdn\llvmlite_5570561b56024e2f900181b3a6a221c1\ffi\build.py", line 180, in main
          main_win32()
        File "C:\Users\Dell\AppData\Local\Temp\pip-install-navixrdn\llvmlite_5570561b56024e2f900181b3a6a221c1\ffi\build.py", line 89, in main_win32
          generator = find_win32_generator()
        File "C:\Users\Dell\AppData\Local\Temp\pip-install-navixrdn\llvmlite_5570561b56024e2f900181b3a6a221c1\ffi\build.py", line 85, in find_win32_generator
          raise RuntimeError("No compatible cmake generator installed on this machine")
      RuntimeError: No compatible cmake generator installed on this machine
      error: command 'C:\\Users\\Dell\\anaconda3\\python.exe' failed with exit code 1
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
  ERROR: Failed building wheel for llvmlite
  Running setup.py clean for llvmlite
Failed to build llvmlite
Installing collected packages: llvmlite, keras, flatbuffers, tensorflow-estimator, sox, scipy, protobuf, promise, numba, keras-preprocessing, importlib_resources, imageio, etils, absl-py, tf-slim, tensorflow-probability, sk-video, resampy, mir-eval, matplotlib, googleapis-common-protos, dm-sonnet, tensorflow-metadata, librosa, tensorflow-datasets, tensorboard, note-seq, tensorflow, magenta
  Attempting uninstall: llvmlite
    Found existing installation: llvmlite 0.39.1
    Uninstalling llvmlite-0.39.1:
      Successfully uninstalled llvmlite-0.39.1
  Running setup.py install for llvmlite: started
  Running setup.py install for llvmlite: finished with status 'error'
  error: subprocess-exited-with-error

  × Running setup.py install for llvmlite did not run successfully.
  │ exit code: 1
  ╰─> [45 lines of output]
      running install
      C:\Users\Dell\anaconda3\lib\site-packages\setuptools\command\install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.
        warnings.warn(
      running build
      got version from file C:\Users\Dell\AppData\Local\Temp\pip-install-navixrdn\llvmlite_5570561b56024e2f900181b3a6a221c1\llvmlite/_version.py {'version': '0.32.1', 'full': 'aa11b129c0b55973067422397821ae6d44fa5e70'}
      running build_ext
      C:\Users\Dell\anaconda3\python.exe C:\Users\Dell\AppData\Local\Temp\pip-install-navixrdn\llvmlite_5570561b56024e2f900181b3a6a221c1\ffi\build.py
      Trying generator 'Visual Studio 14 2015 Win64'
      -- Selecting Windows SDK version  to target Windows 10.0.19044.
      CMake Error at CMakeLists.txt:3 (project):
        Failed to run MSBuild command:

          MSBuild.exe

        to get the value of VCTargetsPath:

          Das System kann die angegebene Datei nicht finden
       Rolling back uninstall of llvmlite

      -- Configuring incomplete, errors occurred!
      See also "C:/Users/Dell/AppData/Local/Temp/tmpja61gmu1/CMakeFiles/CMakeOutput.log".
      Trying generator 'Visual Studio 15 2017 Win64'
      CMake Error at CMakeLists.txt:3 (project):
        Generator

          Visual Studio 15 2017 Win64

        could not find any instance of Visual Studio.

      -- Configuring incomplete, errors occurred!
      See also "C:/Users/Dell/AppData/Local/Temp/tmplskfqy1q/CMakeFiles/CMakeOutput.log".
      Traceback (most recent call last):
        File "C:\Users\Dell\AppData\Local\Temp\pip-install-navixrdn\llvmlite_5570561b56024e2f900181b3a6a221c1\ffi\build.py", line 192, in <module>
          main()
        File "C:\Users\Dell\AppData\Local\Temp\pip-install-navixrdn\llvmlite_5570561b56024e2f900181b3a6a221c1\ffi\build.py", line 180, in main
          main_win32()
        File "C:\Users\Dell\AppData\Local\Temp\pip-install-navixrdn\llvmlite_5570561b56024e2f900181b3a6a221c1\ffi\build.py", line 89, in main_win32
          generator = find_win32_generator()
        File "C:\Users\Dell\AppData\Local\Temp\pip-install-navixrdn\llvmlite_5570561b56024e2f900181b3a6a221c1\ffi\build.py", line 85, in find_win32_generator
          raise RuntimeError("No compatible cmake generator installed on this machine")
      RuntimeError: No compatible cmake generator installed on this machine
      error: command 'C:\\Users\\Dell\\anaconda3\\python.exe' failed with exit code 1
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.

  Moving to c:\users\dell\anaconda3\lib\site-packages\llvmlite-0.39.1.dist-info\
   from C:\Users\Dell\anaconda3\Lib\site-packages\~lvmlite-0.39.1.dist-info
  Moving to c:\users\dell\anaconda3\lib\site-packages\llvmlite\
   from C:\Users\Dell\anaconda3\Lib\site-packages\~lvmlite
error: legacy-install-failure

× Encountered error while trying to install package.
╰─> llvmlite

note: This is an issue with the package mentioned above, not pip.
hint: See above for output from the failure.
Backend QtAgg is interactive backend. Turning interactive mode on.
</code>```

What I already tried and didn't work:

reinstall all 3 packages

installed the newest version of Visual Studio 2022 (17.4.3)

downgrade versions of those packages

the same with cmake and wheel package

install windows sdk

test it on another device

Body:
I have a problem with installing magenta via pip install.

I have no idea how to continue. Do you have a solution for this?  What we've found out is, that this issue is only appearing on windows but working on mac OS.  my python version is 3.9.13  Thank you very much!

Here is what I get as an error:

Building wheels for collected packages: llvmlite
  Building wheel for llvmlite (setup.py): started
  Building wheel for llvmlite (setup.py): finished with status 'error'
  error: subprocess-exited-with-error

  × python setup.py bdist_wheel did not run successfully.
  │ exit code: 1
  ╰─> [40 lines of output]
      running bdist_wheel
      C:\Users\Dell\anaconda3\python.exe C:\Users\Dell\AppData\Local\Temp\pip-install-navixrdn\llvmlite_5570561b56024e2f900181b3a6a221c1\ffi\build.py
      Trying generator 'Visual Studio 14 2015 Win64'
      -- Selecting Windows SDK version  to target Windows 10.0.19044.
      CMake Error at CMakeLists.txt:3 (project):
        Failed to run MSBuild command:

          MSBuild.exe

        to get the value of VCTargetsPath:

          Das System kann die angegebene Datei nicht finden

      -- Configuring incomplete, errors occurred!
      See also "C:/Users/Dell/AppData/Local/Temp/tmpuyuidx7g/CMakeFiles/CMakeOutput.log".
      Trying generator 'Visual Studio 15 2017 Win64'
      CMake Error at CMakeLists.txt:3 (project):
        Generator

          Visual Studio 15 2017 Win64

        could not find any instance of Visual Studio.

      -- Configuring incomplete, errors occurred!
      See also "C:/Users/Dell/AppData/Local/Temp/tmpemzf5k9q/CMakeFiles/CMakeOutput.log".
      Traceback (most recent call last):
        File "C:\Users\Dell\AppData\Local\Temp\pip-install-navixrdn\llvmlite_5570561b56024e2f900181b3a6a221c1\ffi\build.py", line 192, in <module>
          main()
        File "C:\Users\Dell\AppData\Local\Temp\pip-install-navixrdn\llvmlite_5570561b56024e2f900181b3a6a221c1\ffi\build.py", line 180, in main
          main_win32()
        File "C:\Users\Dell\AppData\Local\Temp\pip-install-navixrdn\llvmlite_5570561b56024e2f900181b3a6a221c1\ffi\build.py", line 89, in main_win32
          generator = find_win32_generator()
        File "C:\Users\Dell\AppData\Local\Temp\pip-install-navixrdn\llvmlite_5570561b56024e2f900181b3a6a221c1\ffi\build.py", line 85, in find_win32_generator
          raise RuntimeError("No compatible cmake generator installed on this machine")
      RuntimeError: No compatible cmake generator installed on this machine
      error: command 'C:\\Users\\Dell\\anaconda3\\python.exe' failed with exit code 1
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
  ERROR: Failed building wheel for llvmlite
  Running setup.py clean for llvmlite
Failed to build llvmlite
Installing collected packages: llvmlite, keras, flatbuffers, tensorflow-estimator, sox, scipy, protobuf, promise, numba, keras-preprocessing, importlib_resources, imageio, etils, absl-py, tf-slim, tensorflow-probability, sk-video, resampy, mir-eval, matplotlib, googleapis-common-protos, dm-sonnet, tensorflow-metadata, librosa, tensorflow-datasets, tensorboard, note-seq, tensorflow, magenta
  Attempting uninstall: llvmlite
    Found existing installation: llvmlite 0.39.1
    Uninstalling llvmlite-0.39.1:
      Successfully uninstalled llvmlite-0.39.1
  Running setup.py install for llvmlite: started
  Running setup.py install for llvmlite: finished with status 'error'
  error: subprocess-exited-with-error

  × Running setup.py install for llvmlite did not run successfully.
  │ exit code: 1
  ╰─> [45 lines of output]
      running install
      C:\Users\Dell\anaconda3\lib\site-packages\setuptools\command\install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.
        warnings.warn(
      running build
      got version from file C:\Users\Dell\AppData\Local\Temp\pip-install-navixrdn\llvmlite_5570561b56024e2f900181b3a6a221c1\llvmlite/_version.py {'version': '0.32.1', 'full': 'aa11b129c0b55973067422397821ae6d44fa5e70'}
      running build_ext
      C:\Users\Dell\anaconda3\python.exe C:\Users\Dell\AppData\Local\Temp\pip-install-navixrdn\llvmlite_5570561b56024e2f900181b3a6a221c1\ffi\build.py
      Trying generator 'Visual Studio 14 2015 Win64'
      -- Selecting Windows SDK version  to target Windows 10.0.19044.
      CMake Error at CMakeLists.txt:3 (project):
        Failed to run MSBuild command:

          MSBuild.exe

        to get the value of VCTargetsPath:

          Das System kann die angegebene Datei nicht finden
       Rolling back uninstall of llvmlite

      -- Configuring incomplete, errors occurred!
      See also "C:/Users/Dell/AppData/Local/Temp/tmpja61gmu1/CMakeFiles/CMakeOutput.log".
      Trying generator 'Visual Studio 15 2017 Win64'
      CMake Error at CMakeLists.txt:3 (project):
        Generator

          Visual Studio 15 2017 Win64

        could not find any instance of Visual Studio.

      -- Configuring incomplete, errors occurred!
      See also "C:/Users/Dell/AppData/Local/Temp/tmplskfqy1q/CMakeFiles/CMakeOutput.log".
      Traceback (most recent call last):
        File "C:\Users\Dell\AppData\Local\Temp\pip-install-navixrdn\llvmlite_5570561b56024e2f900181b3a6a221c1\ffi\build.py", line 192, in <module>
          main()
        File "C:\Users\Dell\AppData\Local\Temp\pip-install-navixrdn\llvmlite_5570561b56024e2f900181b3a6a221c1\ffi\build.py", line 180, in main
          main_win32()
        File "C:\Users\Dell\AppData\Local\Temp\pip-install-navixrdn\llvmlite_5570561b56024e2f900181b3a6a221c1\ffi\build.py", line 89, in main_win32
          generator = find_win32_generator()
        File "C:\Users\Dell\AppData\Local\Temp\pip-install-navixrdn\llvmlite_5570561b56024e2f900181b3a6a221c1\ffi\build.py", line 85, in find_win32_generator
          raise RuntimeError("No compatible cmake generator installed on this machine")
      RuntimeError: No compatible cmake generator installed on this machine
      error: command 'C:\\Users\\Dell\\anaconda3\\python.exe' failed with exit code 1
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.

  Moving to c:\users\dell\anaconda3\lib\site-packages\llvmlite-0.39.1.dist-info\
   from C:\Users\Dell\anaconda3\Lib\site-packages\~lvmlite-0.39.1.dist-info
  Moving to c:\users\dell\anaconda3\lib\site-packages\llvmlite\
   from C:\Users\Dell\anaconda3\Lib\site-packages\~lvmlite
error: legacy-install-failure

× Encountered error while trying to install package.
╰─> llvmlite

note: This is an issue with the package mentioned above, not pip.
hint: See above for output from the failure.
Backend QtAgg is interactive backend. Turning interactive mode on.

What I already tried and didn't work:

reinstall all 3 packages

installed the newest version of Visual Studio 2022 (17.4.3)

downgrade versions of those packages

the same with cmake and wheel package

install windows sdk

test it on another device


来源: stackexchange

问:
Is there a way to skip errors in r shiny app
I have an app that needs to scrape data from the internet but sometimes when the web page is down it returns an HTTP error and interrupts the app.

Is there a way to ignore errors when running the app?

ContentLicense: CC BY-SA 4.0


问:
Slash Command won't show up in bot commands list
I have set the right permissions and scope when inviting bot to my server. The commands don't show up in the list. I have waited 24 hours to let it register, same result.

https://ibb.co/HGJYk67

```<code>import discord
from discord.ext import commands

client = commands.Bot(command_prefix='/', intents=discord.Intents.all())

@client.command(name="greet", description="greets the user")
async def greet(ctx):
    await client.tree.sync()
    await ctx.send("Hello!")

@client.command(name="preet", description="preets the user")
async def preet(ctx):
    await client.tree.sync()
    await ctx.send("Hello!")

client.run('bot token')
</code>```

Body:
I have set the right permissions and scope when inviting bot to my server. The commands don't show up in the list. I have waited 24 hours to let it register, same result.

https://ibb.co/HGJYk67

import discord
from discord.ext import commands

client = commands.Bot(command_prefix='/', intents=discord.Intents.all())

@client.command(name="greet", description="greets the user")
async def greet(ctx):
    await client.tree.sync()
    await ctx.send("Hello!")

@client.command(name="preet", description="preets the user")
async def preet(ctx):
    await client.tree.sync()
    await ctx.send("Hello!")

client.run('bot token')


问:
How to replace background image on scroll with animation or parallax effect
I am trying to replace background image on scroll. I have used react-parallax but it is adding effect in another component not replacing the background image. I want to replace the bg image added by a styled component

```<code>  const ImgContainer = styled("div")({
    width: "100%",
    // height: "100vh",
    backgroundImage: `url(${ElHogarBg})`,
    backgroundSize: "cover",
    backgroundPosition: "center",
    backgroundRepeat: "no-repeat",
    position: "relative",
    display: "flex",
    justifyContent: "center",
    alignItems: "center",
    flexDirection: "column",
    zIndex: "1",
  });
</code>```

This is my styled component. I want to replace my image with parallax effect on scroll.

Body:
I am trying to replace background image on scroll. I have used react-parallax but it is adding effect in another component not replacing the background image. I want to replace the bg image added by a styled component

  const ImgContainer = styled("div")({
    width: "100%",
    // height: "100vh",
    backgroundImage: `url(${ElHogarBg})`,
    backgroundSize: "cover",
    backgroundPosition: "center",
    backgroundRepeat: "no-repeat",
    position: "relative",
    display: "flex",
    justifyContent: "center",
    alignItems: "center",
    flexDirection: "column",
    zIndex: "1",
  });

This is my styled component. I want to replace my image with parallax effect on scroll.


问:
NetSuite Restlet Issue: 400 Error but successful login according to audit trail
I'm having an odd issue setting up a NetSuite Restlet. I'm getting a 400 Client Error: Bad Request for url error, but when I check the Login Audit Trail in NetSuite for more info, I'm seeing a successful login.

Has anyone encountered this issue before?

Edit - Below is the endpoint I'm hitting. It's a GET request so no payload.

https://[ACCOUNT_SANDBOX_ID].restlets.api.netsuite.com/app/site/hosting/restlet.nl?script=1346&deploy=1


问:
Is it possible to make an image link to an external link in Apple News Format?
I'm new to Apple News Format and was asked to place a banner on our Apple News articles that links to our external website on a browser.

But I'm not seeing a way to do so. I'm using the Image component, which supports additions for ComponentLinks, which are for internal links only.

Does anyone know of a workaround? It seems like only Text components support external links (via LinkAdditions), so I'm not sure if it's just not feasible with an image or if I'm missing something.


问:
gltf loader extremly slow with light model in three.js
I am currently trying to import a really light gltf model (just one box and one punctual light) to my scene in three.js but it takes more than a second (just the loading process) and i was wondering if this is normal or what is going on because it shouldn't take that long.
The model is 3kb and it takes about 1s.
Everything works but it's just slow.</p>
```<code>const loader = new GLTFLoader()
function first_load() {
    console.log("gltf", this.alles.clock.getElapsedTime())
    loader.load("/models/1/firstload.gltf", (gltf)=> {
        console.log("gltf", this.alles.clock.getElapsedTime())
    }
    )
}
</code>```

Body:
I am currently trying to import a really light gltf model (just one box and one punctual light) to my scene in three.js but it takes more than a second (just the loading process) and i was wondering if this is normal or what is going on because it shouldn't take that long.
The model is 3kb and it takes about 1s.
Everything works but it's just slow.

const loader = new GLTFLoader()
function first_load() {
    console.log("gltf", this.alles.clock.getElapsedTime())
    loader.load("/models/1/firstload.gltf", (gltf)=> {
        console.log("gltf", this.alles.clock.getElapsedTime())
    }
    )
}


问:
Internet is not available, the client will not appear
I have such a problem. when the Internet is I receive a name of the client. Then I turn off the Internet and restart the program. And there appeared the name of the client. I don't have internet as it appeared. I need when the internet is not available, the client will not appear</p>
```<code> StreamBuilder<DocumentSnapshot>(
          stream: FirebaseFirestore.instance
              .collection('users')
              .doc('crystal')
              .snapshots(),
          builder:
              (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
            if (snapshot.hasError) {
              return const Center(
                child: Text(
                  "No connection",
                  style: TextStyle(
                    color: Colors.black,
                    fontSize: 40.0,
                  ),
                ),
              );
            }
            if (snapshot.hasData && !snapshot.data!.exists) {
              return const Center(
                child: Text(
                  "0...",
                  style: TextStyle(
                    color: Colors.black,
                    fontSize: 40.0,
                  ),
                ),
              );
            }
            if (snapshot.hasData) {
              final snap = snapshot.data!;
              ItemUserModel model =
                  ItemUserModel.fromJson(snap.data() as Map<String, dynamic>);

              return Text(model.name);}
 return const Center(child: CircularProgressIndicator());
          }),

class ItemUserModel {
  late String title;
  late String name;

  ItemUserModel({
    required this.title,
    required this.name,
  });

  ItemUserModel.fromJson(Map<String, dynamic> json) {
    title = json['title'];
    text = json['name'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['title'] = title;
    data['name'] = name;
    return data;
  }
}
</code>```

Body:
I have such a problem. when the Internet is I receive a name of the client. Then I turn off the Internet and restart the program. And there appeared the name of the client. I don't have internet as it appeared. I need when the internet is not available, the client will not appear

 StreamBuilder<DocumentSnapshot>(
          stream: FirebaseFirestore.instance
              .collection('users')
              .doc('crystal')
              .snapshots(),
          builder:
              (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
            if (snapshot.hasError) {
              return const Center(
                child: Text(
                  "No connection",
                  style: TextStyle(
                    color: Colors.black,
                    fontSize: 40.0,
                  ),
                ),
              );
            }
            if (snapshot.hasData && !snapshot.data!.exists) {
              return const Center(
                child: Text(
                  "0...",
                  style: TextStyle(
                    color: Colors.black,
                    fontSize: 40.0,
                  ),
                ),
              );
            }
            if (snapshot.hasData) {
              final snap = snapshot.data!;
              ItemUserModel model =
                  ItemUserModel.fromJson(snap.data() as Map<String, dynamic>);

              return Text(model.name);}
 return const Center(child: CircularProgressIndicator());
          }),

class ItemUserModel {
  late String title;
  late String name;

  ItemUserModel({
    required this.title,
    required this.name,
  });

  ItemUserModel.fromJson(Map<String, dynamic> json) {
    title = json['title'];
    text = json['name'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['title'] = title;
    data['name'] = name;
    return data;
  }
}


问:
Cannot find or open the PBD file
Working on an ASP.NET C# web application project in Visual Studio 2022. I've been having the infamous "Breakpoint will not currently be hit. No symbols have been loaded for this document" error when trying to debug.

I've poured over questions here looking for solutions. I am definitely running the debug configuration, and just found out that, in the Module window, absolutely nothing had loaded.

I found a solution for getting some to load by switching the browser I was debugging in (Google Chrome -> Edge). But, now that I have modules in the window, most have "Cannot find or open the PDB file" under the "Symbol Status" column, and my breakpoints are still encountering the same error.

I have been at this for a day or two now with no solutions. I'm not sure where to go from here. Any advice, solutions?

Diagnosed that no symbols had loaded for my project, and expected breakpoints to start working once they had. Symbols have still not loaded properly and breakpoints are still broken.

Title: Cannot find or open the PBD file


问:
LiveData list of objects from Room query not showing up in the view
I'm currently trying to use a SQLite database via the Room library on my Jetpack Compose project to create a view that does the following:

display a list of entries from the database that are filtered to only records with the current user's ID

allow the user to create new records and insert those into the database

update the list to include any newly created records

My issue is that I cannot get the list to show when the view is loaded even though the database has data in it and I am able to insert records into it successfully. I've seen a lot of examples that show how do this if you are just loading all the records, but I cannot seem to figure out how to do this if I only want the list to include records with the user's ID.

After following a few of tutorials and posts it is my understanding that I should have the following:

A DAO, which returns a LiveData object

A repository which calls the DAO method and returns the same LiveData object

A viewholder  class, which will contain two objects: one private MutableLiveData variable and one public LiveData variable (this one is the one we observe from the view)

My view, a Composable function, that observes the changes

However, with this setup, the list still will not load and I do not see any calls to the database to load the list from the "App Inspection" tab. The code is as follows:

TrainingSet.kt

```<code>@Entity(tableName = "training_sets")
data class TrainingSet (
    @PrimaryKey() val id: String,
    @ColumnInfo(name = "user_id") val userId: String,
</code>```

TrainingSetDao.kt

```<code>@Dao
interface TrainingSetDao {
    @Insert(onConflict = OnConflictStrategy.ABORT)
    suspend fun insert(trainingSet: TrainingSet)

    @Query("SELECT * FROM training_sets WHERE user_id = :userId")
    fun getUserTrainingSets(userId: String): LiveData<List<TrainingSet>>
}
</code>```

TrainingSetRepository.kt

```<code>class TrainingSetRepository(private val trainingSetDao: TrainingSetDao) {
    fun getUserTrainingSets(userId: String): LiveData<List<TrainingSet>> {
        return trainingSetDao.getUserTrainingSets(userId)
    }

    suspend fun insert(trainingSet: TrainingSet) {
        trainingSetDao.insert(trainingSet)
    }
}
</code>```

TrainingSetsViewModel.kt

```<code>class TrainingSetsViewModel(application: Application): ViewModel() {
    private val repository: TrainingSetRepository

    private val _userTrainingSets = MutableLiveData<List<TrainingSet>>(emptyList())
    val userTrainingSets: LiveData<List<TrainingSet>> get() = _userTrainingSets

    init {
        val trainingSetDao = AppDatabase.getDatabase(application.applicationContext).getTrainingSetDao()

        repository = TrainingSetRepository(trainingSetDao)
    }

    fun getUserTrainingSets(userId: String) {
        viewModelScope.launch {
            _userTrainingSets.value = repository.getUserTrainingSets(userId).value
        }
    }

    fun insertTrainingSet(trainingSet: TrainingSet) {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                repository.insert(trainingSet)
            } catch (err: Exception) {
                println("Error!!!!: ${err.message}")
            }
        }
    }
}
</code>```

RecordScreen.kt

```<code>@Composable
fun RecordScreen(navController: NavController, trainingSetsViewModel: TrainingSetsViewModel) {
    // observe the list
    val trainingSets by trainingSetsViewModel.userTrainingSets.observeAsState()

    // trigger loading of the list using the userID
    // note: hardcoding this ID for now
    trainingSetsViewModel.getUserTrainingSets("20c1256d-0bdb-4241-8781-10f7353e5a3b")

    // ... some code here

    Button(onClick = {
        trainingSetsViewModel.insertTrainingSet(TrainingSet(// dummy test data here //))
    }) {
        Text(text = "Add Record")
    }

    // ... some more code here

    LazyColumn() {
        itemsIndexed(trainingSets) { key, item ->
            // ... list row components here
        }
    }
</code>```

NavGraph.kt** **(including this in case it's relevant)

```<code>@Composable
fun NavGraph(navController: NavHostController) {
    NavHost(
        navController = navController,
        startDestination = Screens.Record.route,
    ) {
        composable(route = Screens.Record.route) {
            val owner = LocalViewModelStoreOwner.current

            owner?.let {
                val trainingSetsViewModel: TrainingSetsViewModel = viewModel(
                    it,
                    "TrainingSetsViewModel",
                    MainViewModelFactory(LocalContext.current.applicationContext as Application)
                )

            // note: I attempted to load the user training sets here in case it needed to be done before entering the RecordScreen, but that did not affect it (commenting this line out for now)
            //  trainingSetsViewModel.getUserTrainingSets("20c1256d-0bdb-4241-8781-10f7353e5a3b")

                RecordScreen(
                    navController = navController,
                    trainingSetsViewModel= TrainingSetsViewModel,
                )
            }
        }
    }
}
</code>```

What somewhat worked...

I was able to get the list to eventually load by making the following two changes (see comments in code), but it still did not load in the expected sequence and this change did not seem to align from all the examples I've seen. I will note that with this change, once the list showed up, the newly created records would be properly displayed as well.

*TrainingSetsViewModel.kt *(modified)

```<code>private val _userTrainingSets = MutableLiveData<List<TrainingSet>>(emptyList())

/ ***************
// change #1 (change this variable from a val to a var)
/ ***************
var userTrainingSets: LiveData<List<TrainingSet>> = _userTrainingSets

... // same code as above example

fun getUserTrainingSets(userId: String) {
    viewModelScope.launch {
        // ***************
        // change #2 (did this instead of: _userTrainingSets.value = repository.getUserTrainingSets(userId).value)
        // ***************

        userTrainingSets = repository.getUserTrainingSets(userId)
    }
}

... // same code as above example
</code>```

Body:
I'm currently trying to use a SQLite database via the Room library on my Jetpack Compose project to create a view that does the following:

display a list of entries from the database that are filtered to only records with the current user's ID

allow the user to create new records and insert those into the database

update the list to include any newly created records

My issue is that I cannot get the list to show when the view is loaded even though the database has data in it and I am able to insert records into it successfully. I've seen a lot of examples that show how do this if you are just loading all the records, but I cannot seem to figure out how to do this if I only want the list to include records with the user's ID.

After following a few of tutorials and posts it is my understanding that I should have the following:

A DAO, which returns a LiveData object

A repository which calls the DAO method and returns the same LiveData object

A viewholder  class, which will contain two objects: one private MutableLiveData variable and one public LiveData variable (this one is the one we observe from the view)

My view, a Composable function, that observes the changes

However, with this setup, the list still will not load and I do not see any calls to the database to load the list from the "App Inspection" tab. The code is as follows:

TrainingSet.kt

@Entity(tableName = "training_sets")
data class TrainingSet (
    @PrimaryKey() val id: String,
    @ColumnInfo(name = "user_id") val userId: String,

TrainingSetDao.kt

@Dao
interface TrainingSetDao {
    @Insert(onConflict = OnConflictStrategy.ABORT)
    suspend fun insert(trainingSet: TrainingSet)

    @Query("SELECT * FROM training_sets WHERE user_id = :userId")
    fun getUserTrainingSets(userId: String): LiveData<List<TrainingSet>>
}

TrainingSetRepository.kt

class TrainingSetRepository(private val trainingSetDao: TrainingSetDao) {
    fun getUserTrainingSets(userId: String): LiveData<List<TrainingSet>> {
        return trainingSetDao.getUserTrainingSets(userId)
    }

    suspend fun insert(trainingSet: TrainingSet) {
        trainingSetDao.insert(trainingSet)
    }
}

TrainingSetsViewModel.kt

class TrainingSetsViewModel(application: Application): ViewModel() {
    private val repository: TrainingSetRepository

    private val _userTrainingSets = MutableLiveData<List<TrainingSet>>(emptyList())
    val userTrainingSets: LiveData<List<TrainingSet>> get() = _userTrainingSets

    init {
        val trainingSetDao = AppDatabase.getDatabase(application.applicationContext).getTrainingSetDao()

        repository = TrainingSetRepository(trainingSetDao)
    }

    fun getUserTrainingSets(userId: String) {
        viewModelScope.launch {
            _userTrainingSets.value = repository.getUserTrainingSets(userId).value
        }
    }

    fun insertTrainingSet(trainingSet: TrainingSet) {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                repository.insert(trainingSet)
            } catch (err: Exception) {
                println("Error!!!!: ${err.message}")
            }
        }
    }
}

RecordScreen.kt

@Composable
fun RecordScreen(navController: NavController, trainingSetsViewModel: TrainingSetsViewModel) {
    // observe the list
    val trainingSets by trainingSetsViewModel.userTrainingSets.observeAsState()

    // trigger loading of the list using the userID
    // note: hardcoding this ID for now
    trainingSetsViewModel.getUserTrainingSets("20c1256d-0bdb-4241-8781-10f7353e5a3b")

    // ... some code here

    Button(onClick = {
        trainingSetsViewModel.insertTrainingSet(TrainingSet(// dummy test data here //))
    }) {
        Text(text = "Add Record")
    }

    // ... some more code here

    LazyColumn() {
        itemsIndexed(trainingSets) { key, item ->
            // ... list row components here
        }
    }

NavGraph.kt** **(including this in case it's relevant)

@Composable
fun NavGraph(navController: NavHostController) {
    NavHost(
        navController = navController,
        startDestination = Screens.Record.route,
    ) {
        composable(route = Screens.Record.route) {
            val owner = LocalViewModelStoreOwner.current

            owner?.let {
                val trainingSetsViewModel: TrainingSetsViewModel = viewModel(
                    it,
                    "TrainingSetsViewModel",
                    MainViewModelFactory(LocalContext.current.applicationContext as Application)
                )

            // note: I attempted to load the user training sets here in case it needed to be done before entering the RecordScreen, but that did not affect it (commenting this line out for now)
            //  trainingSetsViewModel.getUserTrainingSets("20c1256d-0bdb-4241-8781-10f7353e5a3b")

                RecordScreen(
                    navController = navController,
                    trainingSetsViewModel= TrainingSetsViewModel,
                )
            }
        }
    }
}

What somewhat worked...

I was able to get the list to eventually load by making the following two changes (see comments in code), but it still did not load in the expected sequence and this change did not seem to align from all the examples I've seen. I will note that with this change, once the list showed up, the newly created records would be properly displayed as well.

*TrainingSetsViewModel.kt *(modified)

private val _userTrainingSets = MutableLiveData<List<TrainingSet>>(emptyList())

/ ***************
// change #1 (change this variable from a val to a var)
/ ***************
var userTrainingSets: LiveData<List<TrainingSet>> = _userTrainingSets

... // same code as above example

fun getUserTrainingSets(userId: String) {
    viewModelScope.launch {
        // ***************
        // change #2 (did this instead of: _userTrainingSets.value = repository.getUserTrainingSets(userId).value)
        // ***************

        userTrainingSets = repository.getUserTrainingSets(userId)
    }
}

... // same code as above example


问:
mandatory and optional options with argc and argv
I want to create a programme that will have mandatory option and optional option.

Mandatory:

-d <device>

Optional:

-h : help

-m <value> : launch an internal function with the value of the argument.

... (other optional option with or without argument).

I see how manage only optional option but how to cohabitate the mandatory and optional?

Other info: the mandatory option will give the information on what /dev/video# to open and needs to be done before parsing the optional options where functions will be called that need to have the file descriptor already opened.

I tried to manage it with getopt() but I did not see how to manage both mandatory and optional options.


问:
GitHub Actions - Add Submodule

Problem

I want to be able to add a submodule automatically using GitHub Actions.

I have tried using the following command (since it works fine when run locally on my computer)

```<code>name: Trigger to Add New Submodule

on:

  repository_dispatch:
    types: [ trigger-add-new-submodule ]

jobs:
  addSubmodule:
    name: Add Submodule
    runs-on: [ self-hosted, windows ]

    steps:
      - name: Checkout
        uses: actions/checkout@v3
        with:
          token: ${{ secrets.MY_TOKEN || secrets.GITHUB_TOKEN }}
          submodules: recursive

      - name: Pull
        run: git pull

      - name: Add Submodule
        run: git submodule add URL PATH
</code>```

However, when it is running through the GitHub Actions it appears to have frozen.

I am not sure if it is waiting for user input, or stuck for some other reason.

I used GitHub Hosted instead of self-hosted and got the following output.

```<code>fatal: Cannot prompt because user interactivity has been disabled.
bash: line 1: /dev/tty: No such device or address
error: failed to execute prompt script (exit code 1)
fatal: could not read Username for 'https://github.com': No such file or directory
</code>```

It appears to be an issue with lack of user interactivity.
I am not sure how to allow this, since I cannot use with: token: with run:

Question

Is this even the right way to go about doing this?

I couldn't find any pre-built GitHub Actions to do this, so I figured I should just use the git commands directly.

Is this the correct command to be using, or is there another command that would work better?

Title: GitHub Actions - Add Submodule

Body:
Problem

I want to be able to add a submodule automatically using GitHub Actions.

I have tried using the following command (since it works fine when run locally on my computer)

name: Trigger to Add New Submodule

on:

  repository_dispatch:
    types: [ trigger-add-new-submodule ]

jobs:
  addSubmodule:
    name: Add Submodule
    runs-on: [ self-hosted, windows ]

    steps:
      - name: Checkout
        uses: actions/checkout@v3
        with:
          token: ${{ secrets.MY_TOKEN || secrets.GITHUB_TOKEN }}
          submodules: recursive

      - name: Pull
        run: git pull

      - name: Add Submodule
        run: git submodule add URL PATH

However, when it is running through the GitHub Actions it appears to have frozen.

I am not sure if it is waiting for user input, or stuck for some other reason.

I used GitHub Hosted instead of self-hosted and got the following output.

fatal: Cannot prompt because user interactivity has been disabled.
bash: line 1: /dev/tty: No such device or address
error: failed to execute prompt script (exit code 1)
fatal: could not read Username for 'https://github.com': No such file or directory

It appears to be an issue with lack of user interactivity.
I am not sure how to allow this, since I cannot use with: token: with run:

Question

Is this even the right way to go about doing this?

I couldn't find any pre-built GitHub Actions to do this, so I figured I should just use the git commands directly.

Is this the correct command to be using, or is there another command that would work better?


Title: Send a binary file as raw

Body:
I am trying to send a zip file as binary via HTTP request, When I do a call setting the Postman's tab as Binary then it works as I want to:

But when I try to send the same file as binary and use the option "RAW" then it does not work.I've tried to convert the zip into a binary in Java with the below code:

    try {
        StringBuilder sb = new StringBuilder();
        File file = new File(filePath);
        DataInputStream input = new DataInputStream( new FileInputStream( file ) );
        try {
            while( true ) {
                sb.append( Integer.toBinaryString( input.readByte() ) );
                //10100001001011111001010000010000101111111111111111111111111111111100101101010101100100111111111111111111111111111001110101100111111111111111111111111110110011101000010000001000000111010011001011110011111010010111011101001111000111010010101110010011011011011101001001110101110000110000100010100001001011110111110101000001000010111111111111111111111111111111110010110101010110010011111111111111111111111111100111010110011111111111111111111111111011001110100001000000100001001000000000100000000000011101001100101111001111101001011101110100111100011101001010010000000000101100001011001101100100010111101111011011111111111111111111111111011001110110011011001000101111011110110111111111111111111111111110110011111111111111111111111111101110101111111111111111111111111011011111111111111111111111111111101110100110111101101111111111111111111111111101100111010000100101110111000001010101101000011000000000
            }
        } catch( EOFException eof ) {
        } catch( IOException e ) {
            e.printStackTrace();
        }
        System.out.println(sb.toString());
    } catch( FileNotFoundException e2 ) {
        e2.printStackTrace();
    }

The message is being receiving with a different size and it is not the content I am expecting:

Can you tell me how I can send it as binary using the tab raw?


问:
How can I filter datetime field in time slots?
I have time series in Polars which I need to filter e.g. in between 15:30 and 22:00 for any day.

I've found this example to filter dates but its not enough as I need to filter by hours and minutes:

filtered_range_df = df.filter(
    pl.col("Date").is_between(datetime(1995, 7, 1), datetime(1995, 11, 1)),
)
```
<p>In pandas its possible:</p>
```i = pd.date_range('2018-04-09', periods=4, freq='1D20min')
ts = pd.DataFrame({'A': [1, 2, 3, 4]}, index=i)
ts.between_time('0:15', '0:45')
```

Body:
I have time series in Polars which I need to filter e.g. in between 15:30 and 22:00 for any day.

I've found this example to filter dates but its not enough as I need to filter by hours and minutes:

filtered_range_df = df.filter(
    pl.col("Date").is_between(datetime(1995, 7, 1), datetime(1995, 11, 1)),
)

In pandas its possible:

i = pd.date_range('2018-04-09', periods=4, freq='1D20min')
ts = pd.DataFrame({'A': [1, 2, 3, 4]}, index=i)
ts.between_time('0:15', '0:45')


问:
1000 Errors BC30469, Reference BC30925, After Creating a Form and Inserting Some Components
I was adding a new Form to my program in visual studio, and I put in some basic components like panel, labels and PictureBox, when I got back to the code, it simply All forms had problems BC30469 with the description "Reference to a non-shared member requires a reference of object." and some like BC30925 with the description "Access specified in form "friend" does not match the access specified in "Public" in one of its other partial types." for all commands that reference other commands in other forms, and before to add this new form, there was none,

I undo the whole process of adding the form and it continues with the same errors!


问:
Transforming random variables from competing exponential distributions
I have a question regarding transforming one set of random variables to another.
Suppose that we have a sample of data collected from two competing exponential distributions, with rate a and b. We know that the random variables X follow an exponential distribution with rate (a + b).
Now suppose that we know the rate a, and we want to transform the random variables to a new set of random variables, so that the new set of random variables Y so that Y follows the exponential distribution with rate b.
Is there a way to do so? I would appreciate any answers or references.
Best regards.

We have looked into convolution of variables, but it seems not to fit since X cannot be represented as sum of two random variables.


问:
Android Studio Firebase upload imagen and path?
I have a problem, I am upload to firebase an image and the result is....

Example:
This is the result that upload on firebase

/storage/emulated/0/android.graphics.Bitmap@69ce6fb.png

But I'm require an URL.
EXAMPLE:

https://firebasestorage.googleapis.com/v0/b/-89ac7.appspot.com/o/Tue%20Nov%2008%2018%3A03%3A.....

Code example:

```<code>Bundle bundle = getIntent().getExtras();
        if (bundle!=null){
            int res_image= bundle.getInt("myImage");
            Toast.makeText(this, "foto"+res_image, Toast.LENGTH_SHORT).show();
        }
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeStream(EditPhotoActivity.this.openFileInput("myImage"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        File file = new File(Environment.getExternalStorageDirectory()
                .toString() + "/" + bitmap + ".png");
        mImagenPerfil = file.getAbsolutePath();
</code>```

Body:
I have a problem, I am upload to firebase an image and the result is....

Example:
This is the result that upload on firebase

/storage/emulated/0/android.graphics.Bitmap@69ce6fb.png

But I'm require an URL.
EXAMPLE:

https://firebasestorage.googleapis.com/v0/b/-89ac7.appspot.com/o/Tue%20Nov%2008%2018%3A03%3A.....

Code example:

Bundle bundle = getIntent().getExtras();
        if (bundle!=null){
            int res_image= bundle.getInt("myImage");
            Toast.makeText(this, "foto"+res_image, Toast.LENGTH_SHORT).show();
        }
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeStream(EditPhotoActivity.this.openFileInput("myImage"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        File file = new File(Environment.getExternalStorageDirectory()
                .toString() + "/" + bitmap + ".png");
        mImagenPerfil = file.getAbsolutePath();


问:
Filter from the secondary data source can't be applied to a worksheet in Tableau
I have a worksheet that connects to two CSVs - 'Customer Report' and 'Views'. Customer Report is the secondary data source and Views is the primary data source blended within the worksheet on "location" and "sub location" fields.

I have used an "Age" filter from the Customer Report in another worksheet that has Customer Report as the primary data source and I have applied it to all related data sources. However, I'm not being able to apply it to my current worksheet. Even when I select "Apply to selected worksheets" and search for the relevant worksheet name, it appears greyed out. Any idea how I can get it to apply?

Thank you in advance!


问:
Tensorflow error Invalid argument Compilation failure: Detected unsupported operations when trying to compile graph cluster_tpu_function
I am receiving an error when I train my Deep Learning network using TPU

The error is related to the below part of my code but I don't know how to solve it.

```<code>preprocessing.RandomCrop(28, 28)
</code>```

NB: the code is running fine if I use no accelerator or GPU but not on TPU

I am using tensorflow 2.6.4 and kaggle TPU V3-8 for the training

You can find the notebook link that reproduce the error  here on kaggle

Here is the code that reproduce the error:

import math, re, os
import tensorflow as tf
print("Tensorflow version " + tf.__version__)
# from tensorflow.keras.utils import img_to_array, load_img
from tensorflow.keras.preprocessing.image import img_to_array, load_img
from tensorflow.image import extract_patches
from tensorflow.keras.layers import Input,  Dense, Embedding, LayerNormalization, Conv2D, concatenate, LeakyReLU, GlobalMaxPooling2D
from tensorflow.keras.layers.experimental import preprocessing#, RandomFlip, RandomZoom, RandomRotation, Rescaling

from tensorflow.keras.models import Model,Sequential#, Input
import numpy as np
AUTO = tf.data.experimental.AUTOTUNE

try: # detect TPUs
    tpu = tf.distribute.cluster_resolver.TPUClusterResolver.connect() # TPU detection
    strategy = tf.distribute.TPUStrategy(tpu)
except ValueError: # detect GPUs
    strategy = tf.distribute.MirroredStrategy() # for GPU or multi-GPU machines

print("Number of accelerators: ", strategy.num_replicas_in_sync)

image_shape =(224, 224,3) #128, 128(286, 286) (224, 224,3)
# batch_size = 5
batch_size = 32 * strategy.num_replicas_in_sync
save_dir = "./"
path = "../input/urban-and-rural-photos/train/"
N_sample = 32 # number of samples per batch

trainAug = Sequential([
#   preprocessing.Rescaling(scale=1.0 / 255),
    preprocessing.RandomFlip("horizontal_and_vertical"),
    preprocessing.RandomZoom(
        height_factor=(-0.05, -0.15),
        width_factor=(-0.05, -0.15)),
    preprocessing.RandomRotation(0.3)
])

def load_images(path, size=image_shape):
    data_list = list()
    # enumerate filenames in directory, assume all are images
    for filename in os.listdir(path):
        # load and resize the image
        pixels = load_img(path + filename, target_size=size)
        # convert to numpy array
        pixels = img_to_array(pixels)
        # store
        data_list.append(pixels)

    datas = np.asarray(data_list)
    datas = datas.astype('float32') / 255.0
    dataset = tf.data.Dataset.from_tensor_slices(datas)
    # dataset = dataset.batch(128)
    #   dataset = dataset.shuffle(buffer_size=1024)
    return dataset

with strategy.scope():
    # load dataset (low light image)
    dataL_all = (load_images(path + '/rural/')
    #   .shuffle(batch_size * 100)
        .batch(batch_size)
        .cache()
        .map(lambda x: (trainAug(x)),
             num_parallel_calls=tf.data.AUTOTUNE)
        .prefetch(tf.data.AUTOTUNE)
    )

    # load dataset (normal light image)
    dataH_all =(
        load_images(path + '/urban/')
    #   .shuffle(batch_size * 100)
        .batch(batch_size)
        .cache()
        .map(lambda x: (trainAug(x)),
             num_parallel_calls=tf.data.AUTOTUNE)
        .prefetch(tf.data.AUTOTUNE)
    )
dataL_allD = strategy.experimental_distribute_dataset(dataL_all)
dataH_allD = strategy.experimental_distribute_dataset(dataH_all)

with strategy.scope():
    discriminator_local = Sequential(
        [
            Input(shape=image_shape),
            preprocessing.RandomCrop(28, 28),
            Conv2D(8, (3, 3), strides=(2, 2), padding="same"),
            LeakyReLU(alpha=0.2),
            Conv2D(16, (3, 3), strides=(2, 2), padding="same"),
            LeakyReLU(alpha=0.2),
            Conv2D(32, (3, 3), strides=(2, 2), padding="same"),
            LeakyReLU(alpha=0.2),
            Conv2D(64, (3, 3), strides=(2, 2), padding="same"),
            LeakyReLU(alpha=0.2),
            Conv2D(128, (3, 3), strides=(2, 2), padding="same"),
            LeakyReLU(alpha=0.2),
            Conv2D(256, (3, 3), strides=(2, 2), padding="same"),
            LeakyReLU(alpha=0.2),
            GlobalMaxPooling2D(),
            Dense(1),
        ],
        name="local_discriminator",
    )
    discriminator_local.summary()

@tf.function
def train_steps(dataset):
    return discriminator_local(dataset[0])

EPOCHS = 2
STEPS = 3
for epoch in range(EPOCHS):
    total_loss = 0.0
    num_batches = 0
    for step, datasets in enumerate(zip(dataL_allD, dataH_allD)):
        loss_per_replica= strategy.run(train_steps, args=(datasets,)) #train_step(datasets)
        total_loss += strategy.reduce("SUM", loss_per_replica,axis=0)
        num_batches += 1
    average_train_loss = total_loss / num_batches
    print(f'Epoch :{epoch}   loss : {average_train_loss}')

```
<p>And here is the stack trace of the error:</p>
```2022-12-25 12:21:26.814769: W tensorflow/core/distributed_runtime/eager/remote_tensor_handle_data.cc:76] Unable to destroy remote tensor handles. If you are running a tf.function, it usually indicates some op in the graph gets an error: 9 root error(s) found.
  (0) Invalid argument: {{function_node __inference_tpu_function_6371}} Compilation failure: Detected unsupported operations when trying to compile graph cluster_tpu_function_6096887307567101759[] on XLA_TPU_JIT: StatelessRandomUniformInt (No registered 'StatelessRandomUniformInt' OpKernel for XLA_TPU_JIT devices compatible with node {{node local_discriminator/random_crop/stateless_random_uniform}}
     (OpKernel was found, but attributes didn't match) Requested Attributes: T=DT_INT32, Tseed=DT_INT64, dtype=DT_INT32, _device="/device:TPU_REPLICATED_CORE"){{node local_discriminator/random_crop/stateless_random_uniform}}One approach is to outside compile the unsupported ops to run on CPUs by enabling soft placement `tf.config.set_soft_device_placement(True)`. This has a potential performance penalty.
    TPU compilation failed
     [[tpu_compile_succeeded_assert/_9679846132704141549/_5]]
     [[cluster_tpu_function/control_after/_1/_279]]
  (1) Invalid argument: {{function_node __inference_tpu_function_6371}} Compilation failure: Detected unsupported operations when trying to compile graph cluster_tpu_function_6096887307567101759[] on XLA_TPU_JIT: StatelessRandomUniformInt (No registered 'StatelessRandomUniformInt' OpKernel for XLA_TPU_JIT devices compatible with node {{node local_discriminator/random_crop/stateless_random_uniform}}
     (OpKernel was found, but attributes didn't match) Requested Attributes: T=DT_INT32, Tseed=DT_INT64, dtype=DT_INT32, _device="/device:TPU_REPLICATED_CORE"){{node local_discriminator/random_crop/stateless_random_uniform}}One approach is to outside compile the unsupported ops to run on CPUs by enabling soft placement `tf.config.set_soft_device_placement(True)`. This has a potential performance penalty.
    TPU compilation failed
     [[tpu_compile_succeeded_assert/_9679846132704141549/_5]]
     [[tpu_compile_succeeded_assert/_9679846132704141549/_5/_153]]
  (2) Invalid argument: {{function_node __inference_tpu_function_6371}} Compilation failure: Detected unsupported operations when trying to compile graph cluster_tpu_function_6096887307567101759[] on XLA_TPU_JIT: StatelessRandomUniformInt (No registered 'StatelessRandomUniformInt' OpKernel for XLA_TPU_JIT devices compatible with node {{node local_discriminator/random_crop/stateless_random_uniform}}
     (OpKernel was found, but attributes didn't match) Requested Attributes: T=DT_INT32, Tseed=DT_INT64, dtype=DT_INT32, _device="/device:TPU_REPLICATED_CORE"){{node local_discriminator/random_crop/stateless_random_uniform}}One approach is to outside compile the unsupported ops to run on CPUs by enabling soft placement `tf.config.set_soft_device_placement(True)`. This has a potential performance penalty.
    TPU compilation failed
     [[tpu_compile_succeeded_assert/_9679846132704141549/_5]]
     [[tpu_compile_succeeded_assert/_9679846132704141549/_5/_167]]
  (3) Invalid argument: {{function_node __inference_tpu_function_6371}} Compilation failure: Detected unsupported operations when trying to compile graph cluster_tpu_function_6096887307567101759[] on XL ... [truncated]
---------------------------------------------------------------------------
InvalidArgumentError                      Traceback (most recent call last)
/tmp/ipykernel_20/3910360392.py in <module>
      6     for step, datasets in enumerate(zip(dataL_allD, dataH_allD)):
      7         loss_per_replica= strategy.run(train_steps, args=(datasets,)) #train_step(datasets)
----> 8         total_loss += strategy.reduce("SUM", loss_per_replica,axis=0)
      9         num_batches += 1
     10     average_train_loss = total_loss / num_batches

/opt/conda/lib/python3.7/site-packages/tensorflow/python/distribute/distribute_lib.py in reduce(self, reduce_op, value, axis)
   1386
   1387           self._reduce_sum_fns[axis] = def_function.function(reduce_sum_fn)
-> 1388         value = self._reduce_sum_fns[axis](value)
   1389       else:
   1390         value = self.run(reduce_sum, args=(value,))

/opt/conda/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds)
    826     tracing_count = self.experimental_get_tracing_count()
    827     with trace.Trace(self._name) as tm:
--> 828       result = self._call(*args, **kwds)
    829       compiler = "xla" if self._experimental_compile else "nonXla"
    830       new_tracing_count = self.experimental_get_tracing_count()

/opt/conda/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds)
    860       # In this case we have not created variables on the first call. So we can
    861       # run the first trace but we should fail if variables are created.
--> 862       results = self._stateful_fn(*args, **kwds)
    863       if self._created_variables:
    864         raise ValueError("Creating variables on a non-first call to a function"

/opt/conda/lib/python3.7/site-packages/tensorflow/python/eager/function.py in __call__(self, *args, **kwargs)
   2939     with self._lock:
   2940       (graph_function,
-> 2941        filtered_flat_args) = self._maybe_define_function(args, kwargs)
   2942     return graph_function._call_flat(
   2943         filtered_flat_args, captured_inputs=graph_function.captured_inputs)  # pylint: disable=protected-access

/opt/conda/lib/python3.7/site-packages/tensorflow/python/eager/function.py in _maybe_define_function(self, args, kwargs)
   3312     if self.input_signature is None or args is not None or kwargs is not None:
   3313       args, kwargs, flat_args, filtered_flat_args = \
-> 3314           self._function_spec.canonicalize_function_inputs(*args, **kwargs)
   3315     else:
   3316       flat_args, filtered_flat_args = [None], []

/opt/conda/lib/python3.7/site-packages/tensorflow/python/eager/function.py in canonicalize_function_inputs(self, *args, **kwargs)
   2695
   2696     if self._input_signature is None:
-> 2697       inputs, flat_inputs, filtered_flat_inputs = _convert_numpy_inputs(inputs)
   2698       kwargs, flat_kwargs, filtered_flat_kwargs = _convert_numpy_inputs(kwargs)
   2699       return (inputs, kwargs, flat_inputs + flat_kwargs,

/opt/conda/lib/python3.7/site-packages/tensorflow/python/eager/function.py in _convert_numpy_inputs(inputs)
   2735   # are eventually passed to ConcreteFunction()._call_flat, which requires
   2736   # expanded composites.
-> 2737   flat_inputs = nest.flatten(inputs, expand_composites=True)
   2738
   2739   # Check for NumPy arrays in arguments and convert them to Tensors.

/opt/conda/lib/python3.7/site-packages/tensorflow/python/util/nest.py in flatten(structure, expand_composites)
    339     return [None]
    340   expand_composites = bool(expand_composites)
--> 341   return _pywrap_utils.Flatten(structure, expand_composites)
    342
    343

/opt/conda/lib/python3.7/site-packages/tensorflow/python/distribute/values.py in _type_spec(self)
    381       return copy.deepcopy(self._type_spec_override)
    382     return PerReplicaSpec(
--> 383         *(type_spec.type_spec_from_value(v) for v in self._values))
    384
    385   @property

/opt/conda/lib/python3.7/site-packages/tensorflow/python/distribute/values.py in <genexpr>(.0)
    381       return copy.deepcopy(self._type_spec_override)
    382     return PerReplicaSpec(
--> 383         *(type_spec.type_spec_from_value(v) for v in self._values))
    384
    385   @property

/opt/conda/lib/python3.7/site-packages/tensorflow/python/framework/type_spec.py in type_spec_from_value(value)
    537       is not supported.
    538   """
--> 539   spec = _type_spec_from_value(value)
    540   if spec is not None:
    541     return spec

/opt/conda/lib/python3.7/site-packages/tensorflow/python/framework/type_spec.py in _type_spec_from_value(value)
    559   if isinstance(value, ops.Tensor):
    560     # Note: we do not include Tensor names when constructing TypeSpecs.
--> 561     return tensor_spec.TensorSpec(value.shape, value.dtype)
    562
    563   if isinstance(value, composite_tensor.CompositeTensor):

/opt/conda/lib/python3.7/site-packages/tensorflow/python/framework/ops.py in shape(self)
   1173         # `_tensor_shape` is declared and defined in the definition of
   1174         # `EagerTensor`, in C.
-> 1175         self._tensor_shape = tensor_shape.TensorShape(self._shape_tuple())
   1176       except core._NotOkStatusException as e:
   1177         six.raise_from(core._status_to_exception(e.code, e.message), None)

InvalidArgumentError: 9 root error(s) found.
  (0) Invalid argument: {{function_node __inference_tpu_function_6371}} Compilation failure: Detected unsupported operations when trying to compile graph cluster_tpu_function_6096887307567101759[] on XLA_TPU_JIT: StatelessRandomUniformInt (No registered 'StatelessRandomUniformInt' OpKernel for XLA_TPU_JIT devices compatible with node {{node local_discriminator/random_crop/stateless_random_uniform}}
     (OpKernel was found, but attributes didn't match) Requested Attributes: T=DT_INT32, Tseed=DT_INT64, dtype=DT_INT32, _device="/device:TPU_REPLICATED_CORE"){{node local_discriminator/random_crop/stateless_random_uniform}}One approach is to outside compile the unsupported ops to run on CPUs by enabling soft placement `tf.config.set_soft_device_placement(True)`. This has a potential performance penalty.
    TPU compilation failed
     [[tpu_compile_succeeded_assert/_9679846132704141549/_5]]
     [[cluster_tpu_function/control_after/_1/_279]]
  (1) Invalid argument: {{function_node __inference_tpu_function_6371}} Compilation failure: Detected unsupported operations when trying to compile graph cluster_tpu_function_6096887307567101759[] on XLA_TPU_JIT: StatelessRandomUniformInt (No registered 'StatelessRandomUniformInt' OpKernel for XLA_TPU_JIT devices compatible with node {{node local_discriminator/random_crop/stateless_random_uniform}}
     (OpKernel was found, but attributes didn't match) Requested Attributes: T=DT_INT32, Tseed=DT_INT64, dtype=DT_INT32, _device="/device:TPU_REPLICATED_CORE"){{node local_discriminator/random_crop/stateless_random_uniform}}One approach is to outside compile the unsupported ops to run on CPUs by enabling soft placement `tf.config.set_soft_device_placement(True)`. This has a potential performance penalty.
    TPU compilation failed
     [[tpu_compile_succeeded_assert/_9679846132704141549/_5]]
     [[tpu_compile_succeeded_assert/_9679846132704141549/_5/_153]]
  (2) Invalid argument: {{function_node __inference_tpu_function_6371}} Compilation failure: Detected unsupported operations when trying to compile graph cluster_tpu_function_6096887307567101759[] on XLA_TPU_JIT: StatelessRandomUniformInt (No registered 'StatelessRandomUniformInt' OpKernel for XLA_TPU_JIT devices compatible with node {{node local_discriminator/random_crop/stateless_random_uniform}}
     (OpKernel was found, but attributes didn't match) Requested Attributes: T=DT_INT32, Tseed=DT_INT64, dtype=DT_INT32, _device="/device:TPU_REPLICATED_CORE"){{node local_discriminator/random_crop/stateless_random_uniform}}One approach is to outside compile the unsupported ops to run on CPUs by enabling soft placement `tf.config.set_soft_device_placement(True)`. This has a potential performance penalty.
    TPU compilation failed
     [[tpu_compile_succeeded_assert/_9679846132704141549/_5]]
     [[tpu_compile_succeeded_assert/_9679846132704141549/_5/_167]]
  (3) Invalid argument: {{function_node __inference_tpu_function_6371}} Compilation failure: Detected unsupported operations when trying to compile graph cluster_tpu_function_6096887307567101759[] on XL ... [truncated]
```

Please, I need your help to advance on my project

Body:
I am receiving an error when I train my Deep Learning network using TPU

The error is related to the below part of my code but I don't know how to solve it.

preprocessing.RandomCrop(28, 28)

NB: the code is running fine if I use no accelerator or GPU but not on TPU

I am using tensorflow 2.6.4 and kaggle TPU V3-8 for the training

You can find the notebook link that reproduce the error  here on kaggle

Here is the code that reproduce the error:

import math, re, os
import tensorflow as tf
print("Tensorflow version " + tf.__version__)
# from tensorflow.keras.utils import img_to_array, load_img
from tensorflow.keras.preprocessing.image import img_to_array, load_img
from tensorflow.image import extract_patches
from tensorflow.keras.layers import Input,  Dense, Embedding, LayerNormalization, Conv2D, concatenate, LeakyReLU, GlobalMaxPooling2D
from tensorflow.keras.layers.experimental import preprocessing#, RandomFlip, RandomZoom, RandomRotation, Rescaling

from tensorflow.keras.models import Model,Sequential#, Input
import numpy as np
AUTO = tf.data.experimental.AUTOTUNE

try: # detect TPUs
    tpu = tf.distribute.cluster_resolver.TPUClusterResolver.connect() # TPU detection
    strategy = tf.distribute.TPUStrategy(tpu)
except ValueError: # detect GPUs
    strategy = tf.distribute.MirroredStrategy() # for GPU or multi-GPU machines

print("Number of accelerators: ", strategy.num_replicas_in_sync)

image_shape =(224, 224,3) #128, 128(286, 286) (224, 224,3)
# batch_size = 5
batch_size = 32 * strategy.num_replicas_in_sync
save_dir = "./"
path = "../input/urban-and-rural-photos/train/"
N_sample = 32 # number of samples per batch

trainAug = Sequential([
#   preprocessing.Rescaling(scale=1.0 / 255),
    preprocessing.RandomFlip("horizontal_and_vertical"),
    preprocessing.RandomZoom(
        height_factor=(-0.05, -0.15),
        width_factor=(-0.05, -0.15)),
    preprocessing.RandomRotation(0.3)
])

def load_images(path, size=image_shape):
    data_list = list()
    # enumerate filenames in directory, assume all are images
    for filename in os.listdir(path):
        # load and resize the image
        pixels = load_img(path + filename, target_size=size)
        # convert to numpy array
        pixels = img_to_array(pixels)
        # store
        data_list.append(pixels)

    datas = np.asarray(data_list)
    datas = datas.astype('float32') / 255.0
    dataset = tf.data.Dataset.from_tensor_slices(datas)
    # dataset = dataset.batch(128)
    #   dataset = dataset.shuffle(buffer_size=1024)
    return dataset

with strategy.scope():
    # load dataset (low light image)
    dataL_all = (load_images(path + '/rural/')
    #   .shuffle(batch_size * 100)
        .batch(batch_size)
        .cache()
        .map(lambda x: (trainAug(x)),
             num_parallel_calls=tf.data.AUTOTUNE)
        .prefetch(tf.data.AUTOTUNE)
    )

    # load dataset (normal light image)
    dataH_all =(
        load_images(path + '/urban/')
    #   .shuffle(batch_size * 100)
        .batch(batch_size)
        .cache()
        .map(lambda x: (trainAug(x)),
             num_parallel_calls=tf.data.AUTOTUNE)
        .prefetch(tf.data.AUTOTUNE)
    )
dataL_allD = strategy.experimental_distribute_dataset(dataL_all)
dataH_allD = strategy.experimental_distribute_dataset(dataH_all)

with strategy.scope():
    discriminator_local = Sequential(
        [
            Input(shape=image_shape),
            preprocessing.RandomCrop(28, 28),
            Conv2D(8, (3, 3), strides=(2, 2), padding="same"),
            LeakyReLU(alpha=0.2),
            Conv2D(16, (3, 3), strides=(2, 2), padding="same"),
            LeakyReLU(alpha=0.2),
            Conv2D(32, (3, 3), strides=(2, 2), padding="same"),
            LeakyReLU(alpha=0.2),
            Conv2D(64, (3, 3), strides=(2, 2), padding="same"),
            LeakyReLU(alpha=0.2),
            Conv2D(128, (3, 3), strides=(2, 2), padding="same"),
            LeakyReLU(alpha=0.2),
            Conv2D(256, (3, 3), strides=(2, 2), padding="same"),
            LeakyReLU(alpha=0.2),
            GlobalMaxPooling2D(),
            Dense(1),
        ],
        name="local_discriminator",
    )
    discriminator_local.summary()

@tf.function
def train_steps(dataset):
    return discriminator_local(dataset[0])

EPOCHS = 2
STEPS = 3
for epoch in range(EPOCHS):
    total_loss = 0.0
    num_batches = 0
    for step, datasets in enumerate(zip(dataL_allD, dataH_allD)):
        loss_per_replica= strategy.run(train_steps, args=(datasets,)) #train_step(datasets)
        total_loss += strategy.reduce("SUM", loss_per_replica,axis=0)
        num_batches += 1
    average_train_loss = total_loss / num_batches
    print(f'Epoch :{epoch}   loss : {average_train_loss}')

And here is the stack trace of the error:

2022-12-25 12:21:26.814769: W tensorflow/core/distributed_runtime/eager/remote_tensor_handle_data.cc:76] Unable to destroy remote tensor handles. If you are running a tf.function, it usually indicates some op in the graph gets an error: 9 root error(s) found.
  (0) Invalid argument: {{function_node __inference_tpu_function_6371}} Compilation failure: Detected unsupported operations when trying to compile graph cluster_tpu_function_6096887307567101759[] on XLA_TPU_JIT: StatelessRandomUniformInt (No registered 'StatelessRandomUniformInt' OpKernel for XLA_TPU_JIT devices compatible with node {{node local_discriminator/random_crop/stateless_random_uniform}}
     (OpKernel was found, but attributes didn't match) Requested Attributes: T=DT_INT32, Tseed=DT_INT64, dtype=DT_INT32, _device="/device:TPU_REPLICATED_CORE"){{node local_discriminator/random_crop/stateless_random_uniform}}One approach is to outside compile the unsupported ops to run on CPUs by enabling soft placement `tf.config.set_soft_device_placement(True)`. This has a potential performance penalty.
    TPU compilation failed
     [[tpu_compile_succeeded_assert/_9679846132704141549/_5]]
     [[cluster_tpu_function/control_after/_1/_279]]
  (1) Invalid argument: {{function_node __inference_tpu_function_6371}} Compilation failure: Detected unsupported operations when trying to compile graph cluster_tpu_function_6096887307567101759[] on XLA_TPU_JIT: StatelessRandomUniformInt (No registered 'StatelessRandomUniformInt' OpKernel for XLA_TPU_JIT devices compatible with node {{node local_discriminator/random_crop/stateless_random_uniform}}
     (OpKernel was found, but attributes didn't match) Requested Attributes: T=DT_INT32, Tseed=DT_INT64, dtype=DT_INT32, _device="/device:TPU_REPLICATED_CORE"){{node local_discriminator/random_crop/stateless_random_uniform}}One approach is to outside compile the unsupported ops to run on CPUs by enabling soft placement `tf.config.set_soft_device_placement(True)`. This has a potential performance penalty.
    TPU compilation failed
     [[tpu_compile_succeeded_assert/_9679846132704141549/_5]]
     [[tpu_compile_succeeded_assert/_9679846132704141549/_5/_153]]
  (2) Invalid argument: {{function_node __inference_tpu_function_6371}} Compilation failure: Detected unsupported operations when trying to compile graph cluster_tpu_function_6096887307567101759[] on XLA_TPU_JIT: StatelessRandomUniformInt (No registered 'StatelessRandomUniformInt' OpKernel for XLA_TPU_JIT devices compatible with node {{node local_discriminator/random_crop/stateless_random_uniform}}
     (OpKernel was found, but attributes didn't match) Requested Attributes: T=DT_INT32, Tseed=DT_INT64, dtype=DT_INT32, _device="/device:TPU_REPLICATED_CORE"){{node local_discriminator/random_crop/stateless_random_uniform}}One approach is to outside compile the unsupported ops to run on CPUs by enabling soft placement `tf.config.set_soft_device_placement(True)`. This has a potential performance penalty.
    TPU compilation failed
     [[tpu_compile_succeeded_assert/_9679846132704141549/_5]]
     [[tpu_compile_succeeded_assert/_9679846132704141549/_5/_167]]
  (3) Invalid argument: {{function_node __inference_tpu_function_6371}} Compilation failure: Detected unsupported operations when trying to compile graph cluster_tpu_function_6096887307567101759[] on XL ... [truncated]
---------------------------------------------------------------------------
InvalidArgumentError                      Traceback (most recent call last)
/tmp/ipykernel_20/3910360392.py in <module>
      6     for step, datasets in enumerate(zip(dataL_allD, dataH_allD)):
      7         loss_per_replica= strategy.run(train_steps, args=(datasets,)) #train_step(datasets)
----> 8         total_loss += strategy.reduce("SUM", loss_per_replica,axis=0)
      9         num_batches += 1
     10     average_train_loss = total_loss / num_batches

/opt/conda/lib/python3.7/site-packages/tensorflow/python/distribute/distribute_lib.py in reduce(self, reduce_op, value, axis)
   1386
   1387           self._reduce_sum_fns[axis] = def_function.function(reduce_sum_fn)
-> 1388         value = self._reduce_sum_fns[axis](value)
   1389       else:
   1390         value = self.run(reduce_sum, args=(value,))

/opt/conda/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds)
    826     tracing_count = self.experimental_get_tracing_count()
    827     with trace.Trace(self._name) as tm:
--> 828       result = self._call(*args, **kwds)
    829       compiler = "xla" if self._experimental_compile else "nonXla"
    830       new_tracing_count = self.experimental_get_tracing_count()

/opt/conda/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds)
    860       # In this case we have not created variables on the first call. So we can
    861       # run the first trace but we should fail if variables are created.
--> 862       results = self._stateful_fn(*args, **kwds)
    863       if self._created_variables:
    864         raise ValueError("Creating variables on a non-first call to a function"

/opt/conda/lib/python3.7/site-packages/tensorflow/python/eager/function.py in __call__(self, *args, **kwargs)
   2939     with self._lock:
   2940       (graph_function,
-> 2941        filtered_flat_args) = self._maybe_define_function(args, kwargs)
   2942     return graph_function._call_flat(
   2943         filtered_flat_args, captured_inputs=graph_function.captured_inputs)  # pylint: disable=protected-access

/opt/conda/lib/python3.7/site-packages/tensorflow/python/eager/function.py in _maybe_define_function(self, args, kwargs)
   3312     if self.input_signature is None or args is not None or kwargs is not None:
   3313       args, kwargs, flat_args, filtered_flat_args = \
-> 3314           self._function_spec.canonicalize_function_inputs(*args, **kwargs)
   3315     else:
   3316       flat_args, filtered_flat_args = [None], []

/opt/conda/lib/python3.7/site-packages/tensorflow/python/eager/function.py in canonicalize_function_inputs(self, *args, **kwargs)
   2695
   2696     if self._input_signature is None:
-> 2697       inputs, flat_inputs, filtered_flat_inputs = _convert_numpy_inputs(inputs)
   2698       kwargs, flat_kwargs, filtered_flat_kwargs = _convert_numpy_inputs(kwargs)
   2699       return (inputs, kwargs, flat_inputs + flat_kwargs,

/opt/conda/lib/python3.7/site-packages/tensorflow/python/eager/function.py in _convert_numpy_inputs(inputs)
   2735   # are eventually passed to ConcreteFunction()._call_flat, which requires
   2736   # expanded composites.
-> 2737   flat_inputs = nest.flatten(inputs, expand_composites=True)
   2738
   2739   # Check for NumPy arrays in arguments and convert them to Tensors.

/opt/conda/lib/python3.7/site-packages/tensorflow/python/util/nest.py in flatten(structure, expand_composites)
    339     return [None]
    340   expand_composites = bool(expand_composites)
--> 341   return _pywrap_utils.Flatten(structure, expand_composites)
    342
    343

/opt/conda/lib/python3.7/site-packages/tensorflow/python/distribute/values.py in _type_spec(self)
    381       return copy.deepcopy(self._type_spec_override)
    382     return PerReplicaSpec(
--> 383         *(type_spec.type_spec_from_value(v) for v in self._values))
    384
    385   @property

/opt/conda/lib/python3.7/site-packages/tensorflow/python/distribute/values.py in <genexpr>(.0)
    381       return copy.deepcopy(self._type_spec_override)
    382     return PerReplicaSpec(
--> 383         *(type_spec.type_spec_from_value(v) for v in self._values))
    384
    385   @property

/opt/conda/lib/python3.7/site-packages/tensorflow/python/framework/type_spec.py in type_spec_from_value(value)
    537       is not supported.
    538   """
--> 539   spec = _type_spec_from_value(value)
    540   if spec is not None:
    541     return spec

/opt/conda/lib/python3.7/site-packages/tensorflow/python/framework/type_spec.py in _type_spec_from_value(value)
    559   if isinstance(value, ops.Tensor):
    560     # Note: we do not include Tensor names when constructing TypeSpecs.
--> 561     return tensor_spec.TensorSpec(value.shape, value.dtype)
    562
    563   if isinstance(value, composite_tensor.CompositeTensor):

/opt/conda/lib/python3.7/site-packages/tensorflow/python/framework/ops.py in shape(self)
   1173         # `_tensor_shape` is declared and defined in the definition of
   1174         # `EagerTensor`, in C.
-> 1175         self._tensor_shape = tensor_shape.TensorShape(self._shape_tuple())
   1176       except core._NotOkStatusException as e:
   1177         six.raise_from(core._status_to_exception(e.code, e.message), None)

InvalidArgumentError: 9 root error(s) found.
  (0) Invalid argument: {{function_node __inference_tpu_function_6371}} Compilation failure: Detected unsupported operations when trying to compile graph cluster_tpu_function_6096887307567101759[] on XLA_TPU_JIT: StatelessRandomUniformInt (No registered 'StatelessRandomUniformInt' OpKernel for XLA_TPU_JIT devices compatible with node {{node local_discriminator/random_crop/stateless_random_uniform}}
     (OpKernel was found, but attributes didn't match) Requested Attributes: T=DT_INT32, Tseed=DT_INT64, dtype=DT_INT32, _device="/device:TPU_REPLICATED_CORE"){{node local_discriminator/random_crop/stateless_random_uniform}}One approach is to outside compile the unsupported ops to run on CPUs by enabling soft placement `tf.config.set_soft_device_placement(True)`. This has a potential performance penalty.
    TPU compilation failed
     [[tpu_compile_succeeded_assert/_9679846132704141549/_5]]
     [[cluster_tpu_function/control_after/_1/_279]]
  (1) Invalid argument: {{function_node __inference_tpu_function_6371}} Compilation failure: Detected unsupported operations when trying to compile graph cluster_tpu_function_6096887307567101759[] on XLA_TPU_JIT: StatelessRandomUniformInt (No registered 'StatelessRandomUniformInt' OpKernel for XLA_TPU_JIT devices compatible with node {{node local_discriminator/random_crop/stateless_random_uniform}}
     (OpKernel was found, but attributes didn't match) Requested Attributes: T=DT_INT32, Tseed=DT_INT64, dtype=DT_INT32, _device="/device:TPU_REPLICATED_CORE"){{node local_discriminator/random_crop/stateless_random_uniform}}One approach is to outside compile the unsupported ops to run on CPUs by enabling soft placement `tf.config.set_soft_device_placement(True)`. This has a potential performance penalty.
    TPU compilation failed
     [[tpu_compile_succeeded_assert/_9679846132704141549/_5]]
     [[tpu_compile_succeeded_assert/_9679846132704141549/_5/_153]]
  (2) Invalid argument: {{function_node __inference_tpu_function_6371}} Compilation failure: Detected unsupported operations when trying to compile graph cluster_tpu_function_6096887307567101759[] on XLA_TPU_JIT: StatelessRandomUniformInt (No registered 'StatelessRandomUniformInt' OpKernel for XLA_TPU_JIT devices compatible with node {{node local_discriminator/random_crop/stateless_random_uniform}}
     (OpKernel was found, but attributes didn't match) Requested Attributes: T=DT_INT32, Tseed=DT_INT64, dtype=DT_INT32, _device="/device:TPU_REPLICATED_CORE"){{node local_discriminator/random_crop/stateless_random_uniform}}One approach is to outside compile the unsupported ops to run on CPUs by enabling soft placement `tf.config.set_soft_device_placement(True)`. This has a potential performance penalty.
    TPU compilation failed
     [[tpu_compile_succeeded_assert/_9679846132704141549/_5]]
     [[tpu_compile_succeeded_assert/_9679846132704141549/_5/_167]]
  (3) Invalid argument: {{function_node __inference_tpu_function_6371}} Compilation failure: Detected unsupported operations when trying to compile graph cluster_tpu_function_6096887307567101759[] on XL ... [truncated]

Please, I need your help to advance on my project


问:
Which AWS service does this IP address range belongs to
We have recently analyzed our AWS data transfers/NAT gateway charges and what we have observed is that we are sending 80% of the traffic to an AMAZON service in this IP address range.

```<code>    {
      "ip_prefix": "3.237.107.0/25",
      "region": "us-east-1",
      "service": "AMAZON",
      "network_border_group": "us-east-1"
    }
</code>```

When looking at AWS public IP address range in this link

https://ip-ranges.amazonaws.com/ip-ranges.json

This just mentions the above range as "AMAZON" but doesn't give many details about it.

Anyway can we know which AWS service falls under this IP address category?

Tried looking at S3/Dynamo DB/RDS/Elastic Cache and other AWS services we were using and this doesn't fall under those services.

Body:
We have recently analyzed our AWS data transfers/NAT gateway charges and what we have observed is that we are sending 80% of the traffic to an AMAZON service in this IP address range.

    {
      "ip_prefix": "3.237.107.0/25",
      "region": "us-east-1",
      "service": "AMAZON",
      "network_border_group": "us-east-1"
    }

When looking at AWS public IP address range in this link

https://ip-ranges.amazonaws.com/ip-ranges.json

This just mentions the above range as "AMAZON" but doesn't give many details about it.

Anyway can we know which AWS service falls under this IP address category?

Tried looking at S3/Dynamo DB/RDS/Elastic Cache and other AWS services we were using and this doesn't fall under those services.


问:
throw new Error('Could not load the default credentials.')
I set up my credentials using a dotenv file and I'm parsing that data so googleAuth accepts it. I tried using that parsed JSON against fileName key, but it needs to be a file, how do I get the file link to dotenv with turning it into JSON as well? Or how do I complete my current code, I'm trying another way and manually inputting the string of keys, id, and email, but it's showing the error "Could not load the default credentials."</p>
```<code>const express = require("express");
const { google } = require("googleapis");
require("dotenv").config();

// let testENV = JSON.parse(process.env.GOOGLE_ENV);
let keys = process.env["GOOGLE_ENV"];
const googleKeys = JSON.parse(keys);
const privateKey = googleKeys["private_key"];
const keyId = googleKeys["private_key_id"];
const email = googleKeys["client_email"];

const app = express();

app.get("/", async (req, res) => {
  const auth = new google.auth.GoogleAuth({
    key: privateKey,
    keyId: keyId,
    email: email,
    scopes: "https://www.googleapis.com/auth/spreadsheets",
  });

  // Create client instance for auth
  const client = await auth.getClient();
});

app.listen(3000, (req, res) => {
  console.log("Running on 3000");
});

</code>```

Body:
I set up my credentials using a dotenv file and I'm parsing that data so googleAuth accepts it. I tried using that parsed JSON against fileName key, but it needs to be a file, how do I get the file link to dotenv with turning it into JSON as well? Or how do I complete my current code, I'm trying another way and manually inputting the string of keys, id, and email, but it's showing the error "Could not load the default credentials."

const express = require("express");
const { google } = require("googleapis");
require("dotenv").config();

// let testENV = JSON.parse(process.env.GOOGLE_ENV);
let keys = process.env["GOOGLE_ENV"];
const googleKeys = JSON.parse(keys);
const privateKey = googleKeys["private_key"];
const keyId = googleKeys["private_key_id"];
const email = googleKeys["client_email"];

const app = express();

app.get("/", async (req, res) => {
  const auth = new google.auth.GoogleAuth({
    key: privateKey,
    keyId: keyId,
    email: email,
    scopes: "https://www.googleapis.com/auth/spreadsheets",
  });

  // Create client instance for auth
  const client = await auth.getClient();
});

app.listen(3000, (req, res) => {
  console.log("Running on 3000");
});


问:
How to separate veins from bleeding areas
I am currently working on an endoscopic image analysis system. The main functionality will be segmentation of the bleeding area.

So far, I have the following snapshot processing plan:

The texture and geometry of bleeding vary over a very wide range, which makes it difficult to use these features for the segmentation task. Therefore, we will use color-based segmentation.

It is not very convenient to determine the color in RGB, so first we will convert the image to HSV format.

Let's manually create a dataset that includes fragments of areas with bleeding, which we use to obtain a distribution reflecting the ratio of the H and S color parameters.

The "pillars" of distributions (H,S) and (H,V) can be divided into subdomains forming clusters. At the segmentation stage, a vector of color parameters (H,S,V) is assigned to each pixel of the image and the color parameters belonging to one of the clusters of the bleeding model is checked. The bleeding area is formed from pixels whose parameters are included in one of the clusters.

So... At this stage, we may have problems with veins and other dark red objects being mistaken for bleeding.

I want to find a solution to this problem that does not use machine learning methods.So far, nothing has occurred to me except that it is possible to somehow apply morphological methods of image processing, but I am not sure about this method.


问:
Error when testing Fragment with Roboelectric
I am writing a test for the class LogoutFragment:

```<code>@Config(manifest=Config.NONE)
@RunWith(AndroidJUnit4::class)
class MyActivityTest {

    lateinit var mainActivity: MainActivity
    lateinit var logoutFragment: LogoutFragment
    @Before
    fun setup() {
        mainActivity = Robolectric.buildActivity(MainActivity::class.java).get()
        logoutFragment = LogoutFragment()
        startFragment(logoutFragment)
    }

    @Test
    fun testContext() {
        assertThat(logoutFragment.m_Context).isNotNull()
    }

    private fun startFragment(fragment: Fragment) {
        val fragmentManager: FragmentManager = mainActivity.supportFragmentManager
        val fragmentTransaction: FragmentTransaction = fragmentManager.beginTransaction()
        fragmentTransaction.add(fragment, null)
        fragmentTransaction.commit()
    }
}
</code>```

When running the test testContext I get an error:
"java.lang.IllegalStateException: FragmentManager has not been attached to a host."

This occurs on the .commit code line in the startFragment() function.

Does anyone have an idea how to solve this?

Thank you!

Body:
I am writing a test for the class LogoutFragment:

@Config(manifest=Config.NONE)
@RunWith(AndroidJUnit4::class)
class MyActivityTest {

    lateinit var mainActivity: MainActivity
    lateinit var logoutFragment: LogoutFragment
    @Before
    fun setup() {
        mainActivity = Robolectric.buildActivity(MainActivity::class.java).get()
        logoutFragment = LogoutFragment()
        startFragment(logoutFragment)
    }

    @Test
    fun testContext() {
        assertThat(logoutFragment.m_Context).isNotNull()
    }

    private fun startFragment(fragment: Fragment) {
        val fragmentManager: FragmentManager = mainActivity.supportFragmentManager
        val fragmentTransaction: FragmentTransaction = fragmentManager.beginTransaction()
        fragmentTransaction.add(fragment, null)
        fragmentTransaction.commit()
    }
}

When running the test testContext I get an error:
"java.lang.IllegalStateException: FragmentManager has not been attached to a host."

This occurs on the .commit code line in the startFragment() function.

Does anyone have an idea how to solve this?

Thank you!


问:
Unable to run default ABP project
I've followed the instructions and created a new solution using command

abp new Acme.BookStore -u blazor-server --tiered --preview

When I try and run the solution i get an error:

AbpException: Could not find the bundle file '/libs/bootstrap/css/bootstrap.css' for the bundle 'Blazor.LeptonXLiteTheme.Global'!

I've tried running abp install-libs but still doesn't work. Any ideas?

Title: Unable to run default ABP project


问:
android SDK version
How can I fix this problem?

Your 1 version code com.fass.vpnn app includes the SDK
com.unity3d.ads:unity-ads, which collects personal or sensitive data,
including but not limited to Advertising ID, Android ID identifiers,
or an SDK that one of your libraries uses . Persistent device
identifiers cannot be linked to other personal and sensitive user data
or resettable device identifiers as described in the User Data Policy.

Starting at midnight (UTC) on January 11, 2023, new app versions
containing SDK versions that do not comply with the User Data Policy
may be blocked from being made available. If the SDK is available from
your provider, you may want to consider upgrading to a
policy-compliant version of this SDK that does not contain the
offending code or removing it from your app.

Depending on your SDK provider, you can downgrade to 4.0.1 and/or
contact your SDK provider to see if a suitable version will be
available later. Google cannot endorse or recommend third-party
software.

ACTION REQUIRED: Install a new compatible version AND disable the
non-compliant version.

Read the User Data policy for more details and learn how to submit an
updated app for review here.

If you've reviewed the policy and think our decision may have been
incorrect, please contact our policy support team.

I've read some users' comments about this, but they didn't work for me.

Title: android SDK version


问:
How to use variable inside "Where" keyword in C#
I want to use string variable inside .where keyword to filter out some data from list or from DbSet

Here is my sample code and it's working fine

```<code>var logdata = DbContext.CampaignLog.Where(o => o.Id == 1));

</code>```

but i want to write the above code like this

```<code>var query = "o => o.Id == 1 ||o.Id == 3";
var logdata = DbContext.CampaignLog.Where(query));
</code>```

or

```<code>List<int> numbers = new List<int>()
{
    1, 2, 4, 8, 16, 32
};
var smallNumbers = numbers.Where(n => n < 10);
</code>```

can i wite something like this

```<code>List<int> numbers = new List<int>()
{
    1, 2, 4, 8, 16, 32
};
var query = "n => n < 10";
var smallNumbers = numbers.Where(query);
</code>```

Body:
I want to use string variable inside .where keyword to filter out some data from list or from DbSet

Here is my sample code and it's working fine

var logdata = DbContext.CampaignLog.Where(o => o.Id == 1));

but i want to write the above code like this

var query = "o => o.Id == 1 ||o.Id == 3";
var logdata = DbContext.CampaignLog.Where(query));

or

List<int> numbers = new List<int>()
{
    1, 2, 4, 8, 16, 32
};
var smallNumbers = numbers.Where(n => n < 10);

can i wite something like this

List<int> numbers = new List<int>()
{
    1, 2, 4, 8, 16, 32
};
var query = "n => n < 10";
var smallNumbers = numbers.Where(query);


问:
VS2022 C++ change configuration type based on startup project?
Is it possible to update a project to change from exe to lib depending on if it is set as the startup project?

ie:

Project: Foo

Project: Foo-Unit-tests

using the Pimpl idiom I'm getting link errors if foo is an .exe. Changing it to .lib resolves everything.

So what I'm aiming for is if it is possible to have it that the:

Project>Properties>Configuration Properties>General>[Configuration Type]: = Static library (.lib)

When project Foo-Unit-tests is the startup project. (FOO = .lib)

IF the project: Foo is the startup project, have it set to Application (.exe) instead.

Is there some command line prompts that could allow for this or some settings that can be configured to do this?


问:
Plotly Map New York City Using R
Plotly creates nice maps where the scope term defines the area. I'm wondering if I can make the map so it only shows New York City?

I've read the documentation on scope (https://plotly.com/python/reference/#layout-geo-scope), and see it does not involve any cities, so maybe someone else has a way to solve this?

```<code>library(plotly)
df <- read.csv('https://raw.githubusercontent.com/plotly/datasets/master/2011_february_us_airport_traffic.csv')

# geo styling
g <- list(
  scope = 'usa',
  projection = list(type = 'albers usa'),
  showland = TRUE,
  landcolor = toRGB("gray95"),
  subunitcolor = toRGB("gray85"),
  countrycolor = toRGB("gray85"),
  countrywidth = 0.5,
  subunitwidth = 0.5
)

fig <- plot_geo(df, lat = ~lat, lon = ~long)
fig <- fig %>% add_markers(
    text = ~paste(airport, city, state, paste("Arrivals:", cnt), sep = "<br />"),
    color = ~cnt, symbol = I("square"), size = I(8), hoverinfo = "text"
  )
fig <- fig %>% colorbar(title = "Incoming flights<br />February 2011")
fig <- fig %>% layout(
    title = 'Most trafficked US airports<br />(Hover for airport)', geo = g
  )

fig
</code>```

Title: Plotly Map New York City Using R

Body:
Plotly creates nice maps where the scope term defines the area. I'm wondering if I can make the map so it only shows New York City?

I've read the documentation on scope (https://plotly.com/python/reference/#layout-geo-scope), and see it does not involve any cities, so maybe someone else has a way to solve this?

library(plotly)
df <- read.csv('https://raw.githubusercontent.com/plotly/datasets/master/2011_february_us_airport_traffic.csv')

# geo styling
g <- list(
  scope = 'usa',
  projection = list(type = 'albers usa'),
  showland = TRUE,
  landcolor = toRGB("gray95"),
  subunitcolor = toRGB("gray85"),
  countrycolor = toRGB("gray85"),
  countrywidth = 0.5,
  subunitwidth = 0.5
)

fig <- plot_geo(df, lat = ~lat, lon = ~long)
fig <- fig %>% add_markers(
    text = ~paste(airport, city, state, paste("Arrivals:", cnt), sep = "
"),
    color = ~cnt, symbol = I("square"), size = I(8), hoverinfo = "text"
  )
fig <- fig %>% colorbar(title = "Incoming flights
February 2011")
fig <- fig %>% layout(
    title = 'Most trafficked US airports
(Hover for airport)', geo = g
  )

fig