歌入人心

文章 评论 浏览 32

歌入人心 2025-02-09 18:51:30

需要注意的几件事:

  • 此处介绍的JSON代表了所有具有相同属性的对象。它可以被视为 Records Rows 的数组。
  • 您需要对此JSON进行挑选,在DataGridView中介绍结果,并允许用户过滤并可能对数据进行排序。

您目前可以将此JSON划分为简单收集的类对象,这很好。如果您想过滤和排序此集合,它可能会变得更加复杂,因为一个简单的 list< t> 本身不支持它。绑定清单也不是。
您应该实现 ibindinglistview 处理对象列表,并且很可能还很可能还处理基类中的接口(您的当前用户类)。
或者使用ORM / Mini-orm。

已经建立了一种已经实现所有这些功能的已经建立的(和测试)类型noreferrer“> datatable class。
如前所述,您的JSON实际上是一个表( Records 的数组),因此将其列为数据表非常简单。只是:

Dim dt = JsonConvert.DeserializeObject(Of DataTable)(json) 

数据级类已经允许过滤,设置其属性和排序,设置其 DefaultView.Sort 属性。

尽管如此,我建议使用介体在数据词和UI之间。
该工具非常有用,因为它提供了过滤和分类数据源的常用方法,但只要数据源实际上具有这些功能。
使用BindingSource,无论数据源是什么。
它还生成了一些有用的事件,如
currentchanged 活动等等。
ListChanged 事件还提供了指定更改类型的参数。

使用BindingSource,以序列化回JSON,如果数据发生了变化:

[BindingSource].EndEdit()
Dim json = JsonConvert.SerializeObject([BindingSource].DataSource, Formatting.Indented)

在示例代码中,使用这些对象(请参阅视觉示例):

  • usersSource :bindingsource对象
  • tboxfilteruser < /code>:文本框控件,使用用户名 property
  • tboxFilterTitle :一个文本框控件,使用 title> title> title property过滤
  • 数据代码> btnremovefilter :用于删除当前过滤器的按钮控件
  • dgv :dataGridView控件

Public Class SomeForm

    Private UsersSource As New BindingSource()
    ' Current filters
    Private UserNameFilter As String = "UserName LIKE '%%'"
    Private UserTitleFilter As String = "Title LIKE '%%'"

    Protected Overrides Sub OnLoad(e As EventArgs)
        MyBase.OnLoad(e)

        Dim json = File.ReadAllText("D:\Users.json")
        Dim dt = JsonConvert.DeserializeObject(Of DataTable)(json)
        dt.AcceptChanges()
        UsersSource.DataSource = dt
        dgv.DataSource = UsersSource
    End Sub

    Private Sub tBoxFilterUser_TextChanged(sender As Object, e As EventArgs) Handles tBoxFilterUser.TextChanged
        Dim tbox = DirectCast(sender, TextBox)
        UserNameFilter = $"UserName LIKE '%{tbox.Text}%'"
        UsersSource.Filter = $"{UserNameFilter} AND {UserTitleFilter}"
    End Sub

    Private Sub tBoxFilterTitle_TextChanged(sender As Object, e As EventArgs) Handles tBoxFilterTitle.TextChanged
        Dim tbox = DirectCast(sender, TextBox)
        UserTitleFilter = $"Title LIKE '%{tbox.Text}%'"
        UsersSource.Filter = $"{UserNameFilter} AND {UserTitleFilter}"
    End Sub

    Private Sub btnRemoveFilter_Click(sender As Object, e As EventArgs) Handles btnRemoveFilter.Click
        tBoxFilterUser.Clear()
        tBoxFilterTitle.Clear()
        UsersSource.RemoveFilter()
    End Sub
End Class

这是其工作方式:

“

A few things to note:

  • The JSON presented here represent an array of objects which all have the same properties. It can be considered an array of records or Rows.
  • You need to deserialize this JSON, present the result in a DataGridView and allow the user to filter and probably sort the data.

You're currently deserializing this JSON to simple collection a class objects, which is perfectly fine. It may become a little more complex if you want to filter and sort this collection, since a simple List<T> doesn't support it by itself. Nor does a BindingList.
You should implement the IBindingListView interface in a class that handles the List of objects and most probably also the INotifyPropertyChanged interface in the base class (your current Users class).
Or use an ORM / Mini-ORM instead.

There's an already built (and tested) Type that already implements all these features, the DataTable class.
Since, as mentioned, your JSON IS actually a Table (an array of records), deserializing it to a DataTable is quite straightforward. It's just:

Dim dt = JsonConvert.DeserializeObject(Of DataTable)(json) 

The DataTable class already allows filtering, setting its DefaultView.RowFilter property and sorting, setting its DefaultView.Sort property.

Nonetheless, I suggest to use a BindingSource as mediator between the DataTable and the UI.
This tool is quite useful, since it provides common methods to filter and sort a source of data, provided that the source of data actually has these capabilities.
Using a BindingSource, you always use the same methods, no matter what the source of data is.
It also generates some useful events, as the ListChanged, AddingNew, CurrentChanged events and more.
The ListChanged event also provides arguments that specify the type of change.

With a BindingSource, to serialize back to JSON, if the the data has changed:

[BindingSource].EndEdit()
Dim json = JsonConvert.SerializeObject([BindingSource].DataSource, Formatting.Indented)

In the sample code, these objects are used (see the visual example):

  • UsersSource: the BindingSource object
  • tBoxFilterUser: a TextBox Control, filters the data using the UserName Property
  • tBoxFilterTitle: a TextBox Control, filters the data using the Title Property
  • btnRemoveFilter: a Button Control used to remove the current filters
  • dgv: a DataGridView Control

Public Class SomeForm

    Private UsersSource As New BindingSource()
    ' Current filters
    Private UserNameFilter As String = "UserName LIKE '%%'"
    Private UserTitleFilter As String = "Title LIKE '%%'"

    Protected Overrides Sub OnLoad(e As EventArgs)
        MyBase.OnLoad(e)

        Dim json = File.ReadAllText("D:\Users.json")
        Dim dt = JsonConvert.DeserializeObject(Of DataTable)(json)
        dt.AcceptChanges()
        UsersSource.DataSource = dt
        dgv.DataSource = UsersSource
    End Sub

    Private Sub tBoxFilterUser_TextChanged(sender As Object, e As EventArgs) Handles tBoxFilterUser.TextChanged
        Dim tbox = DirectCast(sender, TextBox)
        UserNameFilter = 
quot;UserName LIKE '%{tbox.Text}%'"
        UsersSource.Filter = 
quot;{UserNameFilter} AND {UserTitleFilter}"
    End Sub

    Private Sub tBoxFilterTitle_TextChanged(sender As Object, e As EventArgs) Handles tBoxFilterTitle.TextChanged
        Dim tbox = DirectCast(sender, TextBox)
        UserTitleFilter = 
quot;Title LIKE '%{tbox.Text}%'"
        UsersSource.Filter = 
quot;{UserNameFilter} AND {UserTitleFilter}"
    End Sub

    Private Sub btnRemoveFilter_Click(sender As Object, e As EventArgs) Handles btnRemoveFilter.Click
        tBoxFilterUser.Clear()
        tBoxFilterTitle.Clear()
        UsersSource.RemoveFilter()
    End Sub
End Class

This is how it works:

JSON to DataTable

在DataGridView中搜索带有输出的JSON文件的内容

歌入人心 2025-02-08 23:26:10

当前的答案

可以通过将Discord.py更新为至少 ,通过使用 pip install git+https://github.com/rapptz/discord.py.py 在终端中。

过时的答案

说明

看起来似乎有一个错误。Py.py会导致此错误。在 _CHECK_CAN_RUN 的混合命令中,它使用互动。_baton作为命令上下文。 Interaction._baton 设置为缺少的前哨值,因此当 discord.py.py.py 试图像常规上下文>上下文> Object一样,它会陷入错误。 。

尽管我不确定任何意外的副作用,但可以简单地修补这一点。只需设置互动。我在两个测试用例中都对其进行了测试,并且它们有效:

代码

@bot.tree.command(name="help", guild=discord.Object(id=703732969160048731))
async def help_command(interaction: discord.Interaction, parameter: str = None):
    embed = discord.Embed(title="Test")

    cmd = bot.get_command(parameter)

    ctx: commands.Context = await bot.get_context(interaction)

    interaction._baton = ctx  # sketchy, but it works

    try:
        await cmd.can_run(ctx)
        embed.add_field(name="Usable by you:", value="Yes")
    except commands.CommandError as exc:
        embed.add_field(name="Usable by you:", value=f"No:\n{exc}")

    await ctx.send(embed=embed)

Current Answer

This can be resolved by updating discord.py to at least commit 36f039a1bffb835a555be8a43976397ba6eb9c76, by using pip install git+https://github.com/rapptz/discord.py in terminal.

Outdated Answer

Explanation

It appears as though there is a bug with discord.py which causes this error. In _check_can_run for hybrid commands, it uses interaction._baton as the command context to check. interaction._baton is set to a missing sentinel value, so it runs into errors when discord.py tries to use it like a regular Context object.

This can be patched pretty simply, although I'm not sure of any unintended side effects. Simply set interaction._baton to be the context you've just fetched. I've tested it with both test cases and they work:

Code

@bot.tree.command(name="help", guild=discord.Object(id=703732969160048731))
async def help_command(interaction: discord.Interaction, parameter: str = None):
    embed = discord.Embed(title="Test")

    cmd = bot.get_command(parameter)

    ctx: commands.Context = await bot.get_context(interaction)

    interaction._baton = ctx  # sketchy, but it works

    try:
        await cmd.can_run(ctx)
        embed.add_field(name="Usable by you:", value="Yes")
    except commands.CommandError as exc:
        embed.add_field(name="Usable by you:", value=f"No:\n{exc}")

    await ctx.send(embed=embed)

discord.py 2.0-获取HybridCommand的上下文

歌入人心 2025-02-08 20:45:24

我正在寻找比这更好的解决方案:

import sys
import logging
class SomeClass:
    def __init__(self) -> None:
        self.logger = logging.getLogger(__name__)
        H = logging.StreamHandler(sys.stdout)
        H.setLevel(logging.INFO)
        H.setFormatter(
            logging.Formatter(
                fmt="[%(asctime)s] %(levelname)s: %(message)s",
                datefmt="%d/%m/%Y ( %H:%M:%S )"
            ))
        self.logger.addHandler(H)
    def foo(self) -> None:
        self.logger.warning("foooo ...")

c = SomeClass()
c.foo()

I'm looking for a better solution than this:

import sys
import logging
class SomeClass:
    def __init__(self) -> None:
        self.logger = logging.getLogger(__name__)
        H = logging.StreamHandler(sys.stdout)
        H.setLevel(logging.INFO)
        H.setFormatter(
            logging.Formatter(
                fmt="[%(asctime)s] %(levelname)s: %(message)s",
                datefmt="%d/%m/%Y ( %H:%M:%S )"
            ))
        self.logger.addHandler(H)
    def foo(self) -> None:
        self.logger.warning("foooo ...")

c = SomeClass()
c.foo()

设置一个级级记录器

歌入人心 2025-02-08 10:49:48

中有3个条件检查如果名称==“ kevin”或“ jon”或“ inbar”:

  • name ==“ kevin”
  • “ jon”
  • “ inbar”

,此if语句等同于

if name == "Kevin":
    print("Access granted.")
elif "Jon":
    print("Access granted.")
elif "Inbar":
    print("Access granted.")
else:
    print("Access denied.")

自<<代码> elif“ jon” 将始终是正确的,因此可以访问任何用户的

解决方案,


下使用任何一种方法

您可以在 fast> fast

if name in ["Kevin", "Jon", "Inbar"]:
    print("Access granted.")
else:
    print("Access denied.")

slow> slow

if name == "Kevin" or name == "Jon" or name == "Inbar":
    print("Access granted.")
else:
    print("Access denied.")

slow + slow + 不必要的代码

if name == "Kevin":
    print("Access granted.")
elif name == "Jon":
    print("Access granted.")
elif name == "Inbar":
    print("Access granted.")
else:
    print("Access denied.")

There are 3 condition checks in if name == "Kevin" or "Jon" or "Inbar":

  • name == "Kevin"
  • "Jon"
  • "Inbar"

and this if statement is equivalent to

if name == "Kevin":
    print("Access granted.")
elif "Jon":
    print("Access granted.")
elif "Inbar":
    print("Access granted.")
else:
    print("Access denied.")

Since elif "Jon" will always be true so access to any user is granted

Solution


You can use any one method below

Fast

if name in ["Kevin", "Jon", "Inbar"]:
    print("Access granted.")
else:
    print("Access denied.")

Slow

if name == "Kevin" or name == "Jon" or name == "Inbar":
    print("Access granted.")
else:
    print("Access denied.")

Slow + Unnecessary code

if name == "Kevin":
    print("Access granted.")
elif name == "Jon":
    print("Access granted.")
elif name == "Inbar":
    print("Access granted.")
else:
    print("Access denied.")

为什么要“ a == x或y或z”总是评估为真?我如何比较“ a”所有这些?

歌入人心 2025-02-08 10:20:45

您没有指定任何停止条件,无论是内部编码还是在行为空间设置中。

我从您最初发布的有关BhaviorSpace设置的图像中看到,您包含了时间限制 1000。我想您到达了那里,因为默认值为0,行为空间实验将永远运行。只有实验仅在达到指定的时间限制后停止,您的买家继续做他们所说的事情的时间比仅5个重复的时间更长 - 因此,很长的列表。

在您的情况下,由于您已经告诉NetLogo要执行 go 的次数(通过使用 repot ),并基于代码的布置(即<<代码> tick 仅在发生所有期望的重复之后才会发生),以下任何一个停止条件都将实现您想要的东西:

  • in CaveniorSpace: ticks = 1 ;
  • 在代码中:
to go
  repeat 5 [
    ...
  ]

  tick
  stop
end

在这两种情况下,您都可以返回到0 <代码>时间限制 0(即无时间限制)。

You didn't specify any stop condition, either in-code or in your BehaviorSpace setup.

I saw from the image you originally posted about the BhaviorSpace setup, that you included a Time limit of 1000. I imagine you got there because, with the default value of 0, BehaviorSpace experiments were running forever. With experiments stopping only once they hit the specified time limit, your buyers are continuing to do what they're told for much longer than just 5 repetitions - hence the very long lists.

In your case, since you are already telling NetLogo how many times you want your go to execute (by using repeat), and based on the arrangement of your code (i.e. tick happening only after all your desired repetitions took place), either of the following stop conditions will achieve what you want:

  • In BehaviorSpace: ticks = 1;
  • In code:
to go
  repeat 5 [
    ...
  ]

  tick
  stop
end

In both cases, you can just go back to having a Time limit of 0 (i.e. no time limit).

Netlogo正在工作,但行为空间正在显示垃圾

歌入人心 2025-02-07 10:41:10

有几种方法可以解决差距。

1:使用 sns.catplot

这可能需要将数据加倍,尽管如果您要在每个子图中绘制不同的变量,则可以

import pandas as pd
import seaborn as sns

# Load the dataset twice
tips_a = sns.load_dataset("tips")
tips_b = sns.load_dataset("tips")
# Add a dummy facet variable
tips_a["col"] = "A"
tips_b["col"] = "B"

# Concat them
tips = pd.concat([tips_a, tips_b])

# Use the dummy variable for the `col` param
g = sns.catplot(x="day", y="total_bill", hue="sex", data=tips, kind="bar", col="col")
# Remove the titles and move the legend
g.set_titles("")
sns.move_legend(g, loc="upper center", ncol=2, title=None, frameon=False)

​。


​> AutoScale 轴

仍然需要一点 bbox_to_anchor 弹奏,您可能想更改正确的y轴标签(以及ticks/ticklabels)。

import matplotlib.pyplot as plt
import seaborn as sns

fig, ax = plt.subplots(1, 2, figsize=(7, 4))
sns.barplot(x="day", y="total_bill", hue="sex", data=tips, ax=ax[0])
ax[0].legend_.remove()
sns.barplot(x="day", y="total_bill", hue="sex", data=tips, ax=ax[1])
sns.move_legend(
    ax[1],
    loc="upper center",
    bbox_to_anchor=(-0.1, 1.1),
    ncol=2,
    title=None,
    frameon=False,
)

ax[0].autoscale()
ax[1].autoscale()

There are a couple of ways that I would approach closing the gap.

1: Use a sns.catplot:

This potentially requires doubling your data, though if you're plotting different variables in each subplot you may be able to melt your data

import pandas as pd
import seaborn as sns

# Load the dataset twice
tips_a = sns.load_dataset("tips")
tips_b = sns.load_dataset("tips")
# Add a dummy facet variable
tips_a["col"] = "A"
tips_b["col"] = "B"

# Concat them
tips = pd.concat([tips_a, tips_b])

# Use the dummy variable for the `col` param
g = sns.catplot(x="day", y="total_bill", hue="sex", data=tips, kind="bar", col="col")
# Remove the titles and move the legend
g.set_titles("")
sns.move_legend(g, loc="upper center", ncol=2, title=None, frameon=False)

enter image description here


2: autoscale the axes

This still requires a little bit of bbox_to_anchor fiddling and you probably want to change the right y-axis label (and ticks/ticklabels).

import matplotlib.pyplot as plt
import seaborn as sns

fig, ax = plt.subplots(1, 2, figsize=(7, 4))
sns.barplot(x="day", y="total_bill", hue="sex", data=tips, ax=ax[0])
ax[0].legend_.remove()
sns.barplot(x="day", y="total_bill", hue="sex", data=tips, ax=ax[1])
sns.move_legend(
    ax[1],
    loc="upper center",
    bbox_to_anchor=(-0.1, 1.1),
    ncol=2,
    title=None,
    frameon=False,
)

ax[0].autoscale()
ax[1].autoscale()

enter image description here

如何将一个传奇人物与两个海洋小号相结合?

歌入人心 2025-02-07 08:59:01

您的代码中有两个简单的错误,可以轻松修复。

  1. 函数的括号前有一个额外的点。由于 querySelector 是一个函数,因此带有属性的括号直接出现在其之后,如下所示。
document.querySelector('.box').style.color = 'pink';
  1. 没有任何东西可以触发onclick事件。解决此问题的最简单方法是将 onClick 属于您的按钮,如下所示:
<button class="pink" onclick="changeColor()">Pink</button>

我希望这可以帮助您。

There are two simple mistakes in your code that can be easily fixed.

  1. There is an extra dot before the parenthesis in your function. Since querySelector is a function, the parenthesis with the attributes come directly after it, as shown below.
document.querySelector('.box').style.color = 'pink';
  1. There isn't anything to trigger the onclick event. The simplest way to fix this is to add an onclick attribute to your button, as shown below:
<button class="pink" onclick="changeColor()">Pink</button>

I hope that this can help.

onclick函数错误,函数未定义

歌入人心 2025-02-07 05:09:01

如果您使用 bcrypt

const salt = bcrypt.genSaltSync(12)
// Continue whatever user saving happens here with salt

其他库也可能具有这些功能,请生成盐,将其用作哈希的参数

If you're using bcrypt

const salt = bcrypt.genSaltSync(12)
// Continue whatever user saving happens here with salt

Other libraries may also have these functions, generate a salt, use it as the parameter of hashing

如何节省盐

歌入人心 2025-02-07 02:10:10
  1. 我希望将用户的数据保存在云上。我个人喜欢Google的Firebase,它可以帮助使用实时数据库进行身份验证和存储。将用户的数据同步到DB非常容易,甚至使用缓存存储数据,以防用户离线并在设备在线后同步到DB。您可以找到有关Firebase及其产品的更多信息在这里

  2. Flutter是一个非常好的框架,可以通过其跨平台兼容性即可一次完成多个平台的应用程序!如果您不想花时间为多个设备创建应用程序,那么Flutter就是要走的路。我个人认为Flutter Web尚未增长,但是它将加班,毕竟是Google的OpenSource框架。我建议这个想法8.5/10

  3. flutter文档写得很好,初学者也可以通过一些视频示例(包括文档中)来完成它。如果您想使用的东西在较新版本的Flutter中不支持,则文本编辑器将在代码上显示一条线,这意味着它被弃用了,不支持它。总是有一个替代方案,您可以使用Flutter Docs或YouTube找到它。 Flutter文档已针对初学者进行优化9/10

  1. I'd prefer saving user's data on the cloud. I personally like Google's firebase which helps with authentication and storage using RealTime Database. It's pretty easy to sync your user's data into the DB and even stores data using cache in case the user is offline and syncs to DB once device is online. You can find more about firebase and their products here.

  2. Flutter is a really great framework to get your apps done for multiple platforms at once, thanks to its cross platform compatibility! If you don't want to spend time creating app for multiple devices, flutter's the way to go. I personally think flutter web is yet to grow, but it will overtime, afterall, it's opensource framework by Google. I'd suggest this idea 8.5/10

  3. Flutter docs are pretty well written and an beginner could get through it with some video examples (included in documentation) as well. In case something you want to use isn't supported in newer version of flutter, the text editor will show a line over the code meaning that it is deprecated and wouldn't be supported. There's always an alternative, which you could find using flutter docs or YouTube. Flutter docs are optimised for beginners 9/10

远程服务器上的数据持久性

歌入人心 2025-02-06 19:55:03

我能够使用像Hive这样的Hive在我的应用程序中的缩略图上在Flutter Web上完成此操作:

在我的Hive Service中,

  static const _thumbnailsKey = 'thumbnails';
  static late Box<List<int>> _thumbnailsBox;

  HiveService._();

  static Future<void> initialize() async {
    await Hive.initFlutter();

    _thumbnailsBox = await Hive.openBox(_thumbnailsKey);
  }

  static Future<void> addThumbnailData({
    required String key,
    required List<int> data,
  }) async {
    await _thumbnailsBox.put(key, data);
  }

  static Uint8List getThumbnailData({required String key}) {
    final bytes = _thumbnailsBox.get(key);

    if (bytes == null) return Uint8List.fromList([]);

    return Uint8List.fromList(bytes);
  }

我的Image Downloader Service

import 'dart:typed_data';

import 'package:http/http.dart' as http;

class ImageService {
  ImageService._();

  static Future<Uint8List> getImageData(String url) async {
    Uri uri = Uri.parse(url);

    final response = await http.get(uri);

    return response.bodyBytes;
  }
}

在我的Widget的ViewModel(或您喜欢的任何地方)

我都在使用 getx 所以我用_imagedata.value = ...

  Future<void> _getThumbnailData() async {
    final cachedThumbnailData = HiveService.getThumbnailData(key: 'someKey');

    // This is where the magic happens
    if (cachedThumbnailData.isNotEmpty) {
      _imageData.value = cachedThumbnailData;
      return;
    }

    // Otherwise fetch the image data
    // In my case it's from a url
    final imageData = await ImageService.getImageData(thumbnailUrl);

    if (imageData.isEmpty) return;

    // Update Hive for the next time you need the image
    // You could also put this wherever you fetch your images
    await HiveService.addThumbnailData(
      key: reactionReportGroup.timestampNameKey,
      data: imageData,
    );

    _imageData.value = imageData;
  }

现在您可以使用 memoryImage(_viewmodel.imodel.imodagegageata) image.memory(_viewModel.imagedata)

I was able to accomplish this on Flutter Web for thumbnails in my app using Hive like so:

In My Hive Service

  static const _thumbnailsKey = 'thumbnails';
  static late Box<List<int>> _thumbnailsBox;

  HiveService._();

  static Future<void> initialize() async {
    await Hive.initFlutter();

    _thumbnailsBox = await Hive.openBox(_thumbnailsKey);
  }

  static Future<void> addThumbnailData({
    required String key,
    required List<int> data,
  }) async {
    await _thumbnailsBox.put(key, data);
  }

  static Uint8List getThumbnailData({required String key}) {
    final bytes = _thumbnailsBox.get(key);

    if (bytes == null) return Uint8List.fromList([]);

    return Uint8List.fromList(bytes);
  }

My Image Downloader Service

import 'dart:typed_data';

import 'package:http/http.dart' as http;

class ImageService {
  ImageService._();

  static Future<Uint8List> getImageData(String url) async {
    Uri uri = Uri.parse(url);

    final response = await http.get(uri);

    return response.bodyBytes;
  }
}

In My Widget's ViewModel (or anywhere you like)

I'm using GetX so I update my Image widget with _imageData.value = ...

  Future<void> _getThumbnailData() async {
    final cachedThumbnailData = HiveService.getThumbnailData(key: 'someKey');

    // This is where the magic happens
    if (cachedThumbnailData.isNotEmpty) {
      _imageData.value = cachedThumbnailData;
      return;
    }

    // Otherwise fetch the image data
    // In my case it's from a url
    final imageData = await ImageService.getImageData(thumbnailUrl);

    if (imageData.isEmpty) return;

    // Update Hive for the next time you need the image
    // You could also put this wherever you fetch your images
    await HiveService.addThumbnailData(
      key: reactionReportGroup.timestampNameKey,
      data: imageData,
    );

    _imageData.value = imageData;
  }

Now you can use either MemoryImage(_viewModel.imageData) or Image.memory(_viewModel.imageData)

如何使用Hive将图像存储在LocalDB中?

歌入人心 2025-02-06 14:26:37

我通过执行以下操作解决了它:

reminder_list = [sms_df, upi_df, flash_df, email_df, ivr_df]
for n,df in enumerate(reminder_list):
    for min_date in df.cycle_end_date.unique():
        max_date = datetime.strptime(min_date, '%Y-%m-%d %H:%M:%S') + timedelta(days=75)
        days = pd.date_range(datetime.strptime(min_date, '%Y-%m-%d %H:%M:%S'),max_date,freq='d')
        event_date_df = pd.DataFrame(days.values).rename(columns={0:'event_date'}).drop_duplicates()
        event_date_df['cycle_end_date'] = min_date
        event_date_df['event_date'] = event_date_df['event_date'].apply(lambda x : x.strftime('%Y-%m-%d %H:%M:%S'))
        reminder_list[n] = df
        df = df.append(event_date_df.merge(df[df.cycle_end_date == min_date], on=['cycle_end_date','event_date'], how='left'))

I solved it by doing the following:

reminder_list = [sms_df, upi_df, flash_df, email_df, ivr_df]
for n,df in enumerate(reminder_list):
    for min_date in df.cycle_end_date.unique():
        max_date = datetime.strptime(min_date, '%Y-%m-%d %H:%M:%S') + timedelta(days=75)
        days = pd.date_range(datetime.strptime(min_date, '%Y-%m-%d %H:%M:%S'),max_date,freq='d')
        event_date_df = pd.DataFrame(days.values).rename(columns={0:'event_date'}).drop_duplicates()
        event_date_df['cycle_end_date'] = min_date
        event_date_df['event_date'] = event_date_df['event_date'].apply(lambda x : x.strftime('%Y-%m-%d %H:%M:%S'))
        reminder_list[n] = df
        df = df.append(event_date_df.merge(df[df.cycle_end_date == min_date], on=['cycle_end_date','event_date'], how='left'))

如何循环浏览列表并为PANDAS中该列表中的每个数据框架制作新的数据框架?

歌入人心 2025-02-06 14:22:58

是的,通过使用拥有的实体,这在EF核心中可能是可能的。 docs ,您可以拥有这样的:

[Owned]
public class StreetAddress
{
    public string Street { get; set; }
    public string City { get; set; }
}

public class Order
{
    public int Id { get; set; }
    public StreetAddress ShippingAddress { get; set; }
}

或者,如果您喜欢使用Fluent API:

modelBuilder.Entity<Order>().OwnsOne(p => p.ShippingAddress);

它会给您这样的表:

“在此处输入图像说明”

Yes, this is possible in EF Core by using owned entities. The docs explain it pretty well but, for example, you can have this:

[Owned]
public class StreetAddress
{
    public string Street { get; set; }
    public string City { get; set; }
}

public class Order
{
    public int Id { get; set; }
    public StreetAddress ShippingAddress { get; set; }
}

Or if you prefer using the fluent API:

modelBuilder.Entity<Order>().OwnsOne(p => p.ShippingAddress);

Which will give you a table like this:

enter image description here

有可能具有“子模型”与实体框架?

歌入人心 2025-02-06 11:43:36

我设法找到了一个解决方案,但是我不得不切换到 selenium-wire

from seleniumwire import webdriver

wd = webdriver.Firefox()
res=wd.get("https://portal.azure.com/")
input("Press Enter to continue...") # After loggin in 
for request in wd.requests:
    print("HEADERS: "+ str(request.headers)) # The bearer can be found here

此解决方案不是最佳的,因为我仍然可以隔离我知道承载者的请求,但是尽管有生锈,但确实有效。

I managed to find a solution, however I had to switch to selenium-wire,

from seleniumwire import webdriver

wd = webdriver.Firefox()
res=wd.get("https://portal.azure.com/")
input("Press Enter to continue...") # After loggin in 
for request in wd.requests:
    print("HEADERS: "+ str(request.headers)) # The bearer can be found here

This solution is not optimal as I could still isolate the requests where I know the Bearer is placed but, despite its rustiness, it does work.

用Selenium检索Azure AD授权承载者

歌入人心 2025-02-06 01:48:20

在此答案中,我将考虑以下实际示例:

  1. pandas.concat

  2. pandas。 dataframe.merge 从一个和另一个列的索引合并数据框。

我们将在每种情况下使用不同的数据框。


1。 a>

使用以下 dataframes 具有相同的列名:

  • price2018 带尺寸(8784,5) P>

     年度每日小时价格
    0 2018 1 1 1 6.74
    1 2018 1 1 2 4.74
    2 2018 1 1 3 3.66
    3 2018 1 1 4 2.30
    4 2018 1 1 5 2.30
    5 2018 1 1 6 2.06
    6 2018 1 1 7 2.06
    7 2018 1 1 8 2.06
    8 2018 1 1 9 2.30
    9 2018 1 1 10 2.30
     
  • Price2019 带尺寸(8760,5)

     年度每日小时价格
    0 2019 1 1 1 66.88
    1 2019 1 1 2 66.88
    2 2019 1 1 3 66.00
    3 2019 1 1 4 63.64
    4 2019 1 1 5 58.85
    5 2019 1 1 6 55.47
    6 2019 1 1 7 56.00
    7 2019 1 1 8 61.09
    8 2019 1 1 9 61.01
    9 2019 1 1 10 61.00
     

可以使用 pandas.concat ,简单地

import pandas as pd

frames = [Price2018, Price2019]

df_merged = pd.concat(frames)

从中导致具有size (17544,5)的数据框架

如果一个人想清楚地了解发生的事情,它可以像这样起作用

”


2。 代码>

在本节中,我们将考虑一个特定情况:合并一个数据框的索引和另一个数据框的列

假设一个人具有 geo ,带有 54 列,是 date type dateTime64 [NS ]

                 Date         1         2  ...        51        52        53
0 2010-01-01 00:00:00  0.565919  0.892376  ...  0.593049  0.775082  0.680621
1 2010-01-01 01:00:00  0.358960  0.531418  ...  0.734619  0.480450  0.926735
2 2010-01-01 02:00:00  0.531870  0.221768  ...  0.902369  0.027840  0.398864
3 2010-01-01 03:00:00  0.475463  0.245810  ...  0.306405  0.645762  0.541882
4 2010-01-01 04:00:00  0.954546  0.867960  ...  0.912257  0.039772  0.627696

和dataFrame Price 具有一列,其价格为 Price> ,索引对应于日期( date ),

                     Price
Date                      
2010-01-01 00:00:00  29.10
2010-01-01 01:00:00   9.57
2010-01-01 02:00:00   0.00
2010-01-01 03:00:00   0.00
2010-01-01 04:00:00   0.00

以便合并它们,一个人可以使用 .merge 如下所示

df_merged = pd.merge(Price, Geo, left_index=True, right_on='Date')

,其中 geo Price 是以前的数据框架。

这将导致以下数据框架

   Price                Date         1  ...        51        52        53
0  29.10 2010-01-01 00:00:00  0.565919  ...  0.593049  0.775082  0.680621
1   9.57 2010-01-01 01:00:00  0.358960  ...  0.734619  0.480450  0.926735
2   0.00 2010-01-01 02:00:00  0.531870  ...  0.902369  0.027840  0.398864
3   0.00 2010-01-01 03:00:00  0.475463  ...  0.306405  0.645762  0.541882
4   0.00 2010-01-01 04:00:00  0.954546  ...  0.912257  0.039772  0.627696

In this answer, I will consider practical examples of:

  1. pandas.concat

  2. pandas.DataFrame.merge to merge dataframes from the index of one and the column of another one.

We will be using different dataframes for each of the cases.


1. pandas.concat

Considering the following DataFrames with the same column names:

  • Price2018 with size (8784, 5)

       Year  Month  Day  Hour  Price
    0  2018      1    1     1   6.74
    1  2018      1    1     2   4.74
    2  2018      1    1     3   3.66
    3  2018      1    1     4   2.30
    4  2018      1    1     5   2.30
    5  2018      1    1     6   2.06
    6  2018      1    1     7   2.06
    7  2018      1    1     8   2.06
    8  2018      1    1     9   2.30
    9  2018      1    1    10   2.30
    
  • Price2019 with size (8760, 5)

       Year  Month  Day  Hour  Price
    0  2019      1    1     1  66.88
    1  2019      1    1     2  66.88
    2  2019      1    1     3  66.00
    3  2019      1    1     4  63.64
    4  2019      1    1     5  58.85
    5  2019      1    1     6  55.47
    6  2019      1    1     7  56.00
    7  2019      1    1     8  61.09
    8  2019      1    1     9  61.01
    9  2019      1    1    10  61.00
    

One can combine them using pandas.concat, by simply

import pandas as pd

frames = [Price2018, Price2019]

df_merged = pd.concat(frames)

Which results in a DataFrame with size (17544, 5)

If one wants to have a clear picture of what happened, it works like this

How concat works

(Source)


2. pandas.DataFrame.merge

In this section, we will consider a specific case: merging the index of one dataframe and the column of another dataframe.

Let's say one has the dataframe Geo with 54 columns, being one of the columns the Date, which is of type datetime64[ns].

                 Date         1         2  ...        51        52        53
0 2010-01-01 00:00:00  0.565919  0.892376  ...  0.593049  0.775082  0.680621
1 2010-01-01 01:00:00  0.358960  0.531418  ...  0.734619  0.480450  0.926735
2 2010-01-01 02:00:00  0.531870  0.221768  ...  0.902369  0.027840  0.398864
3 2010-01-01 03:00:00  0.475463  0.245810  ...  0.306405  0.645762  0.541882
4 2010-01-01 04:00:00  0.954546  0.867960  ...  0.912257  0.039772  0.627696

And the dataframe Price that has one column with the price named Price, and the index corresponds to the dates (Date)

                     Price
Date                      
2010-01-01 00:00:00  29.10
2010-01-01 01:00:00   9.57
2010-01-01 02:00:00   0.00
2010-01-01 03:00:00   0.00
2010-01-01 04:00:00   0.00

In order to merge them, one can use pandas.DataFrame.merge as follows

df_merged = pd.merge(Price, Geo, left_index=True, right_on='Date')

where Geo and Price are the previous dataframes.

That results in the following dataframe

   Price                Date         1  ...        51        52        53
0  29.10 2010-01-01 00:00:00  0.565919  ...  0.593049  0.775082  0.680621
1   9.57 2010-01-01 01:00:00  0.358960  ...  0.734619  0.480450  0.926735
2   0.00 2010-01-01 02:00:00  0.531870  ...  0.902369  0.027840  0.398864
3   0.00 2010-01-01 03:00:00  0.475463  ...  0.306405  0.645762  0.541882
4   0.00 2010-01-01 04:00:00  0.954546  ...  0.912257  0.039772  0.627696

熊猫合并101

歌入人心 2025-02-05 23:26:36

您可以从每个组中删除最后一个bezier,用L线L更改中间的M命令,然后用z这样的路径关闭路径:

svg{width:90vh}
<svg viewBox="300 100 150 150">
  <path fill="red" d="
        M 326 147
        C 329 135 345 130 355 137
        C 376 150 385 188 362 197
        L 381 222
        C 418 214 408 157 385 127   
        C 370 108 340 96 326 115
        z
    ">
  </path>

You can delete the last bezier from every group, change the M command in the middle with a line L and close the path with a Z like so:

svg{width:90vh}
<svg viewBox="300 100 150 150">
  <path fill="red" d="
        M 326 147
        C 329 135 345 130 355 137
        C 376 150 385 188 362 197
        L 381 222
        C 418 214 408 157 385 127   
        C 370 108 340 96 326 115
        z
    ">
  </path>

SVG弯曲区域路径(MC) - 启动时结束(切割)

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

更多

友情链接

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文