向地狱狂奔

文章 评论 浏览 30

向地狱狂奔 2025-02-20 20:25:25

使用多个键来完成此操作的动态方法:

  • 从每个col/ofers to Coll of Cold
  • 或converse to
  • Coll of Colle/tovers forter toruts unique unique utvers unters utvers to and the Adgs witth width zeropad zeropad为每个对象基于indexof(value)键keys值
  • sort使用使用caclutated重量

“在此处输入图像描述”

Object.defineProperty(Array.prototype, 'orderBy', {
value: function(sorts) { 
    sorts.map(sort => {            
        sort.uniques = Array.from(
            new Set(this.map(obj => obj[sort.key]))
        );
        
        sort.uniques = sort.uniques.sort((a, b) => {
            if (typeof a == 'string') {
                return sort.inverse ? b.localeCompare(a) : a.localeCompare(b);
            }
            else if (typeof a == 'number') {
                return sort.inverse ? b - a : a - b;
            }
            else if (typeof a == 'boolean') {
                let x = sort.inverse ? (a === b) ? 0 : a? -1 : 1 : (a === b) ? 0 : a? 1 : -1;
                return x;
            }
            return 0;
        });
    });

    const weightOfObject = (obj) => {
        let weight = "";
        sorts.map(sort => {
            let zeropad = `${sort.uniques.length}`.length;
            weight += sort.uniques.indexOf(obj[sort.key]).toString().padStart(zeropad, '0');
        });
        //obj.weight = weight; // if you need to see weights
        return weight;
    }

    this.sort((a, b) => {
        return weightOfObject(a).localeCompare( weightOfObject(b) );
    });
    
    return this;
}
});

使用:

// works with string, number and boolean
let sortered = your_array.orderBy([
    {key: "type", inverse: false}, 
    {key: "title", inverse: false},
    {key: "spot", inverse: false},
    {key: "internal", inverse: true}
]);

“在此处输入图像说明”

A dynamic way to do that with MULTIPLE keys:

  • filter unique values from each col/key of sort
  • put in order or reverse it
  • add weights width zeropad for each object based on indexOf(value) keys values
  • sort using caclutated weights

enter image description here

Object.defineProperty(Array.prototype, 'orderBy', {
value: function(sorts) { 
    sorts.map(sort => {            
        sort.uniques = Array.from(
            new Set(this.map(obj => obj[sort.key]))
        );
        
        sort.uniques = sort.uniques.sort((a, b) => {
            if (typeof a == 'string') {
                return sort.inverse ? b.localeCompare(a) : a.localeCompare(b);
            }
            else if (typeof a == 'number') {
                return sort.inverse ? b - a : a - b;
            }
            else if (typeof a == 'boolean') {
                let x = sort.inverse ? (a === b) ? 0 : a? -1 : 1 : (a === b) ? 0 : a? 1 : -1;
                return x;
            }
            return 0;
        });
    });

    const weightOfObject = (obj) => {
        let weight = "";
        sorts.map(sort => {
            let zeropad = `${sort.uniques.length}`.length;
            weight += sort.uniques.indexOf(obj[sort.key]).toString().padStart(zeropad, '0');
        });
        //obj.weight = weight; // if you need to see weights
        return weight;
    }

    this.sort((a, b) => {
        return weightOfObject(a).localeCompare( weightOfObject(b) );
    });
    
    return this;
}
});

Use:

// works with string, number and boolean
let sortered = your_array.orderBy([
    {key: "type", inverse: false}, 
    {key: "title", inverse: false},
    {key: "spot", inverse: false},
    {key: "internal", inverse: true}
]);

enter image description here

如何通过多个字段对对象进行排序?

向地狱狂奔 2025-02-20 18:37:17

它不起作用,因为您设置了 index dd2数组的索引,

{DD2.map((x, i) => (
   <option key={i} value={x.content}>{x.content}</option> 
))}

因此当您的DD2数组更改时,该选项仍然相同,因为它具有相同的键。因此,只需将您的钥匙更改为独特的内容即可识别列表中的项目

{DD2.map((x, i) => (
     <option key={x.content} value={x.content}>
         {x.content}
     </option>
))}

It's not working because you set key of option by index of DD2 array

{DD2.map((x, i) => (
   <option key={i} value={x.content}>{x.content}</option> 
))}

so when your DD2 array change, the option still be the same because it have the same key. So just change your key to something unique to identifies the items in the list

{DD2.map((x, i) => (
     <option key={x.content} value={x.content}>
         {x.content}
     </option>
))}

React Hooks&lt; select&gt;&lt; option&gt; gt; 2个下拉问题

向地狱狂奔 2025-02-20 13:28:16

您有许多小的(有些不那么小)会导致您的问题。您的主要问题是将tcars* p_2传递给readbinaryfile(),并用p_2 = malloc(sizeof(tcars)*(* pc)); 每次。为什么?

每个调用malloc()返回带有新地址的新内存块。您可以在每个新调用中覆盖p_2的地址,创建一个内存泄漏并丢失最后一个调用之前存储的数据。相反,您需要realloc()重新分配较大的内存块,然后将现有数据复制到新的较大块,以便您可以在AS上添加下一个tcars价值的数据重新分配的块的末端。

如果您是从一个文件读取数据,则无需将p_2作为一个开始。只需在readbinaryfile()realloc()中声明一个新指针,然后添加每个tcars末尾的数据,然后返回新分配的新分配的数据指针。 (您必须验证每个分配和重新分配)

您选择的void for writebinaryfile()将隐藏遇到的任何错误创建或写入新文件。您必须验证每个输入/输出文件操作,尤其是如果以后将在程序中使用的数据。类型int返回0的简单选择,而 1 成功(或vice-vices-vices-vices-vissa,to you you)就是您的全部需要。这样,您可以在文件创建或写作过程中处理任何错误,而不是盲目地承担成功。

一个更细微的问题/错误是您使用ParkingLot1使用malloc()的分配。理想情况下,您将使用calloc()或使用memset设置所有字节零。为什么?您将整个tcars struct写入文件。 malloc()不会初始化分配的内存。这意味着company名称(nul终止字符)和16字节的末端之间的所有字符将不限化。虽然这不会引起您的读或写入问题,但要确保将所有数据写入文件的所有数据都是初始化的数据,却更好。否则,检查文件的内容将显示写入文件中的非初始化值的块。

另一个小样式问题是指针声明中的'*'通常与变量而不是类型有关。为什么?

    Tcars* a, b, c;

最上面的声明当然不会声明tcars的3个分数,而是声明指针a和两个类型tcars带有自动存储的结构持续时间bc。写作:

    Tcars *a, b, c;

清楚。

最后,不要在功能中使用 magicnumbers 或硬码文件名。您不需要重新编译代码即可读取或编写其他文件名。可以使用“ cars.dat”作为main()中的默认文件名,但要么将文件名为第一个参数(这是是什么) int argc,char ** argv参数到main()是为)或提示用户获取文件名并将其作为输入。 316 magicnumbers 。如果您需要常量,则#define它们或使用全局enum

将其完全放置,您可以做类似的事情,从数据文件中读取未知数的tcars :(

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define NCARS 3       /* if you need a constant, #define one (or more) */
#define COMPANY 16

typedef struct Cars {
    int years;
    char company[COMPANY];
} Tcars;

/* returns 1 on success 0 on error */
int WriteBinaryFile (char *file_name, Tcars *p_1, size_t nelem)
{
  FILE *f;
  size_t size = sizeof *p_1;
  
  f = fopen (file_name, "wb");
  if (!f) {   /* validate file open for writing */
    perror ("fopen-file_name-write");
    return 0;
  }
  
  /* validate that nelem blocks of size are written to file */
  if (fwrite (p_1, size, nelem, f) != nelem) {
    return 0;
  }
  
  if (fclose (f)) {       /* validate close-after-write */
    perror ("fclose-f");
    return 0;
  }
  
  return 1;
}

/* returns pointer to allocated block holding ncars cars on success,
 * NULL on failure to read any cars from file_name.
 */
Tcars *ReadBinaryFile (char *file_name, size_t *ncars)
{
  FILE *f;
  
  Tcars *tcars = NULL, temp;
  size_t nelem = *ncars, size = sizeof (Tcars);
  
  f = fopen (file_name, "rb");
  if (!f) {
    perror ("fopen-file_name-read");
    return NULL;
  }
  
  while (fread (&temp, size, 1, f) == 1) {
    /* always realloc to a temporary pointer */
    void *tempptr = realloc (tcars, (nelem + 1) * size);
    if (!tempptr) {   /* validate realloc succeeds or handle error */
      perror ("realloc-tcars");
      break;
    }
    tcars = tempptr;                      /* assign reallocated block */
    memcpy (tcars + nelem, &temp, size);  /* copy new car to end of block */
    nelem += 1;
  }
  
  fclose (f);
  *ncars = nelem;
  
  return tcars;
}

/* void is fine for print functions with no bearing on the 
 * continued operation of your code.
 */
void prn_cars (Tcars *cars, size_t nelem)
{
  for (size_t i = 0; i < nelem; i++) {
    printf ("%4d  %s\n", cars[i].years, cars[i].company);
  }
}

int main (int argc, char **argv)
{
  /* read from filename provided as 1st argument ("cars.dat" by default) */
  char *filename = argc > 1 ? argv[1] : "cars.dat";
  /* must use calloc() on ParkingLot1 or zero memory to avoid writing
   * unintialized characters (rest of company) to file.
   */
  Tcars *ParkingLot1 = calloc (NCARS, sizeof(Tcars)),
        *ParkingLot2 = NULL;
  size_t cars_amount = 0;
  
  if (!ParkingLot1) {   /* validate EVERY allocation */
    perror ("calloc-ParkingLot1");
    return 1;
  }
  
  for (int i = 0; i < NCARS; i++) {
    ParkingLot1[i].years = 2000 + i;
  }
  
  strcpy (ParkingLot1[0].company, "Fiat");
  strcpy (ParkingLot1[1].company, "Ford");
  strcpy (ParkingLot1[2].company,"Toyota");
  
  /* validate WriteBinaryFile succeeds or handle error */
  if (!WriteBinaryFile (filename, ParkingLot1, NCARS)) {
    return 1;
  }
  
  ParkingLot2 = ReadBinaryFile (filename, &cars_amount);
  
  if (ParkingLot2) {  /* validate ReadBinaryFile succeeds or handle error */
    prn_cars (ParkingLot2, cars_amount);    /* output cars read from file */
    free (ParkingLot2);                     /* free if ParkingLot2 not NULL */
  }
  
  free(ParkingLot1);  /* free ParkingLot1 */
}

注意:您始终检查的返回fclose() after-a-write捕获任何文件错误和错误将数据冲入文件,而在fwrite()呼叫时都无法捕获的文件)

也要注意在男人页面中freadfwrite他们可以读取或写入少于您要求的字节数(或元素)。 A 短阅读可能代表或可能不代表错误或过早的文件结束,您需要调用ferror()feof()确定发生了哪些(如果有)。虽然直接从磁盘读取的文件并不像网络读取和写入那样容易简短阅读,但无论在何处读取或写入数据的位置,完整的实现都会防止简短阅读。进一步调查将留给您。

示例使用/输出

$ ./fwrite_fread_cars dat/cars.dat
2000  Fiat
2001  Ford
2002  Toyota

内存使用/错误检查

在您编写的任何代码中都动态分配内存,您对分配的任何内存块有2个责任 :(1)始终保留一个指向记忆块的起始地址 so,(2)当不再需要时,它可以是 freed

必须使用内存错误检查程序来确保您不尝试访问内存或在分配块的边界之外/之外访问内存或写入,试图在非初始化的值上读取或以有条件的跳跃来确认您可以释放所有分配的内存。

对于Linux valgrind是正常的选择。每个平台都有类似的内存检查器。它们都易于使用,只需通过它运行您的程序。

$ valgrind ./fwrite_fread_cars dat/cars.dat
==7237== Memcheck, a memory error detector
==7237== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==7237== Using Valgrind-3.18.1 and LibVEX; rerun with -h for copyright info
==7237== Command: ./fwrite_fread_cars dat/cars.dat
==7237==
2000  Fiat
2001  Ford
2002  Toyota
==7237==
==7237== HEAP SUMMARY:
==7237==     in use at exit: 0 bytes in 0 blocks
==7237==   total heap usage: 9 allocs, 9 frees, 10,340 bytes allocated
==7237==
==7237== All heap blocks were freed -- no leaks are possible
==7237==
==7237== For lists of detected and suppressed errors, rerun with: -s
==7237== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

始终确认您已经释放了所有已分配的内存,并且没有内存错误。

看看事情,让我知道您是否有任何疑问。

You have a number of small (and some not so small errors) that are causing you problems. Your primary problem is passing Tcars* p_2 to ReadBinaryFile() and allocating with p_2 = malloc(sizeof(Tcars) * (*pc)); each time. Why?

Each call to malloc() returns a new block of memory with a new and different address. You overwrite the address of p_2 with each new call, creating a memory leak and losing the data stored prior to the last call. Instead, you need to realloc() to reallocate a larger block of memory and copy your existing data to the new larger block so you can add the next Tcars worth of data at the end of the reallocated block.

If you are reading data from one file, then there is no need to pass p_2 as a parameter to begin with. Simply declare a new pointer in ReadBinaryFile() and realloc() and add each Tcars worth of data at the end and then return the newly allocated pointer. (you must validate every allocation and reallocation)

Your choice of void for WriteBinaryFile() will conceal any error encountered creating or writing to your new file. You must validate EVERY input/output file operation, especially if the data written will be used later in your program. A simple choice of return of type int returning 0 for failure and 1 for success (or vice-versa, up to you) is all you need. That way you can handle any error during file creation or writing and not blindly assume success.

A slightly more subtle issue/error is your allocation for ParkingLot1 using malloc(). Ideally you would use calloc() or use memset to set all bytes zero. Why? You write the entire Tcars struct to the file. malloc() does not initialize the memory allocated. That means all characters in the company name between the end of the name (the nul-terminating character) and the end of the 16 bytes of storage will be uninitialized. While that will not cause problems with your read or write, it is far better to ensure all data being written to your file is initialized data. Otherwise examining the contents of the file will show blocks of uninitialized values written to the file.

Another small style issue is the '*' in the declaration of a pointer generally goes with the variable and not the type. Why?

    Tcars* a, b, c;

The declaration above most certainly does not declare 3-pointers of type Tcars, instead it declares pointer a and two struct of type Tcars with automatic storage duration b, and c. Writing:

    Tcars *a, b, c;

makes that clear.

Lastly, don't use MagicNumbers or hardcode filenames in your functions. You shouldn't need to recompile your code just to read or write a different filename. It's fine to use "cars.dat" as a default filename in main(), but either take the filenames as the 1st argument to your program (that's what int argc, char **argv parameters to main() are for) or prompt the user for a filename and take it as input. 3 and 16 are MagicNumbers. If you need a constant, #define them or use a global enum.

Putting it altogether, you could do something similar to the following to read an unknown number of Tcars from your data file:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define NCARS 3       /* if you need a constant, #define one (or more) */
#define COMPANY 16

typedef struct Cars {
    int years;
    char company[COMPANY];
} Tcars;

/* returns 1 on success 0 on error */
int WriteBinaryFile (char *file_name, Tcars *p_1, size_t nelem)
{
  FILE *f;
  size_t size = sizeof *p_1;
  
  f = fopen (file_name, "wb");
  if (!f) {   /* validate file open for writing */
    perror ("fopen-file_name-write");
    return 0;
  }
  
  /* validate that nelem blocks of size are written to file */
  if (fwrite (p_1, size, nelem, f) != nelem) {
    return 0;
  }
  
  if (fclose (f)) {       /* validate close-after-write */
    perror ("fclose-f");
    return 0;
  }
  
  return 1;
}

/* returns pointer to allocated block holding ncars cars on success,
 * NULL on failure to read any cars from file_name.
 */
Tcars *ReadBinaryFile (char *file_name, size_t *ncars)
{
  FILE *f;
  
  Tcars *tcars = NULL, temp;
  size_t nelem = *ncars, size = sizeof (Tcars);
  
  f = fopen (file_name, "rb");
  if (!f) {
    perror ("fopen-file_name-read");
    return NULL;
  }
  
  while (fread (&temp, size, 1, f) == 1) {
    /* always realloc to a temporary pointer */
    void *tempptr = realloc (tcars, (nelem + 1) * size);
    if (!tempptr) {   /* validate realloc succeeds or handle error */
      perror ("realloc-tcars");
      break;
    }
    tcars = tempptr;                      /* assign reallocated block */
    memcpy (tcars + nelem, &temp, size);  /* copy new car to end of block */
    nelem += 1;
  }
  
  fclose (f);
  *ncars = nelem;
  
  return tcars;
}

/* void is fine for print functions with no bearing on the 
 * continued operation of your code.
 */
void prn_cars (Tcars *cars, size_t nelem)
{
  for (size_t i = 0; i < nelem; i++) {
    printf ("%4d  %s\n", cars[i].years, cars[i].company);
  }
}

int main (int argc, char **argv)
{
  /* read from filename provided as 1st argument ("cars.dat" by default) */
  char *filename = argc > 1 ? argv[1] : "cars.dat";
  /* must use calloc() on ParkingLot1 or zero memory to avoid writing
   * unintialized characters (rest of company) to file.
   */
  Tcars *ParkingLot1 = calloc (NCARS, sizeof(Tcars)),
        *ParkingLot2 = NULL;
  size_t cars_amount = 0;
  
  if (!ParkingLot1) {   /* validate EVERY allocation */
    perror ("calloc-ParkingLot1");
    return 1;
  }
  
  for (int i = 0; i < NCARS; i++) {
    ParkingLot1[i].years = 2000 + i;
  }
  
  strcpy (ParkingLot1[0].company, "Fiat");
  strcpy (ParkingLot1[1].company, "Ford");
  strcpy (ParkingLot1[2].company,"Toyota");
  
  /* validate WriteBinaryFile succeeds or handle error */
  if (!WriteBinaryFile (filename, ParkingLot1, NCARS)) {
    return 1;
  }
  
  ParkingLot2 = ReadBinaryFile (filename, &cars_amount);
  
  if (ParkingLot2) {  /* validate ReadBinaryFile succeeds or handle error */
    prn_cars (ParkingLot2, cars_amount);    /* output cars read from file */
    free (ParkingLot2);                     /* free if ParkingLot2 not NULL */
  }
  
  free(ParkingLot1);  /* free ParkingLot1 */
}

(note: you always check the return of fclose() after-a-write to catch any file errors and error flushing the data to the file that can't be caught at the time of the fwrite() call)

Also note in the man page for fread and fwrite they can read or write less than the number of byte (or elements) you request. A short-read may or may not represent an error or premature end-of-file and you need to call ferror() and feof() to determine which, if any, occurred. While direct file reads from disk are not as prone to short-reads as network reads and writes, a full implementation would protect against a short-read regardless of where the data is being read from or written to. Further investigation is left to you.

Example Use/Output

$ ./fwrite_fread_cars dat/cars.dat
2000  Fiat
2001  Ford
2002  Toyota

Memory Use/Error Check

In any code you write that dynamically allocates memory, you have 2 responsibilities regarding any block of memory allocated: (1) always preserve a pointer to the starting address for the block of memory so, (2) it can be freed when it is no longer needed.

It is imperative that you use a memory error checking program to ensure you do not attempt to access memory or write beyond/outside the bounds of your allocated block, attempt to read or base a conditional jump on an uninitialized value, and finally, to confirm that you free all the memory you have allocated.

For Linux valgrind is the normal choice. There are similar memory checkers for every platform. They are all simple to use, just run your program through it.

$ valgrind ./fwrite_fread_cars dat/cars.dat
==7237== Memcheck, a memory error detector
==7237== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==7237== Using Valgrind-3.18.1 and LibVEX; rerun with -h for copyright info
==7237== Command: ./fwrite_fread_cars dat/cars.dat
==7237==
2000  Fiat
2001  Ford
2002  Toyota
==7237==
==7237== HEAP SUMMARY:
==7237==     in use at exit: 0 bytes in 0 blocks
==7237==   total heap usage: 9 allocs, 9 frees, 10,340 bytes allocated
==7237==
==7237== All heap blocks were freed -- no leaks are possible
==7237==
==7237== For lists of detected and suppressed errors, rerun with: -s
==7237== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

Always confirm that you have freed all memory you have allocated and that there are no memory errors.

Look things over and let me know if you have any question.

当我不知道二进制文件中的数据量时,如何使用架子和fwrite

向地狱狂奔 2025-02-19 18:42:37

你肯定可以。我最喜欢的方法是如下:

type NumberLogger = (n: number) => void;

function preloadResources(informLoadPct: NumberLogger )
{
  let pct = 100;
  informLoadPct(pct);

}

如果您需要在对象内传递此方法,则可以做同样的事情。

type NumberLogger = (n: number) => void;

type NumberLoggerProps = {
    logger: NumberLogger;
}

// or

type NumberLoggerProps = {
    logger: (n: number) => void;
}

// or

type NumberLoggerProps = {
    logger(n: number): void;
}

请参阅 typescript文档的更多信息。

You sure can. My prefered way is as follows:

type NumberLogger = (n: number) => void;

function preloadResources(informLoadPct: NumberLogger )
{
  let pct = 100;
  informLoadPct(pct);

}

If you ever need to pass this inside an object, you can do the same thing.

type NumberLogger = (n: number) => void;

type NumberLoggerProps = {
    logger: NumberLogger;
}

// or

type NumberLoggerProps = {
    logger: (n: number) => void;
}

// or

type NumberLoggerProps = {
    logger(n: number): void;
}

See more in the Typescript documentation.

如何指示功能参数函数输入类型

向地狱狂奔 2025-02-19 02:43:35

我不知道在全球范围内做到这一点是否会很容易(描述的孔隙函数似乎在注册表级别不起作用)。

在存储库级别上,尽管您可以使用其Terraform中的示例之类的内容: https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/ecr_repository_policy_policy

resource "aws_ecr_repository" "example" {
  name = "example-repo" # Or replace with a set of repositories/ a data reference
}

data "aws_iam_policy_document" "example" {
  statement {
    sid    = "new policy"
    effect = "Allow"

    principals {
      type        = "AWS"
      identifiers = ["123456789012"]
    }

    actions = [
      "ecr:DescribeImages"
    ]
  }
}

resource "aws_ecr_repository_policy" "example" {
  repository = aws_ecr_repository.example.name
  policy     = data.aws_iam_policy_document.example.json
}

I don't know if it'll be all that easy to do it globally (the describeRepository function seems to not work at the registry level).

At the repository level though you could use something like the example from their terraform: https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/ecr_repository_policy

resource "aws_ecr_repository" "example" {
  name = "example-repo" # Or replace with a set of repositories/ a data reference
}

data "aws_iam_policy_document" "example" {
  statement {
    sid    = "new policy"
    effect = "Allow"

    principals {
      type        = "AWS"
      identifiers = ["123456789012"]
    }

    actions = [
      "ecr:DescribeImages"
    ]
  }
}

resource "aws_ecr_repository_policy" "example" {
  repository = aws_ecr_repository.example.name
  policy     = data.aws_iam_policy_document.example.json
}

如何从另一个帐户中描述重新定位?

向地狱狂奔 2025-02-17 15:35:55

只需按照此链接使用M1/M2芯片将Java 1.8安装到Mac中。苹果使用 rosetta2 用于Mac向Apple Silicon的Mac Transition。

https://www.oracle.com/java/technologies/downloads/# Java8-Mac

向下滚动至Java 1.8,
转到MacOS版本,
单击M2芯片的ARMX64版本,
遵循入职过程,只需安装M2/M1的Java 1.8即可。

Just follow this link to install java 1.8 into your mac with M1/M2 chip. Apple uses Rosetta2 for Mac transition to Apple silicon.

https://www.oracle.com/java/technologies/downloads/#java8-mac

Scroll down to java 1.8,
Go to the MacOS Version,
Click on the ARMx64 Version for M2 Chip,
Follow the onboarding process and simply install the java 1.8 for M2/M1.

X64 JDK-1.8是否会在Mac中使用Apple Silicon(M1)芯片工作?

向地狱狂奔 2025-02-17 15:18:09

这是因为方法fullname没有返回任何内容(none)。要像预期的那样使用该功能,而不是打印字符串,请返回。

def fullname(self):
    return f'{self.name} {self.lname}'

This is because the method fullname is not returning anything (None). To use the function like you expected, instead of printing the string, return it.

def fullname(self):
    return f'{self.name} {self.lname}'

为什么我没有得到。一种方法的打印输出inisde另一种方法

向地狱狂奔 2025-02-17 10:01:35

使用pd.factorizefrozenset

df['Val'] = pd.factorize(df[['B', 'C', 'D']].apply(frozenset, axis=1))[0] + 1
print(df)

# Output
    A  B   C   D  Val
0  AB  X  10  1a    1
1  FH  Y  15  4h    2
2  KY  Z  20  6f    3
3  DA  X  10  1a    1

Use pd.factorize with a frozenset

df['Val'] = pd.factorize(df[['B', 'C', 'D']].apply(frozenset, axis=1))[0] + 1
print(df)

# Output
    A  B   C   D  Val
0  AB  X  10  1a    1
1  FH  Y  15  4h    2
2  KY  Z  20  6f    3
3  DA  X  10  1a    1

行中的组值在一起并为它们分配一个互构值

向地狱狂奔 2025-02-17 03:21:18

对于Windows:

转到PATH \ ELASTICSERACH-8.2.2 \ bin文件夹。
在上面的文件夹或路径下打开PowerShell端子。
现在运行此命令:
。\ elasticsearch-reset-password -u弹性。

注意 - 不要忘记在最后一个。 。密码-U弹性。
注意 - 弹性搜索应运行

Password for the [elastic] user successfully reset.
New value: ******* (this will be your password)

For Windows:

Go to PATH\elasticsearch-8.2.2\bin folder.
under the above folder or path open the PowerShell terminal.
Now run this command :
.\elasticsearch-reset-password -u elastic .

NOTE - don't forget to add dot (.) at the last. .\elasticsearch-reset-password -u elastic .
NOTE - Elastick search should be running

Password for the [elastic] user successfully reset.
New value: ******* (this will be your password)

如何学习Elasticsearch登录和密码

向地狱狂奔 2025-02-16 23:22:59

看来您错过了一个括号:

await http.get(...).then((response) => callback(...))

它们允许您在可用后立即使用上一个将来的结果。如果发现令人困惑,则可以一次声明一个变量。

final response = await http.get(...);
// Check if response was as expected
await callback();

It seems you got a parenthesis missplaced:

await http.get(...).then((response) => callback(...))

The them allows you to use the result of the previous Future, as soon as it becomes available. If you find it confusing you can declare one variable at a time.

final response = await http.get(...);
// Check if response was as expected
await callback();

函数表达式可以命名:然后

向地狱狂奔 2025-02-16 15:34:33

我的主要问题是我有很多管理页面和许多前页面。因此,我不想为此项目提供每个页面解决方案。因此,我认为如果可以使用PathName。我的管理面板路由以“/admin-panel”开头,因此我检查了一下。 _app.js中的以下逻辑为我工作

function MyApp({ Component, pageProps, router }) {
  const adminPanel = router.route.startsWith('/admin-panel') ? true : false
  const getLayout =
    adminPanel ? ((page) => <AdminLayout children={page} />)
      : ((page) => <FrontLayout children={page} />);

  return (
    <>
      {getLayout(<Component {...pageProps} />, pageProps)}
    </>
  );

My main problem is that I have so many admin pages and so many front pages. So, I don't want to have per page solution for this project. So, I think if I could use pathname instead. My admin panel routes starts with '/admin-panel', So I checked for that. The following logic in _app.js works for me

function MyApp({ Component, pageProps, router }) {
  const adminPanel = router.route.startsWith('/admin-panel') ? true : false
  const getLayout =
    adminPanel ? ((page) => <AdminLayout children={page} />)
      : ((page) => <FrontLayout children={page} />);

  return (
    <>
      {getLayout(<Component {...pageProps} />, pageProps)}
    </>
  );

Next.js中的2个不同的布局1和1个Front网站的1个不同的布局?

向地狱狂奔 2025-02-16 10:09:54

注意:此代码是为discord.js v13.7.0编写的,并续集v6


不当更改表

&lt; sequelize&gt; .sync()未使用Alter或force

sequelize 执行根据他们的V6文档,提供了一个称为sync()的函数。此功能用于确保您的模型与数据库最新。但是,有一个警告。如果您在没有参数的情况下执行sync(),则数据库将不会覆盖现有数据。这是您的问题的来源。当您第一次定义模型时,很可能您做以下两件事:

  • 定义iddatatypes.integer
  • id 是一个唯一的字段

由于这些,并且您执行.sync()而没有参数,因此数据库的表不会被覆盖,因此可以保留旧的唯一字段。另外,如果您尝试将Discord ID存储为整数,则可能会遇到一个问题,即缩短或舍入的DISORD ID。

解决方案

将表

作为一次性修复丢弃,您可以使用此命令手动从sqlite3删除表,然后重新运行机器人,而无需修改sync(),它将使用正确的数据创建表:

DROP TABLE 'Cooldowns'

修复过时的表格

为了修复过时的表,您有两个选择。但是,要小心,因为这些都是破坏性的。您可以使用以下参数执行sync()命令:

<Sequelize>.sync({ alter: true }); // Alters tables
<Sequelize>.sync({ force: true }); // Forcefully recreates tables

如前所述,请小心这些操作,因为它们具有破坏性,如果您没有备份,则无法恢复。

正确存储Discord ID,

您需要做的就是将Discord ID存储为datatypes.stringdatatypes.text.text。这将保留ID的雪花形式并防止缩短。

sequelize.define("User", {
  id: {
    type: DataTypes.STRING, // Or .TEXT
    unique: false
  },
  // ...
});

Note: This code is written for Discord.js v13.7.0 and Sequelize v6


Improperly altering tables

<Sequelize>.sync() is not executed with alter or force

Sequelize, according to their v6 documentation, provides a function called sync(). This function is used to ensure that your models are up to date with the database. However, there is one caveat to this. If you execute sync() with no arguments, the database will not overwrite existing data. This is where your issue stems from. When you first defined the models, most likely you did the following two things:

  • Defined id as DataTypes.INTEGER
  • Set id to be a unique field

Due to these and you executing .sync() with no arguments, the database's tables will not be overwritten, therefore preserving the old unique fields. Also, if you attempt to store a Discord ID as an Integer, you may encounter an issue where Discord IDs are shortened or rounded.

Solutions

Drop the table

As a one time fix, you can manually drop the tables from sqlite3 using this command and rerun the bot without modifying sync() which will create the table with the right data:

DROP TABLE 'Cooldowns'

Fixing outdated tables

In order to fix the outdated tables, you have two options. However, be careful as these are destructive actions. You can execute the sync() command with the following arguments:

<Sequelize>.sync({ alter: true }); // Alters tables
<Sequelize>.sync({ force: true }); // Forcefully recreates tables

As stated before, be careful with these actions as they are destructive and cannot be reverted if you do not have backups.

Properly storing Discord IDs

All you need to do is store the Discord IDs as a DataTypes.STRING or DataTypes.TEXT. This will preserve the Snowflake form of the ID and prevent shortening.

sequelize.define("User", {
  id: {
    type: DataTypes.STRING, // Or .TEXT
    unique: false
  },
  // ...
});

与独特ID错误序列化的Discordjs冷却数据库

向地狱狂奔 2025-02-16 07:28:07

将续集连接到现有数据库并不困难。您只需要配置连接并设置模型即可。

如果您先前创建的表包含一些与续集的方法不匹配的属性,则可能需要在模型中编写一些额外的代码。同样,这是相当痛苦的。请参阅使用遗留表以获取更多信息。

It's not particularly difficult to connect Sequelize to an existing database. You just need to configure the connection and set up models.

If your previously-created tables include some attributes that don't match up to Sequelize's approach out of the box, you may need to write some extra code in your models. Again, this is fairly painless. See Working With Legacy Tables for additional information.

在现有数据库上实施异议/续集有没有好的方法?

向地狱狂奔 2025-02-15 04:36:53

有一个名为 dateTimerange 。创建事件后,您可以获取启动和结束DateTime(您已经在执行此操作),并将其传递到DateTimerange函数中,然后将其作为字符串存储在DB中。

当您重新获得活动时。您可以再次获得DateTime值。这是库文档中的一件代码:

import datetime
from datetimerange import DateTimeRange

time_range = DateTimeRange("2015-01-01T00:00:00+0900", "2015-01-04T00:00:00+0900")
for value in time_range.range(datetime.timedelta(days=1)):
    print(value)

There's a library named datetimerange . When an event is created, you can get the start and end datetime (which you are already doing), and pass it into the DateTimeRange function and store it as a string in DB.

When you get the event back. You can get the datetime values again. Here's a piece of code from the documentation of library:

import datetime
from datetimerange import DateTimeRange

time_range = DateTimeRange("2015-01-01T00:00:00+0900", "2015-01-04T00:00:00+0900")
for value in time_range.range(datetime.timedelta(days=1)):
    print(value)

我如何在开始时间和结束时间之间显示在日历上显示的事件

向地狱狂奔 2025-02-15 00:43:58

我想您可以使用vim标记(使用 vim仿真扩展)基本上是相同的想法,但不是真正的自动。

如果您在GIT存储库中工作,VSCODE将在Git选项卡中显示您上演和未分段的更改,并且还将向您显示差异。

实际上,它们是不同的编辑,默认功能不会映射1∶1。

tl; dr:不,不是真的,或者至少不是本地

I suppose you could use Vim marks (with the vim emulation extension), which is basically the same idea, but it's not really automatic.

If you're working in a git repository, VSCode will show you staged and unstaged changes in the git tab, and will also show you the diffs.

It really comes down to the fact that they're different editors and default functionalities will not map 1∶1.

tl;dr: no, not really, or at least not natively

最近更改了VSCODE的位置(例如在Intellij中)

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

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