public-folders 相关问题


将 YAML 文件注入构造函数

我有这个 YAML 文件 src/main/resources/foo.yml: 酒吧: - 你好 - 世界 巴兹: - 洛雷姆 - ipsum 这个组件: @成分 公共类我的组件{ 公共我的组件(地图 我有这个 YAML 文件 src/main/resources/foo.yml: bar: - hello - world baz: - lorem - ipsum 这个组件: @Component public class MyComponent { public MyComponent(Map<String, List<String>> foo) { // foo.get("bar") } } 使用 Spring Boot 2.7,是否可以将配置按原样(自己的文件,无前缀,无类)注入到构造函数中? 你可以这样做 @Configuration public class MyConfiguration { @Bean public Map<String, Object> foo(@Value("classpath:foo.yaml") Resource yaml) { Yaml yaml = new Yaml(); return yaml.load(yaml.getInputStream()); } } @Component public class MyComponent { public MyComponent(@Qualifier("foo") Map<String, Object> foo) { ... } }


将属性值从父级用户控件传递到子级的 DependencyProperty

如何将属性(SomeProperty)从ParentUserControl上下文传递到ChildUserControl的DependencyProperty(MyDProperty)? 在 XAML 中,它应该是: 如何将 ParentUserControl 上下文中的 property (SomeProperty) 传递到 ChildUserControl 的 DependencyProperty (MyDProperty)? 在XAML中,应该是: 但是,由于某种原因,MyDProperty 永远不会使用 Parent.DataContext.SomeProperty 设置。 就我而言,我正在传递一个操作,但这并不重要。我认为问题出在绑定上。 家长用户控制: public Action RemoveEsl1 => throw new NotImplementedException(); <uc:ChildUserControl Title="ESL 1" RemoveEslAction="{Binding RemoveEsl1}" DataContext="{Binding Esl1}"/> 子用户控件: public static readonly DependencyProperty RemoveEslActionProperty = DependencyProperty.Register(nameof(RemoveEslAction), typeof(Action), typeof(ChildUserControl), new PropertyMetadata(delegate { })); public Action RemoveEslAction { get => (Action)GetValue(RemoveEslActionProperty); set => SetValue(RemoveEslActionProperty, value); } 我在这里找到了各种技巧,但没有一个适合我或有效。 回答我自己的问题(检查 ParentUserControl): 型号: public class RootModel : ViewModelBase { private ParentModel parentModel = new(); public ParentModel ParentModel { get => parentModel; set => RisePropertyChanged(ref parentModel, value); } } public class ParentModel : ViewModelBase { private ChildModel childModel = new(); public ChildModel ChildModel { get => childModel; set => RisePropertyChanged(ref childModel, value); } public string ParentModelProperty => "Correct value from ParentModel"; } public class ChildModel : ViewModelBase { private string childModelProperty = "Wrong default value from ChildModel"; public string ChildModelProperty { get => childModelProperty; set => RisePropertyChanged(ref childModelProperty, value); } } 主窗口: <Window.DataContext> <model:RootModel/> </Window.DataContext> <uc:ParentUserControl DataContext="{Binding ParentModel}"/> 家长用户控件: <uc:ChildUserControl ChildDependency="{Binding DataContext.ParentModelProperty, RelativeSource={RelativeSource AncestorType=UserControl}}" DataContext="{Binding ChildModel}"/> 子用户控件: <StackPanel> <Label Content="Dependency property:"/> <Label Content="{Binding ChildDependency, RelativeSource={RelativeSource AncestorType=UserControl}}"/> <Separator/> <Label Content="Property:"/> <Label Content="{Binding ChildModelProperty}"/> </StackPanel> public partial class ChildUserControl : UserControl { public static readonly DependencyProperty ChildDependencyProperty = DependencyProperty.Register(nameof(ChildDependency), typeof(string), typeof(ChildUserControl), new ("Wrong default DP value from ChildUserControl")); public string ChildDependency { get => (string)GetValue(ChildDependencyProperty); set => SetValue(ChildDependencyProperty, value); } public ChildUserControl() { InitializeComponent(); } } 这就是如何将属性 (SomeProperty) 从 ParentUserControl 上下文传递到 ChildUserControl 的 DependencyProperty (MyDProperty)。


如何检查系统深色模式是否启用

binding.switchh.setOnCheckedChangeListener(新CompoundButton.OnCheckedChangeListener(){ @覆盖 public void onCheckedChanged(CompoundButtoncompoundButton, 布尔检查...


通过更少的 Java API 调用来映射 Google 云端硬盘内容的有效方法

大家好,我有一个代码,用于列出共享驱动器中存在的文件(以便稍后下载并创建相同的文件夹路径) 目前我做这样的事情: 哈希映射 大家好,我有一个代码,用于列出共享驱动器中存在的文件(以便稍后下载并创建相同的文件夹路径) 目前我正在做这样的事情: HashMap<String, Strin> foldersPathToID = new HashMap<>(); //searching all folders first saving their IDs searchAllFoldersRecursive(folderName.trim(), driveId, foldersPathToID); //then listing files in all folders HashMap<String, List<File>> pathFile = new HashMap<>(); for (Entry<String, String> pathFolder : foldersPathToID.entrySet()) { List<File> result = search(Type.FILE, pathFolder.getValue()); if (result.size() > 0) { String targetPathFolder = pathFolder.getKey().trim(); pathFile.putIfAbsent(targetPathFolder, new ArrayList<>()); for (File file : result) { pathFile.get(targetPathFolder).add(file); } } } 递归方法在哪里: private static void searchAllFoldersRecursive(String nameFold, String id, HashMap<String, String> map) throws IOException, RefreshTokenException { map.putIfAbsent(nameFold, id); List<File> result; result = search(Type.FOLDER, id); // dig deeper if (result.size() > 0) { for (File folder : result) { searchAllFoldersRecursive(nameFold + java.io.File.separator + normalizeName(folder.getName()), folder.getId(), map); } } } 搜索功能是: private static List<com.google.api.services.drive.model.File> search(Type type, String folderId) throws IOException, RefreshTokenException { String nextPageToken = "go"; List<File> driveFolders = new ArrayList<>(); com.google.api.services.drive.Drive.Files.List request = service.files() .list() .setQ("'" + folderId + "' in parents and mimeType" + (type == Type.FOLDER ? "=" : "!=") + "'application/vnd.google-apps.folder' and trashed = false") .setPageSize(100).setFields("nextPageToken, files(id, name)"); while (nextPageToken != null && nextPageToken.length() > 0) { try { FileList result = request.execute(); driveFolders.addAll(result.getFiles()); nextPageToken = result.getNextPageToken(); request.setPageToken(nextPageToken); return driveFolders; } catch (TokenResponseException tokenError) { if (tokenError.getDetails().getError().equalsIgnoreCase("invalid_grant")) { log.err("Token no more valid removing it Please retry"); java.io.File cred = new java.io.File("./tokens/StoredCredential"); if (cred.exists()) { cred.delete(); } throw new RefreshTokenException("Creds invalid will retry re allow for the token"); } log.err("Error while geting response with token for folder id : " + folderId, tokenError); nextPageToken = null; } catch (Exception e) { log.err("Error while reading folder id : " + folderId, e); nextPageToken = null; } } return new ArrayList<>(); } 我确信有一种方法可以通过很少的 api 调用(甚至可能是一个调用?)对每个文件(使用文件夹树路径)进行正确的映射,因为在我的版本中,我花了很多时间进行调用 service.files().list().setQ("'" + folderId+ "' in parents and mimeType" + (type == Type.FOLDER ? "=" : "!=") + "'application/vnd.google-apps.folder' and trashed = false").setPageSize(100).setFields("nextPageToken, files(id, name)"); 每个子文件夹至少一次......并且递归搜索所有内容需要很长时间。最后,映射比下载本身花费的时间更多...... 我搜索了文档,也在此处搜索,但没有找到任何内容来列出具有一个库的所有驱动器调用任何想法? 我想使用专用的 java API 来获取共享 GoogleDrive 中的所有文件及其相对路径,但调用次数尽可能少。 提前感谢您的时间和答复 我建议您使用高效的数据结构和逻辑来构建文件夹树并将文件映射到其路径,如下所示 private static void mapDriveContent(String driveId) throws IOException { // HashMap to store folder ID to path mapping HashMap<String, String> idToPath = new HashMap<>(); // HashMap to store files based on their paths HashMap<String, List<File>> pathToFile = new HashMap<>(); // Fetch all files and folders in the drive List<File> allFiles = fetchAllFiles(driveId); // Build folder path mapping and organize files for (File file : allFiles) { String parentId = (file.getParents() != null && !file.getParents().isEmpty()) ? file.getParents().get(0) : null; String path = buildPath(file, parentId, idToPath); if (file.getMimeType().equals("application/vnd.google-apps.folder")) { idToPath.put(file.getId(), path); } else { pathToFile.computeIfAbsent(path, k -> new ArrayList<>()).add(file); } } // Now, pathToFile contains the mapping of paths to files // Your logic to handle these files goes here } private static List<File> fetchAllFiles(String driveId) throws IOException { // Implement fetching all files and folders here // Make sure to handle pagination if necessary // ... } private static String buildPath(File file, String parentId, HashMap<String, String> idToPath) { // Build the file path based on its parent ID and the idToPath mapping // ... }


Chainlink 反应热烈

我从 chainlink 文档运行此代码,但没有获得图像。 函数 requestBytes() public returns (bytes32 requestId) { 地址预言=“


顺风未加载颜色

有简单的html: 公共/index.html: 有简单的html: public/index.html: <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="styles.css"> </head> <body class="text-red-600"> some text </body> css 是从 tailwindcss -i src/styles.css -o public/styles.css 获取的 src/styles.css: @tailwind base; @tailwind components; @tailwind utilities; tailwind.config.js: module.exports = { content: ["./src/**/*.{html,js}"], theme: { extend: {}, }, plugins: [], } <body>标签中的红色不适用。默认的顺风类别是否导入到public/styles.css? Tailwind 配置中的 public/index.html 文件似乎没有覆盖 content 文件。您必须确保使用 Tailwind 类的源代码文件被 content 文件 glob 覆盖,否则 Tailwind 将不会扫描这些文件,也不会为存在的类名生成 CSS 规则。考虑阅读有关配置的文档content。 module.exports = { content: [ "./src/**/*.{html,js}", "./public/index.html", ], theme: { extend: {}, }, plugins: [], }


子控件中的绑定命令?

我有一个 UserControl,用作窗口对话框的“模板”。 它包含一个关闭按钮和一个取消按钮。 我有一个 UserControl,用作窗口对话框的“模板”。 它包含一个关闭按钮和一个取消按钮。 <UserControl x:Class="TombLib.WPF.Controls.WindowControlButtons" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:TombLib.WPF.Controls" mc:Ignorable="d" xmlns:darkUI="clr-namespace:DarkUI.WPF;assembly=DarkUI.WPF" xmlns:vm="clr-namespace:TombLib.WPF.ViewModels" xmlns:sg="clr-namespace:SpacedGridControl;assembly=SpacedGridControl" d:DesignHeight="100" d:DesignWidth="300" x:Name="root"> <StackPanel VerticalAlignment="Center" HorizontalAlignment="Right" Height="Auto" Orientation="Horizontal"> <Button Name="oKButton" Margin="{x:Static darkUI:Defaults.MediumThickness}" Width="100" Height="Auto" Command="{Binding Close}" CommandParameter="{Binding Window}" Content="OK"></Button> <Button Name="cancelButton" Margin="{x:Static darkUI:Defaults.MediumThickness}" Width="100" Height="Auto" Command="{Binding Path=Cancel}" CommandParameter="{Binding Window}" Content="Cancel"></Button> </StackPanel> </UserControl> public partial class WindowControlButtons : UserControl { public static readonly DependencyProperty CancelProperty = DependencyProperty.Register( nameof(Cancel), typeof(ICommand), typeof(WindowControlButtons), new PropertyMetadata(null)); public ICommand Cancel { get { return (ICommand)GetValue(CancelProperty); } set { SetValue(CancelProperty, value); } } public static readonly DependencyProperty CloseProperty = DependencyProperty.Register( nameof(Close), typeof(ICommand), typeof(WindowControlButtons), new PropertyMetadata(null)); public ICommand Close { get { return (ICommand)GetValue(CloseProperty); } set { SetValue(CloseProperty, value); } } public static readonly DependencyProperty WindowParameter = DependencyProperty.Register( nameof(Window), typeof(object), typeof(WindowControlButtons), new PropertyMetadata(null)); public object? Window { get { return GetValue(WindowParameter); } set { SetValue(WindowParameter, value); } } public WindowControlButtons() { InitializeComponent(); } } 我想在以下窗口中使用它: <Window x:Class="TombLib.WPF.Windows.SelectIdWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:TombLib.WPF.Windows" mc:Ignorable="d" xmlns:ctrl="clr-namespace:TombLib.WPF.Controls" xmlns:vm="clr-namespace:TombLib.WPF.ViewModels" xmlns:sg="clr-namespace:SpacedGridControl;assembly=SpacedGridControl" xmlns:darkUI="clr-namespace:DarkUI.WPF;assembly=DarkUI.WPF" Title="SelectIdWindow" Height="100" Width="300" d:DataContext="{d:DesignInstance Type=vm:SelectIdViewModel }" x:Name="Self"> <sg:SpacedGrid Margin="{x:Static darkUI:Defaults.MediumThickness}"> <!-- REDACTED --> <ctrl:WindowControlButtons DataContext="{Binding ElementName=Self}" Window="{Binding ElementName=Self, Mode=OneWay}" Close="{Binding CloseCommand,Mode=OneWay}" Cancel="{Binding CancelCommand,Mode=OneWay}" Height="Auto" Width="Auto" Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2" HorizontalAlignment="Right"/> </sg:SpacedGrid> </Window> public partial class SelectIdWindow : Window { public ICommand? CloseCommand { get; set; } public ICommand? CancelCommand { get; set; } public SelectIdWindow() { CloseCommand = new WindowCloseCommand(); InitializeComponent(); } } public class SelectIdViewModel { public string RequestedId { get; set; } = string.Empty; public IEnumerable<string> TakenIds { get; set;} public SelectIdViewModel(IEnumerable<string> takenIDs) { TakenIds = takenIDs; } } 但是,当我打开窗口时如下: SelectIdWindow w = new SelectIdWindow(); var takenIDs = Entities.Select(kv => kv.Key.Name); w.DataContext = new SelectIdViewModel(takenIDs); w.ShowDialog(); 我在绑定 WindowControlButtons 时收到以下错误: DataContext 显式设置为 Self,它应该代表 Window,而不是 ViewModel。我在这里做错了什么? 绑定错误表明问题出在 Button.ICommand 属性上: 要修复此问题,请在 WindowControlButtons 绑定中添加 ElementName=root,以便绑定到声明的依赖项属性而不是 DataContext: <UserControl x:Class="TombLib.WPF.Controls.WindowControlButtons" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:TombLib.WPF.Controls" mc:Ignorable="d" xmlns:darkUI="clr-namespace:DarkUI.WPF;assembly=DarkUI.WPF" xmlns:vm="clr-namespace:TombLib.WPF.ViewModels" xmlns:sg="clr-namespace:SpacedGridControl;assembly=SpacedGridControl" d:DesignHeight="100" d:DesignWidth="300" x:Name="root"> <StackPanel VerticalAlignment="Center" HorizontalAlignment="Right" Height="Auto" Orientation="Horizontal"> <Button Name="oKButton" ... Command="{Binding Close, ElementName=root}" CommandParameter="{Binding Window, ElementName=root}" Content="OK"/> <Button Name="cancelButton" ... Command="{Binding Path=Cancel, ElementName=root}" CommandParameter="{Binding Window, ElementName=root}" Content="Cancel"/> </StackPanel> </UserControl>


安装Spring Boot执行器

我有一个 SpringBoot 应用程序,其配置在端口 8081 上运行: @豆 public SecurityFilterChain filterChain(HttpSecurity http) 抛出异常 { http.csrf(AbstractHttpConf...


使用 StructureMap 连接不同的实现

我有一个非常简单的通用存储库: 公共接口IRepository 其中 TEntity : EntityObject 其中 TNotFound : TEntity, new() { 列表 我有一个非常简单的通用存储库: public interface IRepository<TEntity, TNotFound> where TEntity : EntityObject where TNotFound : TEntity, new() { IList<TEntity> GetAll(); TEntity With(int id); TEntity Persist(TEntity itemToPersist); void Delete(TEntity itemToDelete); } 我想为 Term 类型的存储库定义一个合约,没有任何特殊行为。所以它看起来像这样: public class TermNotFound : Term { public TermNotFound() : base(String.Empty, String.Empty) { } } public interface ITermRepository : IRepository<Term, TermNotFound> { } 现在为了测试,我想创建通用存储库的内存中实现,所以我有这个(为简洁起见,未完成): public class InMemoryRepository<TEntity, TNotFound> : IRepository<TEntity, TNotFound> where TEntity : EntityObject where TNotFound : TEntity, new() { private IList<TEntity> _repo = new List<TEntity>(); public IList<TEntity> GetAll() { return this._repo; } public TEntity With(int id) { return this._repo.SingleOrDefault(i => i.Id == id) ?? new TNotFound(); } public TEntity Persist(TEntity itemToPersist) { throw new NotImplementedException(); } public void Delete(TEntity itemToDelete) { throw new NotImplementedException(); } } 不难看出我希望它如何工作。对于我的测试,我希望注入通用 InMemoryRepository 实现来创建我的 ITermRepository。 好吧,我无法让 StructureMap 来做这件事。我尝试在扫描仪中使用 WithDefaultConventions 和 ConnectImplementationsToTypesClosing(typeof(IRepository<,>)) 但没有成功。接下来我可以尝试什么? 您的 InMemoryRepository 未实现 ITermRepository 接口。这就是为什么你无法连接它们。 你能用你所拥有的最好的办法就是注射 InMemoryRepository<Term, TermNotFound> 以获得 IRepository<Term, TermNotFound>。 如果你确实需要注入ITermRepository,那么你需要有另一个存储库类继承InMemoryRepository并实现ITermRepository: public class InMemoryTermRepository : InMemoryRepository<Term, TermNotFound>, ITermRepository { } 现在您可以使用以下方法将 ITermRepository 连接到 InMemoryTermRepository: .For<ITermRepository>().Use<InMemoryTermRepository>() 如果您有很多像 ITermRepository 这样的接口,您可以创建一个 StructureMap 约定,将 I...Repository 连接到 InMemory...Repository。默认约定是将 IClass 连接到 Class。


如何比较两个对象属性?

公共类 CellAtt { 私人琴弦品牌; 私人长连载; 私人双价; public CellAtt(字符串品牌,长序列,双倍价格) { this.brand = 品牌; ...


“无法为受信任的根颁发机构构建证书链。”升级到 .NET 8 后

我使用以下代码来配置 Saml2 public static voidConfigureSaml2(此IServiceCollection服务,IConfiguration配置) { 服务.配置(


我应该如何使用多部分文件作为RequestParam来测试这个Java API

我正在尝试在控制器上测试以下API: @PostMapping("/{code}") public ResponseEntity importFichier(@PathVariable("code") 字符串代码...


为什么方法的值在select方法中不会改变?

我有一个从 Postgres 中的序列返回值的方法: public long GetSId(DatabaseFacade d,字符串序列名称) { var result = new NpgsqlParameter(":result", NpgsqlDbType.Integ...


将值从用户控件传递到同一用户控件wpf c#中的另一个?

我有四个用户控件,我尝试将值从用户控件传递到另一个用户控件,这些用户控件存在于同一个用户控件中。 这个 xml 主页面 ` 我有四个用户控件,我尝试将值从用户控件传递到另一个用户控件,这些用户控件存在于同一个用户控件中。 这个 xml 主页面 ` <Grid> <StackPanel Background="#FFF"> <local:mwidget x:Name="mwidget" Loaded="UserControl1_Loaded"/> <local:addemploy x:Name="addemploy" Visibility="Hidden"/> <local:editemploy x:Name="editemploy" Visibility="Hidden" /> </StackPanel> </Grid>` 还有这个代码 ` private void UserControl1_Loaded(object sender, RoutedEventArgs e) { mwidget.ShowUserControl2Requested += OnShowUserControl2Requested; addemploy.ShowUserControl1Requested += OnShowUserControl1Requested; editemploy.ShowUserControl1Requestedd += ShowUserControl1Requestedd; mwidget.ShowUserControl2Requestedd += ShowUserControl1Requesteddd; } private void OnShowUserControl2Requested(object sender, EventArgs e) { addemploy.Visibility = Visibility.Visible; mwidget.Visibility = Visibility.Collapsed; } private void OnShowUserControl1Requested(object sender, EventArgs e) { mwidget.Visibility = Visibility.Visible; addemploy.Visibility = Visibility.Collapsed; } private void ShowUserControl1Requestedd(object sender, EventArgs e) { mwidget.Visibility = Visibility.Visible; editemploy.Visibility = Visibility.Collapsed; } private void ShowUserControl1Requesteddd(object sender, EventArgs e) { editemploy.Visibility = Visibility.Visible; mwidget.Visibility = Visibility.Collapsed; }` 这个代码mwidget ` public partial class mwidget : UserControl { public event EventHandler ShowUserControl2Requested; public event EventHandler ShowUserControl2Requestedd; public mwidget() { InitializeComponent(); } private void add_employ(object sender, RoutedEventArgs e) { ShowUserControl2Requested?.Invoke(this, EventArgs.Empty); } private void edit_employ(object sender, System.Windows.RoutedEventArgs e) { ShowUserControl2Requestedd?.Invoke(this, EventArgs.Empty); } }` 所以我想将值从 mwidget 传递到 editemploy,我尝试了一些解决方案,但不起作用 您需要在 mwidget 和 editemploy 中创建 DependencyPropertys 并将它们相互绑定。 (注意:在下面的示例中,我使用了 OneWayToSource。这可以防止 editemploy 更改 mwidget 中的值。如果您不想这样做,请将其更改为 TwoWay。) m小部件: public static readonly DependencyProperty MyValueProperty = DependencyProperty.Register( nameof(MyValue), typeof(bool), typeof(mwidget)); public bool MyValue { get => (bool)GetValue(MyValueProperty); set => SetValue(MyValueProperty, value); } 编辑雇佣: public static readonly DependencyProperty MyPassedValueProperty = DependencyProperty.Register( nameof(MyPassedValue), typeof(bool), typeof(editemploy)); public bool MyPassedValue { get => (bool)GetValue(MyPassedValueProperty); set => SetValue(MyPassedValueProperty, value); } xaml: <local:mwidget x:Name="mwidget" Loaded="UserControl1_Loaded"/> <local:addemploy x:Name="addemploy" Visibility="Hidden"/> <local:editemploy x:Name="editemploy" Visibility="Hidden" MyPassedValue="{Binding ElementName=mwidget, Path=MyValue, Mode=OneWayToSource}" />


ML.net - CreateTimeSeriesEngine

我正在使用 ML.net 进行时间序列分析项目。在这里我尝试预测欧元兑美元的交易汇率。我从 CSV 文件加载数据并使用内存数据创建 IDataView。 列表 我正在使用 ML.net 进行时间序列分析项目。在这里我尝试预测欧元兑美元的交易汇率。我从 CSV 文件加载数据并使用内存数据创建 IDataView。 List<RateData> infoList = new List<RateData>(); // populate list infoList = FileParser(infoList); IDataView data = mlContext.Data.LoadFromEnumerable<RateData>(infoList); 我设法像这样运行预测估计器 var forecastEstimator = mlContext.Forecasting.ForecastBySsa( outputColumnName: nameof(RatePrediction.CurrentRate), inputColumnName: nameof(RateData.HistoricalRate), windowSize: 14, seriesLength: numRateDataPoints, trainSize: numRateDataPoints, horizon: 1, confidenceLevel: 0.95f ); SsaForecastingTransformer forecaster = forecastEstimator.Fit(RateDataSeries); 然后我尝试创建这样的预测引擎 var ForecastEngine = Forecaster.CreateTimeSeriesEngine(mlContext); 这里我遇到了一些错误。 我的输入和输出类如下: public class RateData { public DateTime TransactionDate { get; set; } public float HistoricalRate { get; set; } } public class RatePrediction { public float CurrentRate; } 我有这样的错误 System.InvalidOperationException: Can't bind the IDataView column 'CurrentRate' of type 'Vector<Single, 1>' to field or property 'CurrentRate' of type 'System.Single'. at Microsoft.ML.Data.TypedCursorable`1..ctor(IHostEnvironment env, IDataView data, Boolean ignoreMissingColumns, InternalSchemaDefinition schemaDefn) at Microsoft.ML.Data.TypedCursorable`1.Create(IHostEnvironment env, IDataView data, Boolean ignoreMissingColumns, SchemaDefinition schemaDefinition) at Microsoft.ML.Transforms.TimeSeries.TimeSeriesPredictionEngine`2.PredictionEngineCore(IHostEnvironment env, InputRow`1 inputRow, IRowToRowMapper mapper, Boolean ignoreMissingColumns, SchemaDefinition outputSchemaDefinition, Action& disposer, IRowReadableAs`1& outputRow) at Microsoft.ML.PredictionEngineBase`2..ctor(IHostEnvironment env, ITransformer transformer, Boolean ignoreMissingColumns, SchemaDefinition inputSchemaDefinition, SchemaDefinition outputSchemaDefinition, Boolean ownsTransformer) at Microsoft.ML.Transforms.TimeSeries.TimeSeriesPredictionEngine`2..ctor(IHostEnvironment env, ITransformer transformer, Boolean ignoreMissingColumns, SchemaDefinition inputSchemaDefinition, SchemaDefinition outputSchemaDefinition) at Microsoft.ML.Transforms.TimeSeries.PredictionFunctionExtensions.CreateTimeSeriesEngine[TSrc,TDst](ITransformer transformer, IHostEnvironment env, Boolean ignoreMissingColumns, SchemaDefinition inputSchemaDefinition, SchemaDefinition outputSchemaDefinition) at USD_EURO_Conversion_rate.TimeSeriesModelHelper.FitAndSaveModel(MLContext mlContext, IDataView RateDataSeries, String outputModelPath) 预测类中的属性需要是float[]类型;向量/数组而不是单个值,例如 public class RatePrediction { public float[] CurrentRate; } 类似于此处的Microsoft 示例。


带有 saml2 sso 的 Springboot:未找到依赖方注册

我有一个简单的 Springboot 3.1.2 应用程序,带有 SAML2,使用 okta 作为身份提供者。 我的安全配置是: @豆 public SecurityFilterChain filterChain(HttpSecurity http, SuezGebruikersServ...


在 C# 中将 Task<T> 转换为 Task<object>,无需 T

我有一个充满扩展方法的静态类,其中每个方法都是异步的并返回一些值 - 像这样: 公共静态类 MyContextExtensions{ 公共静态异步任务 我有一个充满扩展方法的静态类,其中每个方法都是异步的并返回一些值 - 像这样: public static class MyContextExtensions{ public static async Task<bool> SomeFunction(this DbContext myContext){ bool output = false; //...doing stuff with myContext return output; } public static async Task<List<string>> SomeOtherFunction(this DbContext myContext){ List<string> output = new List<string>(); //...doing stuff with myContext return output; } } 我的目标是能够从另一个类中的单个方法调用这些方法中的任何一个,并将其结果作为对象返回。它看起来像这样: public class MyHub: Hub{ public async Task<object> InvokeContextExtension(string methodName){ using(var context = new DbContext()){ //This fails because of invalid cast return await (Task<object>)typeof(MyContextExtensions).GetMethod(methodName).Invoke(null, context); } } } 问题是转换失败。我的困境是我无法将任何类型参数传递给“InvokeContextExtension”方法,因为它是 SignalR 中心的一部分并且由 javascript 调用。在某种程度上,我不关心扩展方法的返回类型,因为它只会序列化为 JSON 并发送回 javascript 客户端。但是,我确实必须将 Invoke 返回的值转换为任务才能使用等待运算符。我必须为该“任务”提供一个通用参数,否则它将把返回类型视为 void。因此,这一切都归结为如何成功地将具有通用参数 T 的任务转换为具有对象通用参数的任务,其中 T 表示扩展方法的输出。 您可以分两步完成 - await使用基类执行任务,然后使用反射或dynamic收获结果: using(var context = new DbContext()) { // Get the task Task task = (Task)typeof(MyContextExtensions).GetMethod(methodName).Invoke(null, context); // Make sure it runs to completion await task.ConfigureAwait(false); // Harvest the result return (object)((dynamic)task).Result; } 这是一个完整的运行示例,它将上述通过反射调用 Task 的技术置于上下文中: class MainClass { public static void Main(string[] args) { var t1 = Task.Run(async () => Console.WriteLine(await Bar("Foo1"))); var t2 = Task.Run(async () => Console.WriteLine(await Bar("Foo2"))); Task.WaitAll(t1, t2); } public static async Task<object> Bar(string name) { Task t = (Task)typeof(MainClass).GetMethod(name).Invoke(null, new object[] { "bar" }); await t.ConfigureAwait(false); return (object)((dynamic)t).Result; } public static Task<string> Foo1(string s) { return Task.FromResult("hello"); } public static Task<bool> Foo2(string s) { return Task.FromResult(true); } } 一般来说,要将 Task<T> 转换为 Task<object>,我会简单地采用简单的连续映射: Task<T> yourTaskT; // .... Task<object> yourTaskObject = yourTaskT.ContinueWith(t => (object) t.Result); (文档链接在这里) 但是,您实际的具体需求是 通过反射调用 Task 并获取其(未知类型)结果 。 为此,您可以参考完整的dasblinkenlight的答案,它应该适合您的具体问题。 我想提供一个实现,恕我直言,这是早期答案的最佳组合: 精确的参数处理 无动态调度 通用扩展方法 给你: /// <summary> /// Casts a <see cref="Task"/> to a <see cref="Task{TResult}"/>. /// This method will throw an <see cref="InvalidCastException"/> if the specified task /// returns a value which is not identity-convertible to <typeparamref name="T"/>. /// </summary> public static async Task<T> Cast<T>(this Task task) { if (task == null) throw new ArgumentNullException(nameof(task)); if (!task.GetType().IsGenericType || task.GetType().GetGenericTypeDefinition() != typeof(Task<>)) throw new ArgumentException("An argument of type 'System.Threading.Tasks.Task`1' was expected"); await task.ConfigureAwait(false); object result = task.GetType().GetProperty(nameof(Task<object>.Result)).GetValue(task); return (T)result; } 您不能将 Task<T> 转换为 Task<object>,因为 Task<T> 不是协变的(也不是逆变的)。最简单的解决方案是使用更多反射: var task = (Task) mi.Invoke (obj, null) ; var result = task.GetType ().GetProperty ("Result").GetValue (task) ; 这很慢且效率低下,但如果不经常执行此代码则可用。顺便说一句,如果您要阻塞等待其结果,那么异步 MakeMyClass1 方法有什么用呢? 另一种可能性是为此目的编写一个扩展方法: public static Task<object> Convert<T>(this Task<T> task) { TaskCompletionSource<object> res = new TaskCompletionSource<object>(); return task.ContinueWith(t => { if (t.IsCanceled) { res.TrySetCanceled(); } else if (t.IsFaulted) { res.TrySetException(t.Exception); } else { res.TrySetResult(t.Result); } return res.Task; } , TaskContinuationOptions.ExecuteSynchronously).Unwrap(); } 它是非阻塞解决方案,将保留任务的原始状态/异常。 最有效的方法是自定义等待者: struct TaskCast<TSource, TDestination> where TSource : TDestination { readonly Task<TSource> task; public TaskCast(Task<TSource> task) { this.task = task; } public Awaiter GetAwaiter() => new Awaiter(task); public struct Awaiter : System.Runtime.CompilerServices.INotifyCompletion { System.Runtime.CompilerServices.TaskAwaiter<TSource> awaiter; public Awaiter(Task<TSource> task) { awaiter = task.GetAwaiter(); } public bool IsCompleted => awaiter.IsCompleted; public TDestination GetResult() => awaiter.GetResult(); public void OnCompleted(Action continuation) => awaiter.OnCompleted(continuation); } } 具有以下用法: Task<...> someTask = ...; await TaskCast<..., object>(someTask); 这种方法的局限性在于结果不是 Task<object> 而是一个可等待的对象。 我根据dasblinkenlight的回答做了一个小小的扩展方法: public static class TaskExtension { public async static Task<T> Cast<T>(this Task task) { if (!task.GetType().IsGenericType) throw new InvalidOperationException(); await task.ConfigureAwait(false); // Harvest the result. Ugly but works return (T)((dynamic)task).Result; } } 用途: Task<Foo> task = ... Task<object> = task.Cast<object>(); 这样您就可以将 T 中的 Task<T> 更改为您想要的任何内容。 对于最佳方法,不使用反射和动态丑陋语法,也不传递泛型类型。我将使用两种扩展方法来实现这个目标。 public static async Task<object> CastToObject<T>([NotNull] this Task<T> task) { return await task.ConfigureAwait(false); } public static async Task<TResult> Cast<TResult>([NotNull] this Task<object> task) { return (TResult) await task.ConfigureAwait(false); } 用途: Task<T1> task ... Task<T2> task2 = task.CastToObject().Cast<T2>(); 这是我的第二种方法,但不推荐: public static async Task<TResult> Cast<TSource, TResult>([NotNull] this Task<TSource> task, TResult dummy = default) { return (TResult)(object) await task.ConfigureAwait(false); } 用途: Task<T1> task ... Task<T2> task2 = task.Cast((T2) default); // Or Task<T2> task2 = task.Cast<T1, T2>(); 这是我的第三种方法,但是不推荐:(类似于第二种) public static async Task<TResult> Cast<TSource, TResult>([NotNull] this Task<TSource> task, Type<TResult> type = null) { return (TResult)(object) await task.ConfigureAwait(false); } // Dummy type class public class Type<T> { } public static class TypeExtension { public static Type<T> ToGeneric<T>(this T source) { return new Type<T>(); } } 用途: Task<T1> task ... Task<T2> task2 = task.Cast(typeof(T2).ToGeneric()); // Or Task<T2> task2 = task.Cast<T1, T2>(); 将 await 与动态/反射调用混合使用并不是一个好主意,因为 await 是一条编译器指令,它会围绕调用的方法生成大量代码,并且使用更多反射来“模拟”编译器工作并没有真正的意义,延续、包装等 因为您需要的是在运行时管理代码,然后忘记在编译时工作的 asyc await 语法糖。重写 SomeFunction 和 SomeOtherFunction 而不使用它们,并在运行时创建的您自己的任务中开始操作。您将得到相同的行为,但代码非常清晰。


macOS 14 中的 FortiClient VPN 白色空白屏幕

FortiClient版本:7.0.9.0360 系统版本:macOS 14 Public Beta 2(包括macOS 13.4) 当我打开 FortiClient VPN-Only(包括完整版)时,会显示白色空白屏幕。 截屏 然后我...


进入该片段后屏幕变白。第二次应用程序停止工作。怎么解决这个问题?

@覆盖 public View onCreateView(LayoutInflater inflater, ViewGroup 容器, 捆绑已保存实例状态) { 上下文= getActivity(); view = inflater.inflate(R.layout.fragment_shor1, 包含...


Laravel POST 方法返回状态:405 不允许在 POST 方法上使用方法

请查找以下信息: NoteController.php 请查找以下信息: NoteController.php <?php namespace App\Http\Controllers; use App\Http\Requests\NoteRequest; use App\Models\Note; use Illuminate\Http\JsonResponse; class NoteController extends Controller { public function index():JsonResponse { $notes = Note::all(); return response()->json($notes, 200); } public function store(NoteRequest $request):JsonResponse { $note = Note::create( $request->all() ); return response()->json([ 'success' => true, 'data' => $note ], 201); } public function show($id):JsonResponse { $note = Note::find($id); return response()->json($note, 200); } public function update(NoteRequest $request, $id):JsonResponse { $note = Note::find($id); $note->update($request->all()); return response()->json([ 'success' => true, 'data' => $note, ], 200); } public function destroy($id):JsonResponse { Note::find($id)->delete(); return response()->json([ 'success' => true ], 200); } } NoteRequest.php <?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class NoteRequest extends FormRequest { public function authorize() { return true; } public function rules() { return [ 'title', 'required|max:255|min:3', 'content', 'nullable|max:255|min:10', ]; } } Note.php(模型) <?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Note extends Model { use HasFactory; protected $guarded = []; } api.php <?php use App\Http\Controllers\NoteController; use Illuminate\Support\Facades\Route; Route::prefix('v1')->group(function () { Route::resource('/note', NoteController::class); }); php artisan 路线:列表 GET|HEAD / ...................................................................................................................... POST _ignition/execute-solution ............... ignition.executeSolution › Spatie\LaravelIgnition › ExecuteSolutionController GET|HEAD _ignition/health-check ........................... ignition.healthCheck › Spatie\LaravelIgnition › HealthCheckController POST _ignition/update-config ........................ ignition.updateConfig › Spatie\LaravelIgnition › UpdateConfigController GET|HEAD api/v1/note .......................................................................... note.index › NoteController@index POST api/v1/note .......................................................................... note.store › NoteController@store GET|HEAD api/v1/note/create ................................................................. note.create › NoteController@create GET|HEAD api/v1/note/{note} ..................................................................... note.show › NoteController@show PUT|PATCH api/v1/note/{note} ................................................................. note.update › NoteController@update DELETE api/v1/note/{note} ............................................................... note.destroy › NoteController@destroy GET|HEAD api/v1/note/{note}/edit ................................................................ note.edit › NoteController@edit GET|HEAD sanctum/csrf-cookie .................................. sanctum.csrf-cookie › Laravel\Sanctum › CsrfCookieController@show 迅雷请求(同邮递员) JSON 请求 { "title": "Hello World", "content": "Lorem ipsum." } 尝试发出 JSON POST 请求并获取状态:405 方法不允许并且我正在使用 php artisan 服务,如果需要,我可以提供 GIT 项目。请告诉我。 您的验证规则看起来不正确。在您的 NoteRequest 类中,规则应该是一个关联数组,其中键是字段名称,值是验证规则。但是,在您的代码中,规则被定义为以逗号分隔的字符串列表。这可能会导致验证失败并返回 405 Method Not allowed 错误。 public function rules() { return [ 'title' => 'required|max:255|min:3', 'content' => 'nullable|max:255|min:10', ]; }


.NET MAUI:自定义Shell TitleView并绑定到当前页面标题

我想用我自己的自定义布局替换默认的 Shell 标头,如下所示: 我想用我自己的自定义布局替换默认的 Shell 标头,如下所示: <?xml version="1.0" encoding="UTF-8" ?> <Shell x:Class="MyNamespace.App.AppShell" xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:MyNamespace.App" xmlns:pages="clr-namespace:MyNamespace.App.Pages" BindingContext="{x:Static local:MainView.Instance}" Shell.FlyoutBehavior="{Binding ShellFlyoutType}" x:Name="shellMain"> <Shell.TitleView> <Grid ColumnDefinitions="*,200"> <Label BindingContext="{x:Reference shellMain}" Text="{Binding Path=CurrentPage.Title, Mode=OneWay}" FontSize="Large" TextColor="White" /> <ActivityIndicator IsRunning="{Binding IsBusy}" Color="Orange" Grid.Column="1" HorizontalOptions="End" /> </Grid> </Shell.TitleView> <ShellContent Title=" Login" ContentTemplate="{DataTemplate local:MainPage}" Route="login" FlyoutItemIsVisible="False" /> <ShellContent Title="Dashboard" ContentTemplate="{DataTemplate pages:DashboardPage}" Route="dashboard" /> </Shell> 我无法绑定当前页面标题。 我的 AppShell.xaml Shell 声明如下 <Shell ... x:Name="shellMain"> 作为替代方案,您可以在 OnNaviged 方法中设置 titleview : 在 AppShell.xaml 中,定义标签的名称 <Shell.TitleView> <Grid ColumnDefinitions="*,200"> <Label BindingContext="{x:Reference shellMain}" x:Name="mylabel" FontSize="Large" TextColor="White" /> <ActivityIndicator IsRunning="{Binding IsBusy}" Color="Orange" Grid.Column="1" HorizontalOptions="End" /> </Grid> </Shell.TitleView> 在AppShell.xaml.cs中,重写OnNaviged方法,获取当前项目 protected override void OnNavigated(ShellNavigatedEventArgs args) { base.OnNavigated(args); var shellItem = Shell.Current?.CurrentItem; string title = shellItem?.Title; int iterationCount = 0; while (shellItem != null && title == null) { title = shellItem.Title; shellItem = shellItem.CurrentItem; if (iterationCount > 10) break; // max nesting reached iterationCount++; } myLabel.Text = title; } 希望它对你有用。 我正在尝试同样的方法来修改 TitleView 的外观。它可以在 iOS 上运行,尽管那里还有另一个错误。但在 Android 上我遇到了同样的问题。在前进导航中,它会更新标题,但当您按后退按钮时,标题不会更新。我已经打开了一个问题并添加了一个存储库。 https://github.com/dotnet/maui/issues/12416#issuecomment-1372627514 还有其他方法可以修改TitleView的外观吗? 我使用视图模型开发了这个解决方法,主要不是为了提供 MVVM 解决方案,而是因为其他建议的答案对我不起作用。 (我怀疑 Liqun Shen 2 月 15 日针对他自己的问题的评论中的建议会起作用。但我没有注意到这一点,直到我自己修复)。 当前页面的标题保存在可由 shell 的视图模型和每个内容页面的视图模型访问的类中: public class ServiceHelper { private static ServiceHelper? _default; public static ServiceHelper Default => _default ??= new ServiceHelper(); internal string CurrentPageTitle { get; set; } = string.Empty; } shell 中每个内容页面的视图模型提供其页面标题。为了促进这一点,大部分工作都是由基本视图模型完成的,它们都是从该模型派生而来的: public abstract class ViewModelBase(string title) : ObservableObject { private ServiceHelper? _serviceHelper; public string Title { get; } = title; internal ServiceHelper ServiceHelper { get => _serviceHelper ??= ServiceHelper.Default; set => _serviceHelper = value; // For unit testing. } public virtual void OnAppearing() { ServiceHelper.CurrentPageTitle = Title; } } 每个 shell 内容页面视图模型只需要让其基础视图模型知道它的标题: public class LocationsViewModel : ViewModelBase { public LocationsViewModel() : base("Locations") { } } 每个 shell 内容页面都需要在其视图模型中触发所需的事件响应方法: public partial class LocationsPage : ContentPage { private LocationsViewModel? _viewModel; public LocationsPage() { InitializeComponent(); } private LocationsViewModel ViewModel => _viewModel ??= (LocationsViewModel)BindingContext; protected override void OnAppearing() { base.OnAppearing(); ViewModel.OnAppearing(); } } Shell 的视图模型为标题栏提供当前页面的标题: public class AppShellViewModel() : ViewModelBase(Global.ApplicationTitle) { private string _currentPageTitle = string.Empty; public string CurrentPageTitle { get => _currentPageTitle; set { _currentPageTitle = value; OnPropertyChanged(); } } public void OnNavigated() { CurrentPageTitle = ServiceHelper.CurrentPageTitle; } } Shell 需要在其视图模型中触发所需的事件响应方法: public partial class AppShell : Shell { private AppShellViewModel? _viewModel; public AppShell() { InitializeComponent(); } private AppShellViewModel ViewModel => _viewModel ??= (AppShellViewModel)BindingContext; protected override void OnNavigated(ShellNavigatedEventArgs args) { base.OnNavigated(args); ViewModel.OnNavigated(); } } 最后,Shell 的 XAML 在标题栏/导航栏上显示由 Shell 视图模型提供的当前页面的标题: <Shell.TitleView> <HorizontalStackLayout VerticalOptions="Fill"> <Image Source="falcon_svg_repo_com.png" HeightRequest="50"/> <Label x:Name="CurrentPageTitleLabel" Text="{Binding CurrentPageTitle}" FontSize="24" Margin="10,0" VerticalTextAlignment="Center"/> </HorizontalStackLayout> </Shell.TitleView>


Java 和 Xerces:找不到属性 XMLConstants.ACCESS_EXTERNAL_DTD

我在这个博客上查找了类似的帖子,但找不到我的问题的答案,所以我决定寻求帮助。 我用 Java 编写了这个简单的函数: public void open(InputStream stream) 抛出


AnimationSet 未按预期执行顺序动画

如果我手动执行多个连续动画。它按预期工作。这是我的可行代码 扩展.xml 如果我手动执行多个连续动画。它按预期工作。这是我的可行代码 scale_up.xml <?xml version="1.0" encoding="utf-8"?> <scale xmlns:android="http://schemas.android.com/apk/res/android" android:fromXScale="1.0" android:fromYScale="1.0" android:toXScale="1.1" android:toYScale="1.1" android:pivotX="50%" android:pivotY="50%" android:fillAfter="true" android:interpolator="@android:anim/decelerate_interpolator" android:duration="@android:integer/config_shortAnimTime" /> scale_down.xml <?xml version="1.0" encoding="utf-8"?> <scale xmlns:android="http://schemas.android.com/apk/res/android" android:fromXScale="1.1" android:fromYScale="1.1" android:toXScale="1.0" android:toYScale="1.0" android:pivotX="50%" android:pivotY="50%" android:fillAfter="true" android:interpolator="@android:anim/decelerate_interpolator" android:duration="@android:integer/config_shortAnimTime" /> 手动执行连续动画 public void startAnimation(Button button) { // Define the scale up animation Animation scaleUpAnimation = AnimationUtils.loadAnimation(this, R.anim.scale_up); // Define the scale down animation Animation scaleDownAnimation = AnimationUtils.loadAnimation(this, R.anim.scale_down); scaleUpAnimation.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { button.startAnimation(scaleDownAnimation); } @Override public void onAnimationRepeat(Animation animation) { } }); button.startAnimation(scaleUpAnimation); } 结果 但是,如果我尝试使用 AnimationSet 替换上述代码,动画结果就会损坏。 public void startAnimation(Button button) { // Define the scale up animation Animation scaleUpAnimation = AnimationUtils.loadAnimation(this, R.anim.scale_up); // Define the scale down animation Animation scaleDownAnimation = AnimationUtils.loadAnimation(this, R.anim.scale_down); // Create an AnimationSet to combine both animations // (It makes no difference whether I am using true or false) AnimationSet animationSet = new AnimationSet(true); animationSet.addAnimation(scaleUpAnimation); animationSet.addAnimation(scaleDownAnimation); // Apply the animation to the button button.startAnimation(animationSet); } 使用AnimationSet的结果(动画不流畅) 我可以知道为什么AnimationSet不起作用吗?谢谢。 我们需要使用setStartOffset来延迟第二个动画的执行。这是解决上述问题的完整代码片段。 public void startAnimation(Button button) { int config_shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime); // Define the scale up animation ScaleAnimation scaleUpAnimation = new ScaleAnimation( 1f, 1.02f, 1f, 1.02f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f ); scaleUpAnimation.setInterpolator(new DecelerateInterpolator()); scaleUpAnimation.setDuration(config_shortAnimTime); scaleUpAnimation.setFillAfter(true); // Define the scale down animation ScaleAnimation scaleDownAnimation = new ScaleAnimation( 1.02f, 1f, 1.02f, 1f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f ); scaleDownAnimation.setInterpolator(new AccelerateInterpolator()); scaleDownAnimation.setDuration(config_shortAnimTime); scaleDownAnimation.setFillAfter(true); scaleDownAnimation.setStartOffset(scaleUpAnimation.getDuration()); // Create an AnimationSet to combine both animations AnimationSet animationSet = new AnimationSet(false); animationSet.addAnimation(scaleUpAnimation); animationSet.addAnimation(scaleDownAnimation); // Apply the animation to the button button.startAnimation(animationSet); }


MVC ASP.NET Core Identity,创建登录、注册操作。 AuthController

公共类AuthController:控制器 { SignInManager _signInManager { 获取; } UserManager _userManager { 获取; } 角色管理器 public class AuthController : Controller { SignInManager<AppUser> _signInManager { get; } UserManager<AppUser> _userManager { get; } RoleManager<IdentityRole> _roleManager { get; } public AuthController(SignInManager<AppUser> signInManager, UserManager<AppUser> userManager, RoleManager<IdentityRole> roleManager) { _signInManager = signInManager; _userManager = userManager; _roleManager = roleManager; } public IActionResult Login() { return View(); } [HttpPost] public async Task<IActionResult> Login(string? returnUrl,LoginVM vm) { AppUser user; if (!ModelState.IsValid) { return View(vm); } if (vm.UsernameOrEmail.Contains("@")) { user = await _userManager.FindByEmailAsync(vm.UsernameOrEmail); } else { user = await _userManager.FindByNameAsync(vm.UsernameOrEmail); } if (user == null) { ModelState.AddModelError("", "Username or password is wrong"); return View(vm); } var result = await _signInManager.PasswordSignInAsync(user, vm.Password, vm.IsRemember, true); if (!result.Succeeded) { if (result.IsLockedOut) { ModelState.AddModelError("", "Too many attempts wait until " + DateTime.Parse(user.LockoutEnd.ToString()).ToString("HH:mm")); } else { ModelState.AddModelError("", "Username or password is wrong"); } return View(vm); } if (returnUrl != null) { return LocalRedirect(returnUrl); } return RedirectToAction("Index","Home"); } public IActionResult Register() { return View(); } [HttpPost] public async Task<IActionResult> Register(RegisterVM vm) { if (!ModelState.IsValid) { return View(vm); } var user = new AppUser { Fullname = vm.Fullname, Email = vm.Email, UserName = vm.Username }; var result = await _userManager.CreateAsync(user, vm.Password); if (!result.Succeeded) { foreach (var error in result.Errors) { ModelState.AddModelError("", error.Description); } return View(vm); } var roleResult = await _userManager.AddToRoleAsync(user, Roles.Member.ToString()); if (!roleResult.Succeeded) { ModelState.AddModelError("", "Something went wrong. Please contact admin"); return View(vm); } return View(); } public async Task<IActionResult> Logout() { await _signInManager.SignOutAsync(); return RedirectToAction("Index", "Home"); } public async Task<bool> CreateRoles() { foreach (var item in Enum.GetValues(typeof(Roles))) { if (!await _roleManager.RoleExistsAsync(item.ToString())) { var result = await _roleManager.CreateAsync(new IdentityRole { Name = item.ToString() }); if (!result.Succeeded) { return false; } } } return true; } } } 所以,我在代码中搞乱了登录、注册和注销,现在这个 RoleManager 的事情让我摸不着头脑。我只是想为我的管理员用户提供一些额外的权力,但我有点不知道该怎么做。如果您能用简单的语言解释步骤或需要进行哪些更改来帮助我,那就太棒了。 我的目标是让管理员用户在我的系统中体验更好,您对此的建议非常有用。尝试了解 RoleManager 的事情以及如何为我的管理员用户提供更多能力。您直接的帮助可能会对我解决这个问题产生很大的影响! 定义管理员角色 创建管理员用户 更新注册流程: var roleResult =等待_userManager.AddToRoleAsync(用户,vm.IsAdmin? Roles.Admin.ToString() : Roles.Member.ToString()); 使用管理员角色: [授权(角色=“管理员”)] 公共 IActionResult AdminDashboard() { // 特定于管理的逻辑 } 5.提升管理能力: if (User.IsInRole("管理员")) { // 特定于管理的逻辑 } 中间件配置: services.AddIdentity() .AddRoles() .AddEntityFrameworkStores(); 7.创建角色方法: 公共无效配置(IApplicationBuilder 应用程序,IHostingEnvironment env) { // 其他中间件配置 // Create roles during application startup var authController = new AuthController(/* inject your dependencies here */); authController.CreateRoles().GetAwaiter().GetResult(); }


声明一个带有泛型的函数,用作查找映射中的值

我做错了什么,但不确定是什么。 尝试制作一个查找地图,为我提供可以调用的功能。 简单演示一下问题: java public class aa { /** 没关系...


为什么我在GWT中无法隐藏UiBinder中的DialogBox?

在 Test.ui.xml 中 测试 一些小部件.. 在Test.ui.xml <g:DialogBox ui:field="wishlistDialogBox" autoHide="true"> <g:caption>Test</g:caption> <g:HTMLPanel> some widgets..</g:HTMLPanel> </g:DialogBox> 运行后,应用程序仍然显示DialogBox,所以我尝试在TestView.java中为“wishlistDialogBox”设置隐藏,但没有成功。 @UiField DialogBox wishlistDialogBox; @Inject public TestView(final Binder binder) { widget = binder.createAndBindUi(this); wishlistDialogBox.hide(); } 然后我在TestPresenter.java中为它设置了隐藏,但仍然不起作用 @Override protected void onBind() { super.onBind(); getView().getWishlistDialogBox().hide(); } 怎么了,古德尔根本没有解释。 另外,DialogBox如何重复使用? 当谈论将它们添加到 DOM 时,DialogBox(以及一般的 PopupPanel)不像任何其他小部件那样工作。您永远不应该像以前那样将它们直接附加到它(即 panel.add(yourDialogBox) 或在 UiBinder XML 文件中)。相反,您应该创建它们,然后简单地调用 hide()/show() 以及类似的方法,以使其显示/隐藏(即,在 DOM 的末尾附加/分离)。 对我有用的是与任何其他小部件分开创建一个对话框。所以它有自己的 Java 文件和自己的 ui.xml 文件: UiBinder xml文件: <ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder" xmlns:g="urn:import:com.google.gwt.user.client.ui"> <g:DialogBox ui:field="dialog"> <g:caption>My Dialog</g:caption> <g:HTMLPanel> <g:Button ui:field="closeButton" text="close" /> </g:HTMLPanel> </g:DialogBox> </ui:UiBinder> Java 文件: public class MyDialog { // here you do not inherit anything private static MyDialogUiBinder uiBinder = GWT.create(MyDialogUiBinder.class); interface MyDialogUiBinder extends UiBinder<Widget, MyDialog> { } @UiField DialogBox dialog; @UiField Button closeButton; public MyDialog() { // make cast to DialogBox dialog = (DialogBox) (uiBinder.createAndBindUi(this)); } public void hide() { dialog.hide(); } public void show() { dialog.center(); } @UiHandler("closeButton") public void onClick(ClickEvent event) { hide(); } } 最后我想出了一个办法,那就是把DialogBox放到一个看不见的HTMLPanel <g:HTMLPanel visible="false"> <g:DialogBox ui:field="wishlistDialogBox" autoHide="true"> <g:caption>Test</g:caption> <g:HTMLPanel> some widgets..</g:HTMLPanel> </g:DialogBox> </g:HTMLPanel> 然后像往常一样调用 show & hide DialogBox,即使 DialogBox 被包裹在一个看不见的 DialogBox 中,它也会显示 HTMLPanel。 getView().getWishlistDialogBox().show();


wkhtmltopdf 文档在开发与生产中的生成方式不同

以下用于生成 PDF 的布局设置为使用 Rails 应用程序的 asset/public 目录中的 css 文件,因为 wicked-pdf gem 需要静态链接。它会根据每个环境进行调整...


如何获取应用程序的屏幕空间或 MAUI 中顶部和底部栏的高度?

我在计算某些项目的位置时遇到问题,以及它们是否在 MAUI 的屏幕上可见,使用如下函数 public Point GetScreenCoords(VisualElement视图) { var 结果 = 新...


为什么FormData会导致400错误请求?

更新: 一些奇怪的行为。如果我发布到控制器,它就会工作并且我会获取文件和数据。但是,如果我发布到页面本身(Razor 代码后面) public void OnPost(...) 我收到 400 错误。是


资源提供的整数在运行时出现乱码

在我的 Android 应用程序中,我创建了文件 app/src/main/res/values/integers.xml: 在我的 Android 应用程序中,我创建了文件 app/src/main/res/values/integers.xml: <?xml version="1.0" encoding="utf-8"?> <resources> <integer name="server_port">8080</integer> </resources> 然后我就有了 public class MyApplication extends Application { final MyServer server = new MyServer(R.integer.server_port); } 但是,当应用程序启动时,日志语句显示该值(即 R.integer.server_port)为 2131296322。 为什么数值会出现乱码?这不是整数资源应该如何实现的吗? R.integer.server_port 给出整数的资源 ID,而不是整数本身。为了获得实际的整数,你必须做getResources().getInteger(R.integer.server_port)。但是,这需要对原始代码进行一些修改,因为在实例化 MyApplication 时尚未设置资源。相反,你可以这样做 public class MyApplication extends Application { MyServer server; @Override public void onCreate() { super.onCreate(); server = new MyServer(getResources().getInteger(R.integer.server_port)); } }


访问 ExpandoObject 中的动态视图

我有以下方法来创建这个 ExpandoObject: List 示例 = new List(); foreach(费率中的变量率) { varrateObject = new ExpandoObject() as IDictionar... 我有以下方法来创建这个ExpandoObject: List<object> example = new List<object>(); foreach (var rate in rates) { var rateObject = new ExpandoObject() as IDictionary<string, object>; rateObject["Id"] = rate.Id; rateObject["RateType"] = rate.RateType; rateObject["Units"] = rate.R6Item.Unit.Symbol; rateObject["Schedule"] = rate.R6Item.Schedule.Description; rateObject["R6Code"] = rate.R6Item.Code; rateObject["R6Description"] = rate.R6Item.Description; rateObject["R7Code"] = rate.R7Item.Code; rateObject["R7Description"] = rate.R7Item.Description; rateObject["DICODE"] = rate.R6Item.Schedule.Discipline.Code; foreach (var currency in rate.Project.ProjectCurrencies) { rateObject[currency.Currency.Name] = currency.Currency.Name; } example.Add(rateObject); } 现在,当我展开示例对象时,它看起来像这样: 如果我进一步扩展,就像这样: 现在我想要的数据是如何在动态视图中显示的,有没有办法能够访问它?并有与 ExpandoObject 的动态视图相同的示例? 您肯定可以做很多事情来增强您的调试体验。这是我的快速尝试: 我必须使用组合来扩展密封类ExpandoObject,其属性为: class MyExpando { [DebuggerBrowsable(DebuggerBrowsableState.Never)] public ExpandoObject Value { get; } = new(); [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public List<KeyValuePair<string, object?>> Properties => Value.ToList(); public void Add(string key, object value) => ((IDictionary<string, object?>)Value)[key] = value; public override string ToString() => string.Join(", ", Value.Select(o => $"{o.Key}={o.Value}")); } 有: 覆盖显示集合时使用的ToString()方法, 隐藏在调试器属性 Value 中以访问 ExpandoObject, 属性 Properties 用于在调试器 KeyValuePair 条目中可视化。


访问 Expando 对象内的动态视图

我有以下方法来创建这个expandoObject: List 示例 = new List(); foreach(费率中的变量率) { var 速率对象 = 新 我有以下方法来创建这个expandoObject: List<object> example = new List<object>(); foreach (var rate in rates) { var rateObject = new ExpandoObject() as IDictionary<string, object>; rateObject["Id"] = rate.Id; rateObject["RateType"] = rate.RateType; rateObject["Units"] = rate.R6Item.Unit.Symbol; rateObject["Schedule"] = rate.R6Item.Schedule.Description; rateObject["R6Code"] = rate.R6Item.Code; rateObject["R6Description"] = rate.R6Item.Description; rateObject["R7Code"] = rate.R7Item.Code; rateObject["R7Description"] = rate.R7Item.Description; rateObject["DICODE"] = rate.R6Item.Schedule.Discipline.Code; foreach (var currency in rate.Project.ProjectCurrencies) { rateObject[currency.Currency.Name] = currency.Currency.Name; } example.Add(rateObject); } 现在,当我展开示例对象时,它看起来像这样: 如果我进一步扩展,就像这样: 现在我想要的数据是如何在动态视图中显示的,有没有办法能够访问它?并有与 ExpandoObject 的动态视图相同的示例吗? 您肯定可以做很多事情来增强您的调试体验。这是我的快速尝试: 我必须使用组合来扩展密封类ExpandoObject,其属性为: class MyExpando { [DebuggerBrowsable(DebuggerBrowsableState.Never)] public ExpandoObject Value { get; } = new(); [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public List<KeyValuePair<string, object?>> Properties => Value.ToList(); public void Add(string key, object value) => ((IDictionary<string, object?>)Value)[key] = value; public override string ToString() => string.Join(", ", Value.Select(o => $"{o.Key}={o.Value}")); } 有: 覆盖显示集合时使用的ToString()方法, 隐藏在调试器属性 Value 中以访问 ExpandoObject, 属性 Properties 用于在调试器 KeyValuePair 条目中可视化和编辑。


Velocity 在 Spring Boot 中找不到模板资源

我使用 Velocity 模板引擎在我的 Spring boot 应用程序中使用电子邮件模板发送电子邮件实用程序。 当前的代码如下所示。 pom.xml: 我正在使用 Velocity 模板引擎在我的 Spring boot 应用程序中使用电子邮件模板发送电子邮件实用程序。 当前代码如下所示。 pom.xml: <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity</artifactId> <version>1.7</version> </dependency> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-tools</artifactId> <version>2.0</version> </dependency> 速度引擎 bean 配置: @Configuration public class VelocityConfig { @Bean public VelocityEngine velocityEngine() { VelocityEngine ve = new VelocityEngine(); ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName()); ve.init(); return ve; } } 电子邮件模板放置在 src/main/resources/email-templates/summary-email.vm <!DOCTYPE html> <head> <title>Summary</title> </head> <body> <h1>Claims Summary</h1> </body> </html> 放置在以下目录中: src ├── main │ ├── java │ │ └── com │ │ └── packageNameioot │ │ └── SpringBootApplication.java │ ├── resources │ │ ├── email-templates │ │ │ └── summary-email.vm │ │ └── application.properties 使用模板发送电子邮件的服务类: @Slf4j @Service @RequiredArgsConstructor public class EmailSummaryService { private final EmailConnector connector; private final VelocityEngine velocityEngine; public Mono<Void> sendFinanceClaimsRunEmailSummary(FinancePeriodRunEntity periodRunEntity, int successCount, int errorCount) { EmailDto emailDto = EmailDto.builder() .recipients(Set.of("[email protected]")) .subject("Claims summary") .body(createEmailBody()) .html(true) .build(); return connector.submitEmailRequest(emailDto); } private String createEmailBody() { VelocityContext context = new VelocityContext(); Template template = velocityEngine.getTemplate("email-templates/summary-email.vm"); StringWriter writer = new StringWriter(); template.merge(context, writer); return writer.toString(); } } 但是Velocity无法定位模板,出现以下错误。 ERROR velocity:96 - ResourceManager : unable to find resource 'email-templates/summary-email.vm' in any resource loader. org.apache.velocity.exception.ResourceNotFoundException: Unable to find resource 'email-templates/summary-email.vm' 属性应该这样设置: VelocityEngine ve = new VelocityEngine(); ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); ve.setProperty("resource.loader.classpath.class", ClasspathResourceLoader.class.getName()); 根据 Apache Velocity Engine 文档。


.NET MAUI、ios UseSafeArea 不工作 StackLayout、VerticalStackLayout 和 Grid

<?xml version="1.0" encoding="utf-8" ?> <ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="Test.Views.Activities.ActivityMapList" xmlns:maps="clr-namespace:Microsoft.Maui.Controls.Maps;assembly=Microsoft.Maui.Controls.Maps" xmlns:sensors="clr-namespace:Microsoft.Maui.Devices.Sensors;assembly=Microsoft.Maui.Essentials" xmlns:ios="clr-namespace:Microsoft.Maui.Controls.PlatformConfiguration.iOSSpecific;assembly=Microsoft.Maui.Controls" ios:Page.UseSafeArea="False" Shell.NavBarIsVisible="False" Style="{StaticResource Key=DefaultPage}"> <ContentPage.Content> <StackLayout> <maps:Map VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand"> <x:Arguments> <MapSpan> <x:Arguments> <sensors:Location> <x:Arguments> <x:Double>36.9628066</x:Double> <x:Double>-122.0194722</x:Double> </x:Arguments> </sensors:Location> <x:Double>0.01</x:Double> <x:Double>0.01</x:Double> </x:Arguments> </MapSpan> </x:Arguments> </maps:Map> </StackLayout> </ContentPage.Content> </ContentPage> StackLayout 或 Grid 内的地图控件,iOS 的 SafeArea 为 false,如图所示。 你有什么解决办法吗? 我需要在地图上使用网格或堆栈布局 默认情况下.NET MAUI 将考虑安全区域。所以使用特定于平台的UseSafeArea就是禁用安全区域。目前,将 UseSafeArea 设置为 false 不会改变行为(尽管应该如此),这是一个错误。另请参阅 MAUI github 上的问题:https://github.com/dotnet/maui/issues/5856 您还可以设置 IgnoreSafeArea 属性来实现相同的目的。但是,它不再在 .NET 7 中工作,请参阅以下问题:https://github.com/dotnet/maui/issues/12823 要解决您的问题,您需要将 IgnoreSafeArea="True" 添加到您的 Grid 或 StackLayout 并将 ios:Page.UseSafeArea="False" 添加到您的页面。这应该不是必需的,但这是对我有用的解决方法。 有关在 iOS 上禁用安全区域的文档可以在此处找到:https://learn.microsoft.com/en-us/dotnet/maui/ios/platform-specifics/page-safe-area-layout?view=net-毛伊岛-7.0 您可以设置 Page Padding 值来实现。在OnAppearing方法中,设置页面的safeInsets,如下代码: protected override void OnAppearing() { base.OnAppearing(); DeviceSafeInsetsService d = new DeviceSafeInsetsService(); double topArea = d.GetSafeAreaTop(); double bottomArea = d.GetSafeAreaBottom(); var safeInsets = On<iOS>().SafeAreaInsets(); safeInsets.Top = -topArea; safeInsets.Bottom = -bottomArea; Padding = safeInsets; } 要获取 topArea 和 bottomArea 值,您应该编写平台代码。答案末尾附有有关此内容的更详细教程。 首先你可以在Project文件夹中生成一个新的类文件并将其更改为部分类。生成两个部分方法。 public partial class DeviceSafeInsetsService { public partial double GetSafeAreaTop(); public partial double GetSafeAreaBottom(); } 然后在iOS平台生成部分文件并实现。该文件位于 Project/Platform/iOS 文件夹中,我想提一下的是,该文件是一个部分文件,因此命名空间应与上面的文件相同。生成此文件时,请删除命名空间中的 .Platforms.iOS 后缀。 public partial class DeviceSafeInsetsService { public partial double GetSafeAreaBottom() { if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0)) { UIWindow window = UIApplication.SharedApplication.Delegate.GetWindow(); var bottomPadding = window.SafeAreaInsets.Bottom; return bottomPadding; } return 0; } public partial double GetSafeAreaTop() { if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0)) { UIWindow window = UIApplication.SharedApplication.Delegate.GetWindow(); var TopPadding = window.SafeAreaInsets.Top; return TopPadding; } return 0; } } 更多信息,您可以参考如何在.NET MAUI中编写特定于平台的代码和MauiPlatformCode示例代码 希望它对你有用。


如何在 Xamarin Forms 中缩放 WebView?

我无法缩放 Xamarin.Forms 中的 Web 视图。下面是代码,请有人帮助我。谢谢 我无法缩放 Xamarin.Forms 中的 Web 视图。下面是代码,请有人帮助我。谢谢你 <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="highchart.MainPage"> <ScrollView> <WebView VerticalOptions="FillAndExpand" WidthRequest="80" HorizontalOptions="FillAndExpand"> <WebView.Source WebView.EnableZoomControls="true" WebView.ScalesPageToFit = "true"> <HtmlWebViewSource x:Name="HighChart"/> </WebView.Source> </WebView> </ScrollView> </ContentPage> 针对 Android 特定(在共享项目 [FORMS] 内) XAML 解决方案: <ContentPage ... xmlns:android="clr-namespace:Xamarin.Forms.PlatformConfiguration.AndroidSpecific;assembly=Xamarin.Forms.Core"> <WebView Source="https://www.xamarin.com" android:WebView.EnableZoomControls="true" android:WebView.DisplayZoomControls="true" /> C# 解决方案: using Xamarin.Forms.PlatformConfiguration; using Xamarin.Forms.PlatformConfiguration.AndroidSpecific; ... WebView.On<Android>().EnableZoomControls(true); WebView.On<Android>().DisplayZoomControls(true); 我在iOS上的Android上测试过,看来这个问题只出现在Android上。 您可以创建一个自定义渲染器来实现缩放功能,它在我这边工作得很好。 [assembly: ExportRenderer(typeof(WebView), typeof(CustomWebViewRenderer))] namespace PDFPOC.Droid { public class CustomWebViewRenderer : WebViewRenderer { public CustomWebViewRenderer(Context context) : base(context) { } protected override void OnElementChanged(ElementChangedEventArgs<WebView> e) { base.OnElementChanged(e); if (e.NewElement != null) { Control.Settings.AllowUniversalAccessFromFileURLs = true; Control.Settings.SetSupportZoom(true); Control.Settings.BuiltInZoomControls = true; Control.Settings.DisplayZoomControls = true; } } } }


Laravel 中的策略对我不起作用,这是我的代码

我无法让策略在我的 Laravel 项目中工作,我安装了一个新项目来从头开始测试,我有这个控制器: 我无法让策略在我的 Laravel 项目中工作,我安装了一个新项目来从头开始测试,我有这个控制器: <?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use App\Models\User; class UserController extends Controller { public function index() { $this->authorize('viewAny', auth()->user()); return response("Hello world"); } } 本政策: <?php namespace App\Policies; use Illuminate\Auth\Access\Response; use App\Models\User; class UserPolicy { public function viewAny(User $user): bool { return true; } } 这是我的模型 <?php namespace App\Models; // use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use Laravel\Sanctum\HasApiTokens; class User extends Authenticatable { use HasApiTokens, HasFactory, Notifiable; /** * The attributes that are mass assignable. * * @var array<int, string> */ protected $fillable = [ 'name', 'email', 'password', ]; /** * The attributes that should be hidden for serialization. * * @var array<int, string> */ protected $hidden = [ 'password', 'remember_token', ]; /** * The attributes that should be cast. * * @var array<string, string> */ protected $casts = [ 'email_verified_at' => 'datetime', 'password' => 'hashed', ]; } 我收到错误 403:此操作未经授权。我希望有人能帮助我解决我的问题。谢谢你 我也尝试过修改AuthServiceProvider文件,但没有任何改变。 必须在 App\Providers\AuthServiceProvider 中添加您的策略吗? protected $policies = [ User::class => UserPolicy::class ]; 您需要指定您正在使用的模型。具体来说,就是User。因此,传递当前登录的用户: $this->authorize('viewAny', auth()->user()); 此外,您正在尝试验证用户是否有权访问该页面。确保尝试访问该页面的人是用户,以便策略可以授权或不授权。 要在没有入门套件的情况下进行测试,请创建一个用户并使用它登录。 <?php namespace App\Http\Controllers; use Illuminate\Support\Facades\Auth; class UserController extends Controller { public function index() { $user = \App\Models\User::factory()->create(); Auth::login($user); $this->authorize('viewAny', auth()->user()); return response("Hello world"); } } 但是,如果您希望授予访客用户访问权限,您可以使用 ? 符号将 User 模型设为可选: public function viewAny(?User $user) { return true; }


具有 TimestampableEntity 特征的实体在 PUT 操作中失败

我正在全新安装 API Platform (v3.2.7),并且使用 Gedmo\Timestampable\Traits\TimestampableEntity 这是我的实体(问候语示例) 我正在全新安装 API Platform (v3.2.7),并且正在使用 Gedmo\Timestampable\Traits\TimestampableEntity 这是我的实体(问候语示例) <?php namespace App\Entity; use ApiPlatform\Metadata\ApiResource; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Validator\Constraints as Assert; use Gedmo\Timestampable\Traits\TimestampableEntity; #[ApiResource] #[ORM\Entity] class Greeting { use TimestampableEntity; #[ORM\Id] #[ORM\Column(type: "integer")] #[ORM\GeneratedValue] private ?int $id = null; #[ORM\Column] #[Assert\NotBlank] public string $name = ""; public function getId(): ?int { return $this->id; } } 和我的 config/services.yaml gedmo.listener.timestampable: class: Gedmo\Timestampable\TimestampableListener tags: - { name: doctrine.event_listener, event: 'prePersist' } - { name: doctrine.event_listener, event: 'onFlush' } - { name: doctrine.event_listener, event: 'loadClassMetadata' } 它在 POST 操作上工作正常,但在执行 PUT 时失败。我收到此错误 执行查询时发生异常:SQLSTATE[23000]: 完整性约束违规:1048 列“created_at”不能 空 我使用的版本是:symfony 6.4.1,doctrine 2.12,gedmo 3.14 我最终做的是使用 PATCH 而不是 PUT。所以我可以编辑部分实体,并且特征仍然更新 updated_at 字段


如何解决数字格式异常?

index.html 输入第一个数字: 输入第二个数字... index.html <!DOCTYPE html> <html> <body> <form action="add"> Enter 1st number:<input type="text" name="num1"><br> Enter 2st number:<input type="text" name="num1"><br> <input type="submit"> </form> </body> </html> AddServlet.java 这是 servlet 代码。 package com.adithya; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class AddServlet extends HttpServlet { public void service(HttpServletRequest req,HttpServletResponse res) throws IOException { int i=Integer.parseInt(req.getParameter("num1")); int j=Integer.parseInt(req.getParameter("num2")); int k=i+j; PrintWriter out=res.getWriter(); out.println("result is"+k); } } 我正在尝试获取结果,但它显示了如下所示的异常。我无法理解例外情况。 ** 例外** 这显示了这样的异常。我无法识别问题所在。 java.lang.NumberFormatException: Cannot parse null string java.base/java.lang.Integer.parseInt(Integer.java:630) java.base/java.lang.Integer.parseInt(Integer.java:786) com.adithya.AddServlet.service(AddServlet.java:19) javax.servlet.http.HttpServlet.service(HttpServlet.java:623) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51) 我不明白这是什么错误。我试图从 2 天开始解决这个问题。请任何人帮助我解决这个问题。但它不起作用。 您有 2 个相同的名字 num1,并且您正在尝试呼叫不在场的 num2。 Enter 2st number:<input type="text" name="num1"><br> 关于: Enter 2st number:<input type="text" name="num2"><br>


如何使用 blazor <InputDate /> 标签使用当地文化来格式化日期

我正在我的 Blazor 应用程序中使用该标签。但是我如何使用我自己的文化来格式化日期? 我正在我的 Blazor 应用程序中使用该标签。但是我如何使用我自己的文化来格式化日期? <InputDate class="form-control" @bind-Value="@ValidDate" @bind-Value:culture="nl-BE" @bind-Value:format="dd/MM/yyyy" /> 问候 迪特尔 答案是@bind-Value:format,就像这样 @page "/" <EditForm Model="@CurrentPerson"> <InputDate @bind-Value="@CurrentPerson.DateOfBirth" @bind-Value:format="dd/MM/yyyy"/> </EditForm> @code { Person CurrentPerson = new Person(); public class Person { public DateTime DateOfBirth { get; set; } = DateTime.Now; } } 还可以选择使用bind-Value:culture。 无法设置InputDate或<input type="date">的格式。这取决于浏览器设置。用户可以更改浏览器的语言。但您无法从 HTML 更改它。如果您确实需要自定义格式,则必须使用InputText或<input type="text">。我建议使用一些 javascript 库,例如 jQuery UI datepicker。 该解决方案对我不起作用。我是这样工作的: @代码{ 仅私人日期? _geboortedatum; private string GeboortedatumFormatted { get => _geboortedatum?.ToString("dd-MM-yyyy") ?? ""; set { if (DateOnly.TryParse(value, out var newDate)) { _geboortedatum = newDate; } } } } 地质学 _geboortedatum" class="text-danger" />


使用 InertiaJs 和 Laravel 从数据库中删除用户

我在从数据库中删除记录时遇到问题。我正在使用 InertiaJS 和 Laravel。 组件代码 以下是链接/按钮代码: 我在从数据库中删除记录时遇到问题。我正在使用 InertiaJS 和 Laravel。 组件代码 以下是链接/按钮代码: <Link class="trash" @click="submit(result.ChildID)"> Move to Trash </Link> 注意: ChildID 是数据库中子记录的 id。 现在:当用户单击此链接时,将调用一个方法,如下所示。 methods: { submit: function (ChildID) { alert(ChildID) if (confirm("Are you sure you want to delete this child?")) { this.$inertia.delete('destroy/ChildID'); } }, }, 路线代码 Route::delete('destroy/{childID}',[childrenController::class,'destroy']); 控制器代码 public function destroy(children $childID){ $childID->delete(); return redirect()->route('View_Child_Profile'); } 现在,当我点击删除按钮时,我收到以下错误: 试试这个。我认为你犯了错误“this.$inertia.delete('destroy/ChildID');” methods: { submit: function (ChildID) { alert(ChildID) if (confirm("Are you sure you want to delete this child?")) { this.$inertia.delete(`destroy/${ChildID}`); // or this.$inertia.delete('destroy/'+ChildID); } }, }, 这是我处理删除过程的方式。 前视+惯性: import { Link } from '@inertiajs/inertia-vue3'; 在模板中: <Link method="delete" :href="route('admin.insta_feeds.destroy',id)">Delete</Link> 后端 Laravel: 路线: Route::resource('insta_feeds', InstaFeedsController::class); 控制器功能: public function destroy(InstaFeed $insta_feed) { if(isset($insta_feed->image_path)){ Storage::delete($insta_feed->image_path); } $insta_feed->delete(); return Redirect::route('admin.insta_feeds.index'); }


棱镜:ViewModelLocator.AutowireViewModel 不适用于内容视图

我正在将使用 Prism 的 Xamarin.Forms 应用程序迁移到 .NET Maui。该应用程序有一个 TabbedPage 导航。此迁移有效。 但是 ContentPages 包含几个 ContentView,如下所示: 我正在将使用 Prism 的 Xamarin.Forms 应用程序迁移到 .NET Maui。该应用程序有一个 TabbedPage 导航。此迁移有效。 但是 ContentPages 包含几个 ContentView,如下所示: <?xml version="1.0" encoding="utf-8" ?> <ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:views="clr-namespace:MauiDemo.Views" x:Class="MauiDemo.Views.HomePage" Title="HomePage"> <VerticalStackLayout> <views:FirstContentView HeightRequest="200"/> <views:SecondContentView HeightRequest="200"/> </VerticalStackLayout> </ContentPage> 在 Xamarin 中,我能够将 prism:ViewModelLocator.Autowire="true" 属性添加到 contentview 中,并且 prism 找到了关联的视图模型。在 .NET maui 中,prism:ViewModelLocator.AutowireViewModel="Automatic" 属性没有任何作用。 例如,ContentView 的名称是 “FirstContentView”。关联的viewModel的名称是“FirstContentViewViewModel” 根据https://prismlibrary.com/docs/maui/migration.html中的描述,它应该可以工作,但事实并非如此。 配置这样的自动接线有什么技巧吗? 我使用 prism 存储库的当前克隆 https://github.com/PrismLibrary/Prism 以及带有最新 MAUI 组件的当前 .NET8 SDK 我使用区域而不是通过自动装配。具有不同 ContentView 的页面应该如下所示 <?xml version="1.0" encoding="utf-8" ?> <ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:views="clr-namespace:MauiDemo.Views" xmlns:prism="http://prismlibrary.com" x:Class="MauiDemo.Views.HomePage" Title="HomePage"> <VerticalStackLayout> <ContentView prism:RegionManager.RegionName="FirstContent"/> <ContentView prism:RegionManager.RegionName="SecondContent"/> </VerticalStackLayout> </ContentPage> 所需的视图及其视图模型应在 MauiProgram 中注册为 RegisterForRegionNavigation container.RegisterForRegionNavigation<FirstContentView, FirstContentViewViewModel>(); container.RegisterForRegionNavigation<SecondContentView, SecondContentViewModel>(); .UsePrism(prism => { prism.RegisterTypes(container => { container.RegisterForNavigation<MainPage,MainPageViewModel>(); container.RegisterForNavigation<HomePage>(); container.RegisterForRegionNavigation<FirstContentView, FirstContentViewViewModel>(); container.RegisterForRegionNavigation<SecondContentView, SecondContentViewModel>(); }) .CreateWindow(navigationService => navigationService.CreateBuilder() .AddSegment<MainPage>() .NavigateAsync(HandleNavigationError)); }) 包含多个ContentView的页面的ViewModel应该为所需的ContentView调用RegionManager.RequestNavigate方法。 public class HomePageViewModel : ViewModelBase, IInitialize { private readonly IRegionManager _regionManager; public HomePageViewModel(IRegionManager regionManager) { _regionManager = regionManager; } public void Initialize(INavigationParameters parameters) { _regionManager.RequestNavigate("FirstContent", nameof(FirstContentView)); _regionManager.RequestNavigate("SecondContent", nameof(SecondContentView)); } } 仅此而已。它的工作原理如https://xamgirl.com/prism-regions-in-xamarin-forms/所述


我正在使用 laravel livewire 3 获取页面未找到

单击时,我在控制台中找不到页面 错误:POST http://localhost/livewire/update 404(未找到) counter.blade.php {{ $this->count }} 单击时,我在控制台中找不到页面 错误:POST http://localhost/livewire/update 404(未找到) counter.blade.php <div> <h1>{{ $this->count }}</h1> <button wire:click="increment">+</button> <button wire:click="decrement">-</button> </div> 在刀片中我有以下内容: @section('custom-js') @livewireScripts @endsection @section('custom-css') @livewireStyles @endsection <livewire:counter /> 当单击增量或减量时,我找不到页面 如果您使用Livewire3,则无需手动注入livewire资源的css和javascript,因为它们是自动注入的。 检查此文档页面以查看。 您必须先创建 Livewire 组件 php artisan make:livewire CreatePost Livewire 组件的更新功能。 public function update(){...}


如何在node js中使用DOM更改文本内容

我想做的是 我想在输入错误密码时将标签更改为错误密码 但出现错误 ReferenceError:文档未定义 这是我的 HTML 文件 我想做的是 我想在输入错误密码时将 标签更改为错误密码 但出现错误 ReferenceError:文档未定义 这是我的 HTML 文件 <form action="/check" method="POST"> <label for="password">Password:</label> <input type="text" id="password" name="password" required> <input type="submit" value="Submit"> <p></p> </form> 这是我的 javascript 文件内容 import express from "express"; import {dirname} from "path"; import { fileURLToPath } from "url"; import bodyParser from "body-parser"; const __dirname = dirname(fileURLToPath(import.meta.url)); const app = express(); const port = 3000; const pass = "ILoveProgramming"; var enter = ""; app.use(bodyParser.urlencoded({extended:true})); function checker(req, res, next){ enter = req.body.password; console.log(enter); next(); } app.use(checker); app.get("/", (req,res) =>{ res.sendFile(__dirname +"/public/index.html"); }); app.post("/check",(req,res)=>{ if(pass === enter){ res.sendFile(__dirname+"/public/secret.html"); } else{ document.querySelector("p").textContent("The paswrd is wrong"); console.log("The password is incorrect"); } // console.log(enter); }); app.use(bodyParser); app.listen(port, () =>{ console.log(`server is live at ${port}`); }); 我对这一切都是新手所以把我当作一个没有任何经验的人 document对象是浏览器DOM API的一部分,它在服务器端不可用。在浏览器控制台上,它是 window 对象的属性。 window.document。 您正在尝试操作服务器上的 DOM,这是不可能的。您应该在浏览器接收并呈现 HTML 页面后在客户端处理 DOM 操作。为此,您应该在 HTML 文件内有一个 script 标签。 <script> // inside here you add your logic to access document <script/> script标签将在浏览器上执行,您可以访问此标签内的document对象


无法访问派生模板类中模板基类的成员[重复]

我有一个模板基类。可以说。 模板 类基类 { 私人的: int成员1; 字符成员2; .... }; 我从上面的类派生了另一个类。 模板 我有一个模板基类。可以说。 template<class KeyF> class Base { private: int member1; char member2; .... }; 我从上面的类派生了另一个类。 template<class KeyF> class Derived : public Base<KeyF> { public: void func1() { <accessing member1/member2> } .... }; 上面的代码不能在 gcc 中编译。说明 member1 不是 Derived 的成员。但它已经从基类派生了,那为什么它不能访问它的成员呢? 您需要在基本成员名称前添加 this-> 或 Base<KeyF>:: 前缀,或者向类添加 using 声明以取消隐藏它们。他们的名字是从属名称,并且是隐藏的。 Base中的成员是private。您无法在本课程之外访问课程的 private members(friend 除外)。让它们 protected,或者让 protected getters。 您尝试过受保护吗?自从我深入 C++ 以来已经有一段时间了... 我认为解决这个问题需要两个改变: 在基类中,将成员定义为“受保护”而不是“私有”,以便在派生类中可访问。 在派生类中,在受保护成员前面添加基类名称。在这种情况下,它应该看起来像“Base::member1”。 在我的例子中使用 C++17 标准,问题得到了解决。希望这有帮助。感谢 Kerrek SB 提供的信息。


ClosedXML 导出数据网格到 Excel 仅 10 行

我有一个包含 60 行数据的数据网格和一个将其导入 Excel 的按钮: 我有一个包含 60 行数据的数据网格和一个将其导入 Excel 的按钮: <DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Source}" CanUserAddRows="False" HeadersVisibility="All" Name="dgDisplay"> <DataGrid.Columns> <DataGridTextColumn Header="Day" Binding="{Binding Day}"/> <DataGridTextColumn Header="Data" Binding="{Binding Data}"/> </DataGrid.Columns> </DataGrid> <Button Command="{Binding SaveDataGridToExcelCommand}" CommandParameter="{Binding ElementName=dgDisplay}"/> 其中 Day 和 Data 只是一些随机生成的 int 数据。 我的代码使用 ClosedXML 将数据从中导出到 Excel,它使用 MainWindowViewModel: ObservableObject 调用 MVVM.Toolkit。 [RelayCommand] public void SaveDataGridToExcel(DataGrid dataGrid) { DataTable dt = new DataTable(); foreach (DataGridColumn column in dataGrid.Columns) { dt.Columns.Add(column.Header.ToString()); } foreach (var item in dataGrid.Items) { DataRow dr = dt.NewRow(); bool rowHasData = false; for (int i = 0; i < dataGrid.Columns.Count; i++) { var cellContent = dataGrid.Columns[i].GetCellContent(item); if (cellContent is TextBlock textBlock) { //check if row empty, dont add this row.I add it on purpose to check //if the datagrid recognite the rest 50 rows not have data. It actually //dont save those data dr[i] = textBlock.Text; if (!string.IsNullOrEmpty(textBlock.Text)) { rowHasData = true; } } } if (rowHasData) { dt.Rows.Add(dr); } } SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "Excel files (*.xlsx)|*.xlsx"; if (saveFileDialog.ShowDialog() == DialogResult.OK) { using (XLWorkbook wb = new XLWorkbook()) { wb.Worksheets.Add(dt, "Sheet1"); wb.SaveAs(saveFileDialog.FileName); } } } 但是保存的60行结果只显示了10行数据,其余50行都是空的。如果疑问为什么不使用Microsoft.Interop.Excel,那是因为该包不适合我的 Excel 版本。我没有在 ClosedXML 中看到任何对此有限制或许可的地方,所以我想知道为什么。如有任何帮助,我们将不胜感激。 在浏览 github 几个小时后,我自己找到了答案。 我没有访问单元格内容,而是直接从 DataGrid 的 ItemsSource 访问数据: public void SaveDataGridToExcel(DataGrid dataGrid) { DataTable dataTable = new DataTable(); foreach (DataGridColumn column in dataGrid.Columns) { dataTable.Columns.Add(column.Header.ToString()); } var itemsSource = dataGrid.ItemsSource as IEnumerable; if (itemsSource != null) { foreach (var item in itemsSource) { var properties = item.GetType().GetProperties(); var row = dataTable.NewRow(); foreach (var property in properties) { row[property.Name] = property.GetValue(item); } dataTable.Rows.Add(row); } } //show dialog... }


如何使用 Xamarin 立即用点屏蔽密码字符

我想消除在 Xamarin.Forms 中输入密码时的延迟。我在互联网上没有找到任何解决方案。 我想消除在 Xamarin.Forms 中输入密码时的延迟。我在网上没有找到任何解决方案。 <local:NoDelayEntry x:Name="passwordEntry" Placeholder="Password" /> class NoDelayEntry : Entry { public NoDelayEntry() : base() { this.TextChanged += OnEntryTextChanged; } private void OnEntryTextChanged(object sender, TextChangedEventArgs e) { // Customize the behavior as needed this.IsPassword = true; this.Text = new string('●', e.NewTextValue.Length); } } 到目前为止我已经尝试过以下操作;但是,当我登录时,原始密码文本被替换为“●”。有没有办法在保留原始密码的同时仍然使用屏蔽行为? 一种想法是使用一个标签来遮盖密码字段,该标签会更新以显示键入的点数,但我不确定如何保持标签下方的密码字段可选。


为什么我有很多对 API 的请求,需要在 next.js 13v 的服务器端获取数据

我使用 Next.js 13v 在服务器端获取数据。 我的组件 const 页脚 = async () => { // 获取数据 const allCategories = (await getAllCategories({})).data; 返回 我使用 Next.js 13v 在服务器端获取数据。 我的组件 const Footer = async () => { // Get data const allCategories = (await getAllCategories({})).data; return <footer className={styles.footer}></footer>; }; 我的功能 export const getAllCategories = async ( params: IGetAllCategoriesRequest, ): Promise<AxiosResponse<IGetAllCategoriesResponse>> => { const url = 'static-pages/category/public'; const response = await axiosInstance.get<IGetAllCategoriesResponse>( url, { params: params, }, ); return response; }; 如果请求成功,我有一个请求 但是如果出现错误,我有很多请求,然后重定向到错误页面 本机获取具有相同的行为 那么为什么我在 next.js 13v 中对 API 有很多请求并在服务器端获取数据? 可能和开发模式有关。我发现这篇文章可能与此行为有关:https://dev.to/noclat/fixing-too-many-connections-errors-with-database-clients-stacking-in-dev-mode-with-next -js-3kpm


Laravel 购物车页面,表单内有一个表单,用于处理删除和提交数据更新数据库

我有一个购物车页面,表格内有一个表格,也许你可以建议我应该做什么? 根据图片,我给出的蓝色圆圈是一个表格 我的刀片代码 我有一个购物车页面,表格内有一个表格,也许你可以建议我应该做什么?根据图片我给出的蓝色圆圈是一个表格我的刀片代码<table class="table"> <thead> <tr> <th scope="col">No</th> <th scope="col">Nama Barang</th> <th scope="col">Quantity</th> <th scope="col">Action</th> </tr> </thead> <tbody> @php $no = 1; @endphp @forelse ($permintaans as $b) <tr> <td>{{ $no ++ }}</td> <td> {{ $b->nama_kategori }} {{ $b->nama_atk }} </td> <td> <form action="{{ route('permintaan.update', $b->id) }}" method="POST" style="display: inline-block;"> @csrf @method('PUT') <div class="input-group input-group-sm mb-3"> <input type="number" class="form-control" aria-label="Sizing example input" aria-describedby="inputGroup-sizing-sm" name="satuan_permintaan" min="0" max={{ $b->stok }} required> <span class="input-group-text" id="inputGroup-sizing-sm">{{ $b->subsatuan_atk }}</span> </div> </td> <td> <form action="{{ route('permintaan.destroy', $b->id) }}" method="POST" style="display: inline-block;"> @csrf @method('DELETE') <button type="submit" class="btn custom2-btn"><svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" fill="red" class="bi bi-trash" viewBox="0 0 16 16"> <path d="M5.5 5.5A.5.5 0 0 1 6 6v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5m2.5 0a.5.5 0 0 1 .5.5v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5m3 .5a.5.5 0 0 0-1 0v6a.5.5 0 0 0 1 0z"/> <path d="M14.5 3a1 1 0 0 1-1 1H13v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V4h-.5a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1H6a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1h3.5a1 1 0 0 1 1 1zM4.118 4 4 4.059V13a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1V4.059L11.882 4zM2.5 3h11V2h-11z"/> </svg></button> </form> </td> </tr> @empty @endforelse </tbody> </table> 我的控制器public function store(Request $request) { $task = new Permintaan(); $task->atk_id = $request->input('atk_id'); $task->proses = 'Proses'; if (Permintaan::where('atk_id', $task->atk_id)->exists()){ return redirect('/atk/permintaan')->with(['info' => 'ATK Sudah Dalam Permintaan']); } else{ $task->save(); return redirect()->route('permintaan.index'); } } public function destroy($id) { $permintaan = Permintaan::find($id); $permintaan->delete(); return redirect()->route('permintaan.index'); } 我要处理删除并提交数据更新数据库 在开始销毁表单之前关闭更新表单第一个表单标签(缺少)。


如何在webview中加载html字符串?

我有一个包含以下内容的html字符串: 我有一个包含以下内容的html字符串: <!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=windows-1250"> <meta name="spanish press" content="spain, spanish newspaper, news,economy,politics,sports"> <title></title> </head> <body id="body"> <!-- The following code will render a clickable image ad in the page --> <script src="http://www.myscript.com/a"></script> </body> </html> 我需要将该网站显示到 Android 中的网络视图中。 我尝试过这一切: webView.loadDataWithBaseURL(null, txt, "text/html", "UTF-8", null); webView.loadDataWithBaseURL("x-data://base", txt, "text/html", "UTF-8", null); webView.loadDataWithBaseURL("notreal/", txt, "text/htm", "utf-8",null); 我还尝试删除 DOCTYPE 标签: txt=txt.replace("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">", ""); 这些人都没有工作。我刚刚实现了将字符串显示到 webview(html 代码)中,但不是必须使用该 html 代码创建的网站。 出了什么问题? 在 WebView 中加载数据。调用WebView的loadData()方法 wv.loadData(yourData, "text/html", "UTF-8"); 你可以查看这个例子 http://developer.android.com/reference/android/webkit/WebView.html [编辑1] 您应该在 -- " 之前添加 -- \ -- 例如 --> name=\"spanish press\" 下面的字符串对我有用 String webData = "<!DOCTYPE html><head> <meta http-equiv=\"Content-Type\" " + "content=\"text/html; charset=utf-8\"> <html><head><meta http-equiv=\"content-type\" content=\"text/html; charset=windows-1250\">"+ "<meta name=\"spanish press\" content=\"spain, spanish newspaper, news,economy,politics,sports\"><title></title></head><body id=\"body\">"+ "<script src=\"http://www.myscript.com/a\"></script>şlkasşldkasşdksaşdkaşskdşk</body></html>"; 你也可以试试这个 final WebView webView = new WebView(this); webView.loadDataWithBaseURL(null, content, "text/html", "UTF-8", null); 从资产 html 文件中读取 ViewGroup webGroup; String content = readContent("content/ganji.html"); final WebView webView = new WebView(this); webView.loadDataWithBaseURL(null, content, "text/html", "UTF-8", null); webGroup.addView(webView); 我有同样的要求,我是按照以下方式完成的。你也可以试试这个。 使用loadData方法 web.loadData(""" <p style='text-align:center'> <img class='aligncenter size-full wp-image-1607' title='' src="+movImage+" alt='' width='240px' height='180px' /> </p> <p> <center> <U> <H2>"+movName+"("+movYear+")</H2> </U> </center> </p> <p><strong>Director : </strong>"+movDirector+"</p> <p><strong>Producer : </strong>"+movProducer+"</p> <p><strong>Character : </strong>"+movActedAs+"</p> <p><strong>Summary : </strong>"+movAnecdotes+"</p> <p><strong>Synopsis : </strong>"+movSynopsis+"</p> """, "text/html", "UTF-8" ); movDirector movProducer 都是我的字符串变量。 简而言之,我保留了 URL 的自定义样式。 如果您正在 JetpackCompose 中寻找某些内容,这可以帮助您: @Composable fun HtmlTextVisualizerComponent(textFromData: String) { val mimeType = "text/html" val encoding = "UTF-8" LazyColumn( modifier = Modifier .padding( start = 24.dp, end = 24.dp, top = 16.dp, bottom = 24.dp, ), ) { items(1) { val state = rememberWebViewState( url = "data:$mimeType;$encoding,$textFromData", ) val navigator = rememberWebViewNavigator() WebView( state = state, modifier = Modifier.fillMaxSize(), navigator = navigator, onCreated = { it.settings.javaScriptEnabled = true }, ) } } } 一定不要忘记在你的 gradle 中添加依赖项: implementation "com.google.accompanist:accompanist-webview:0.30.1"


Struts 2 与 Apache Shiro 集成时如何显示结果页面

使用: struts2 2.5.10, 春天 4.x, struts2-spring-插件2.5.10, 希罗1.4.0, Shiro-Spring 1.4.0。 网络.xml: 使用: struts2 2.5.10, 春季 4.x, struts2-spring-插件2.5.10, 四郎1.4.0, shiro-spring 1.4.0. web.xml: <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <display-name>Archetype Created Web Application</display-name> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:beans.xml</param-value> </context-param> <filter> <filter-name>shiroFilter</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> <init-param> <param-name>targetFilterLifecycle</param-name> <param-value>true</param-value> </init-param> </filter> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <!-- shiro filter mapping has to be first --> <filter-mapping> <filter-name>shiroFilter</filter-name> <url-pattern>/*</url-pattern> <dispatcher>REQUEST</dispatcher> <dispatcher>FORWARD</dispatcher> <dispatcher>INCLUDE</dispatcher> <dispatcher>ERROR</dispatcher> </filter-mapping> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app> beanx.xml: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd "> <bean name="loginAction" class="example.shiro.action.LoginAction" > </bean> <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <property name="securityManager" ref="securityManager" /> <property name="loginUrl" value="/login.jsp" /> <property name="filterChainDefinitions"> <value> /login.jsp = authc /logout = logout /* = authc </value> </property> </bean> <bean id="iniRealm" class="org.apache.shiro.realm.text.IniRealm"> <property name="resourcePath" value="classpath:shiro.ini" /> </bean> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <property name="realm" ref="iniRealm" /> </bean> <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/> </beans> struts.xml: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name="struts.devMode" value="true" /> <package name="default" extends="struts-default"> <action name="list" class="loginAction" method="list"> <result name="success">/success.jsp</result> <result name="error">error.jsp</result> </action> </package> </struts> index.jsp: <body> <s:action name="list" /> </body> login.jsp 看起来像: <form name="loginform" action="" method="post"> <table align="left" border="0" cellspacing="0" cellpadding="3"> <tr> <td>Username:</td> <td><input type="text" name="username" maxlength="30"></td> </tr> <tr> <td>Password:</td> <td><input type="password" name="password" maxlength="30"></td> </tr> <tr> <td colspan="2" align="left"><input type="checkbox" name="rememberMe"><font size="2">Remember Me</font></td> </tr> <tr> <td colspan="2" align="right"><input type="submit" name="submit" value="Login"></td> </tr> </table> </form> LoginAction.list(): public String list() { Subject currentUser = SecurityUtils.getSubject(); if(currentUser.isAuthenticated()) {System.out.println("user : "+currentUser.getPrincipal()); System.out.println("You are authenticated!"); } else { System.out.println("Hey hacker, hands up!"); } return "success"; } shiro.ini: [users] root=123,admin guest=456,guest frank=789,roleA,roleB # role name=permission1,permission2,..,permissionN [roles] admin=* roleA=lightsaber:* roleB=winnebago:drive:eagle5 index.jsp、login.jsp、success.jsp放在webapp下 我想要的是:输入LoginAction.list()需要进行身份验证,如果登录成功,则运行LoginAction.list()并返回"success"然后显示定义为Struts操作结果的success.jsp。 现在登录成功后可以执行LoginAction.list(),但是success.jsp不显示,浏览器是空白页面。 为什么? 我找到了原因:我在index.jsp中使用了<s:action name="list" />,但是struts文档说如果我们想用<s:action>看到结果页面,那么我们必须将其属性executeResult设置为true,即就像<s:action name="list" executeResult="true"/>。 在我看来,这有点奇怪,这个属性默认应该是 true。 有一个示例,您应该如何使用 Shiro applicationContext.xml 进行配置: <property name="filterChainDefinitions"> <value> # some example chain definitions: /admin/** = authc, roles[admin] /** = authc # more URL-to-FilterChain definitions here </value> </property> 以 /admin/ 开头的 URL 通过角色 admin 进行保护,任何其他 URL 均不受保护。如果 Struts 操作和结果 JSP 不在受保护区域中,则会显示它们。


© www.soinside.com 2019 - 2024. All rights reserved.