自由范儿

文章 评论 浏览 27

自由范儿 2025-02-04 18:17:27

Quarkus Cassandra客户端有分页,但是我也无法像我想要的那样使其正常工作。在下面,您可以看到一个示例以获取分页态,其中包含Quarkus文档 https://quarkus.io/guides/guides /cassandra

public PagingFruit getPagingState(String pagingState){
        ByteBuffer state = ByteBuffer.wrap(pagingState.getBytes());
        MutinyMappedReactiveResultSet<Fruit> fruit = this.fruitMapper.fruitDao().findAll(x -> x.setPagingState(state).setPageSize(1000); // here we provide the unary operator that sets the state.  
        var newState = Uni.createFrom().publisher(fruit.getExecutionInfos()).map(ExecutionInfo::getPagingState).await().indefinitely().toString();
        return new PagingFruit(fruit.collect().asList().await().indefinitely(), newState);
}

record PagingFruit(List<Fruit> fruit, String pagingState){}

这使用了mutinyMappedReactiverEsultSet,该群可以使您查询executionInfos。

我目前使用Quarkus实施的问题是,我需要两次查询Cassandra,以实际提供数据和分页。因此,我选择了这样的示例的准备好的陈述:

class PaginatedRepository {

    private final QuarkusCqlSession cqlSession;
    private final PreparedStatement query;
    
    PaginatedRepository(QuarkusCqlSession quarkusCqlSession){
        this.cqlSession = quarkusCqlSession;
        this.query = cqlSession.prepare("SELECT fruit FROM keypace.table");
    }
    
    public Uni<PagingFruit> findFruit(String page) {
        var statement = query
                .bind()
                .setPageSize(1000)
                .setPagingState(PagingState.fromString(page));
    
        return Uni.createFrom().completionStage(cqlSession.executeAsync(statement))
                .map(resultSet -> {
                    var pagingState = resultSet.getExecutionInfo().getSafePagingState();
                    var newCursor = (pagingState == null) ? null : pagingState.toString();
                    var rows = Streams.stream(resultSet.currentPage())
                            .map(row -> row.get(1, Fruit.class)
                            ).filter(Objects::nonNull).toList();
                    return new PagingFruit(rows, newCursor);
                });
    }

这是未经测试的代码,只是应该有效的一般概念。

There is pagination in the Quarkus Cassandra client however I can't make it work as I would like either. Below you see an example to get the pagination state with the example from the quarkus documentation https://quarkus.io/guides/cassandra

public PagingFruit getPagingState(String pagingState){
        ByteBuffer state = ByteBuffer.wrap(pagingState.getBytes());
        MutinyMappedReactiveResultSet<Fruit> fruit = this.fruitMapper.fruitDao().findAll(x -> x.setPagingState(state).setPageSize(1000); // here we provide the unary operator that sets the state.  
        var newState = Uni.createFrom().publisher(fruit.getExecutionInfos()).map(ExecutionInfo::getPagingState).await().indefinitely().toString();
        return new PagingFruit(fruit.collect().asList().await().indefinitely(), newState);
}

record PagingFruit(List<Fruit> fruit, String pagingState){}

This uses the MutinyMappedReactiveResultSet which allows you to query the ExecutionInfos.

The problem I have at this moment using the quarkus implementation is that I need to query Cassandra twice to actually provide the data and the pagination with it. Therefore I opted for a prepared statement like this example:

class PaginatedRepository {

    private final QuarkusCqlSession cqlSession;
    private final PreparedStatement query;
    
    PaginatedRepository(QuarkusCqlSession quarkusCqlSession){
        this.cqlSession = quarkusCqlSession;
        this.query = cqlSession.prepare("SELECT fruit FROM keypace.table");
    }
    
    public Uni<PagingFruit> findFruit(String page) {
        var statement = query
                .bind()
                .setPageSize(1000)
                .setPagingState(PagingState.fromString(page));
    
        return Uni.createFrom().completionStage(cqlSession.executeAsync(statement))
                .map(resultSet -> {
                    var pagingState = resultSet.getExecutionInfo().getSafePagingState();
                    var newCursor = (pagingState == null) ? null : pagingState.toString();
                    var rows = Streams.stream(resultSet.currentPage())
                            .map(row -> row.get(1, Fruit.class)
                            ).filter(Objects::nonNull).toList();
                    return new PagingFruit(rows, newCursor);
                });
    }

This is untested code, just the general concept which should work.

是否有Quarkus cassandra客户端进行分页的工作示例?

自由范儿 2025-02-04 14:26:49

是的。呼叫:

rawset(table, key, value)

示例:

rawset(_G, 'foo', 'bar')
print(foo)
-- Output: bar
-- Lets loop it and rawget() it too
-- rawset() returns table _G here to rawget()
-- rawset() is executed before rawget() in this case
for i = 1, 10 do
 print(rawget(rawset(_G, 'var' .. i, i), 'var' .. i))
end
-- Output: 10 lines - First the number 1 and last the number 10

请参阅: https://lua.org/manual/5.1/ Manual.html#PDF-RAWSET

将所有内容放在一起并创建一个自己的功能...

function create_vars(var, start, stop)
for i = start, stop do
 print(var .. i, '=>', rawget(rawset(_G, var .. i, i), var .. i))
end
end

并使用它...

> create_vars('var', 42, 42)
var42   =>  42
> print(var42)
42

Yes. Call:

rawset(table, key, value)

Example:

rawset(_G, 'foo', 'bar')
print(foo)
-- Output: bar
-- Lets loop it and rawget() it too
-- rawset() returns table _G here to rawget()
-- rawset() is executed before rawget() in this case
for i = 1, 10 do
 print(rawget(rawset(_G, 'var' .. i, i), 'var' .. i))
end
-- Output: 10 lines - First the number 1 and last the number 10

See: https://lua.org/manual/5.1/manual.html#pdf-rawset

Putting all together and create an own function...

function create_vars(var, start, stop)
for i = start, stop do
 print(var .. i, '=>', rawget(rawset(_G, var .. i, i), var .. i))
end
end

And use it...

> create_vars('var', 42, 42)
var42   =>  42
> print(var42)
42

在LUA中生成带有字符串和值的变量名称

自由范儿 2025-02-04 11:20:25

我建议您去查看编译器错误,其中有很多!
例如:

main.c:66:23: error: request for member ‘name’ in something not a structure or union
   66 |             uni.arr[i].name = (char*)malloc((strlen(name) + 1) * sizeof(char));
      |                       ^
main.c:67:27: error: request for member ‘name’ in something not a structure or union
   67 |             if (uni.arr[i].name == NULL)
      |                           ^
main.c:72:23: error: request for member ‘id’ in something not a structure or union
   72 |             uni.arr[i].id = id;
      |                       ^
main.c:73:23: error: request for member ‘grade’ in something not a structure or union
   73 |             uni.arr[i].grade = grade;
      |                       ^
main.c:75:27: error: request for member ‘labor’ in something not a structure or union
   75 |                 uni.arr[i].labor[j] = ch[j];

I suggest you to go look into your compilers error, there's plenty of them!
For example:

main.c:66:23: error: request for member ‘name’ in something not a structure or union
   66 |             uni.arr[i].name = (char*)malloc((strlen(name) + 1) * sizeof(char));
      |                       ^
main.c:67:27: error: request for member ‘name’ in something not a structure or union
   67 |             if (uni.arr[i].name == NULL)
      |                           ^
main.c:72:23: error: request for member ‘id’ in something not a structure or union
   72 |             uni.arr[i].id = id;
      |                       ^
main.c:73:23: error: request for member ‘grade’ in something not a structure or union
   73 |             uni.arr[i].grade = grade;
      |                       ^
main.c:75:27: error: request for member ‘labor’ in something not a structure or union
   75 |                 uni.arr[i].labor[j] = ch[j];

C,从文件读取,prinintg,语法错误标识符

自由范儿 2025-02-03 18:24:57

您可以使用CSS和JavaScript

CSS

@media screen and (min-width: 1050px) {
    body {
       font-size: // the value you want
    }
}

JavaScript

if(screen.width < your point) {
  // change font size
}

you can do it with css and javascript

CSS

@media screen and (min-width: 1050px) {
    body {
       font-size: // the value you want
    }
}

JavaScript

if(screen.width < your point) {
  // change font size
}

当窗口大小到达JavaScript中的某个点时,如何更改CSS

自由范儿 2025-02-03 18:03:50

尝试以下内容:

res = linregress(pupVals, defVals)
SlopeFit = np.array([res.intercept, res.slope])
errs = np.array([res.stderr,intercept_stderr])
CIS = SlopeFit[:,None] + 1.96*errs[:,None]*np.array([[1,-1]])

Try the following:

res = linregress(pupVals, defVals)
SlopeFit = np.array([res.intercept, res.slope])
errs = np.array([res.stderr,intercept_stderr])
CIS = SlopeFit[:,None] + 1.96*errs[:,None]*np.array([[1,-1]])

尝试复制Python中的MATLAB回归功能

自由范儿 2025-02-02 22:07:03

您使自己变得有些困难,并混合了一些概念。当您声明struct Bustypedef时,您会为要读取的每个字符串声明指示器。这些指针是非初始化的,并且必须在尝试将字符串复制到内存位置之前为每个指针分配。 (始终回答问题“我使用的每个指针对我使用的指针点有什么有效的内存地址

?这里是不必要的。如果您的值如示例数据中所示,则可以简单地声明固定数组,而不是指向要存储的数据。看,以下数组尺寸足以满足您的数据(存储空间大约多50%,并且用于NUL终止字符的空间),例如

    traveldate        16-bytes
    traveltime         8-bytes
    fromdestination   63-bytes
    todestination     63-bytes

(根据需要进行调整),

您可以声明一些常数以设置每个的大小数组,并在代码顶部提供一个方便的位置,如果需要,您可以在其中进行更改。常数和您的重写结构可能是:

#define MAXC 1024   /* if you need a constant, #define one (or more) */
#define NBUS  128
#define DESTC  64
#define DATEC  16
#define TIMEC   8

typedef struct bus {
  int busnumber;
  char traveldate[DATEC];       /* use fixed arrays or allocate for each */
  char traveltime[TIMEC];
  char fromdestination[DESTC];
  char todestination[DESTC];
  float price;
  int capacity;
} bus;

您一次在阅读整个行时正确思考。 maxc上面设置了您的读取行为的最大字符数,以确保每次调用fgets()的每次调用。 nbus常数设置要读取的最大总线数(Busses数组的数组大小)。

您的替代方法是动态分配存储空间以存储一大堆以容纳公共汽车。这也相对容易,它使您可以种植内存的块来处理,但是您的文件中有许多公共汽车,而无需事先知道“多少”。 (切勿对数据文件进行两次通过(全读),只是为了找出有多少行 - 高效效率),但是,对于解析示例,我们将使用固定的数组来限制nbus 公共汽车。

考虑到这一点,您可以声明您的公共汽车数组,并将每行读取为缓冲区,将文件名读取为您程序的第一个命令行参数(或默认情况下,从stdin中读取,如果没有参数给出),例如:

int main (int argc, char **argv) {
  
  char buf[MAXC] = "";                        /* read buffer */
  bus busses[NBUS] = {{ .busnumber = 0 }};    /* array of bus */
  size_t n = 0;                               /* number of busses */
  /* use filename provided as 1st argument (stdin by default) */
  FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;

  if (!fp) {  /* validate file open for reading */
      perror ("file open failed");
      return 1;
  }
  
  /* while array not full, read line */
  while (n < NBUS && fgets (buf, MAXC, fp)) {
    ...

虽然有几种替代方法可以将'#'定界符上的行分开,但对于您的固定数据,最简单的是使用sscanf()和精心制作的格式字符串。您可以在保护阵列界限的同时将数据分开以下:

    "%d#%15[^#]#%7[^#]#%63[^#]#%63[^#]#%f#%d"

sscanf()上面的格式字符串将每行分为以下

  • 几行,然后将'#'#',然后将
  • 不超过15字符的字符串,然后是'#'
  • 一串不超过7字符,后跟> '#'
  • 一根不超过63字符的字符串,后跟'#'
  • 一串不超过63字符之后是'#'
  • a float值,然后是'#',最后是
  • 整数。

您可以计算预期的转换数(上面的7),并使用该值验证sscanf()的返回。您可以使用计数器变量(在此处使用n)来跟踪读取的总线数量,并且在成功将所有值成功地分离到您的时,在您的读取环中仅增加n结构阵列。您可以通过检查nnbus来保护Busses数组界限,这是您读取循环条件的一部分(如上所述)。

将其完全放置,您的阅读和分离循环以读取您的文件并填充Busses数组看起来像:

  /* while array not full, read line */
  while (n < NBUS && fgets (buf, MAXC, fp)) {
    /* separate line into stuct variables - VALIDATE return */
    if (sscanf (buf, "%d#%15[^#]#%7[^#]#%63[^#]#%63[^#]#%f#%d", 
                &busses[n].busnumber, busses[n].traveldate,
                busses[n].traveltime, busses[n].fromdestination,
                busses[n].todestination, &busses[n].price,
                &busses[n].capacity) == 7) {
      n++;  /* increment count only on successful separation */
    }
  }

这就是全部。现在,您可以使用Busses数组来做任何您喜欢的事情。

将其放在一个完整的示例中,您将拥有:

#include <stdio.h>

#define MAXC 1024   /* if you need a constant, #define one (or more) */
#define NBUS  128
#define DESTC  64
#define DATEC  16
#define TIMEC   8

typedef struct bus {
  int busnumber;
  char traveldate[DATEC];       /* use fixed arrays or allocate for each */
  char traveltime[TIMEC];
  char fromdestination[DESTC];
  char todestination[DESTC];
  float price;
  int capacity;
} bus;

int main (int argc, char **argv) {
  
  char buf[MAXC] = "";                        /* read buffer */
  bus busses[NBUS] = {{ .busnumber = 0 }};    /* array of bus */
  size_t n = 0;                               /* number of busses */
  /* use filename provided as 1st argument (stdin by default) */
  FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;

  if (!fp) {  /* validate file open for reading */
      perror ("file open failed");
      return 1;
  }
  
  /* while array not full, read line */
  while (n < NBUS && fgets (buf, MAXC, fp)) {
    /* separate line into stuct variables - VALIDATE return */
    if (sscanf (buf, "%d#%15[^#]#%7[^#]#%63[^#]#%63[^#]#%f#%d", 
                &busses[n].busnumber, busses[n].traveldate,
                busses[n].traveltime, busses[n].fromdestination,
                busses[n].todestination, &busses[n].price,
                &busses[n].capacity) == 7) {
      n++;  /* increment count only on successful separation */
    }
  }

  if (fp != stdin)   /* close file if not stdin */
      fclose (fp);
  
  for (size_t i = 0; i < n; i++) {  /* output results */
    printf ("%4d  %s  %s  %-12s  %-12s  %6.2f  %3d\n",
            busses[i].busnumber, busses[i].traveldate,
            busses[i].traveltime, busses[i].fromdestination,
            busses[i].todestination, busses[i].price,
            busses[i].capacity);
  }
}

示例使用/output

在文件中使用示例数据dat/busses.txt您在运行运行时会得到以下内容程序:

./bin/readbusses dat/busses.txt
   1  18042022  14:30  Birzeit       Ramallah        6.00   15
   2  18042022  11:45  Birzeit       Birzeit         6.00    1
  13  19042022  14:30  Birzeit       Atara           6.00   20
  53  20042022  14:00  Birzeit       Nablus          6.00    7

有许多不同的方法可以接近分开每一行的方法,但是从简单的角度来看,一个强大的角度(任何一行数据中的错误都仅影响该行的数据,并且不会从该点开始读取的读取,例如,如果您尝试直接在文件上使用fscanf() - 而无需手动清除以在错误的情况下结束。)

查看问题,让我知道您是否有其他问题。

You are making things a bit difficult on yourself and mixing a few concepts. When you declare your struct bus and typedef, you declare pointers for each string you want to read. These pointers are uninitialized and must have storage allocated for each before attempting to copy a string to the memory location. (always answer the question "To what valid memory address does my pointer point?" for every pointer you use)

While allocating for each string can be done relatively simply, it will add unneeded complexity to your code and is unnecessary here. If your values are as shown in your sample data, then you can simply declare fixed arrays instead of pointers to the data you want to store. Looking, the following array sizes will be sufficient for your data (with roughly 50% more storage than required, and room for the nul-terminating character), e.g.

    traveldate        16-bytes
    traveltime         8-bytes
    fromdestination   63-bytes
    todestination     63-bytes

(adjust as needed)

You can declare a few constants to set the size of each array, and provide a single convenient location at the top of your code where you can make a change if required. The constants and your re-written struct could be:

#define MAXC 1024   /* if you need a constant, #define one (or more) */
#define NBUS  128
#define DESTC  64
#define DATEC  16
#define TIMEC   8

typedef struct bus {
  int busnumber;
  char traveldate[DATEC];       /* use fixed arrays or allocate for each */
  char traveltime[TIMEC];
  char fromdestination[DESTC];
  char todestination[DESTC];
  float price;
  int capacity;
} bus;

You are thinking correctly in reading an entire line at a time. MAXC above sets the maximum number of characters for your read-buffer to ensure a line is fully consumed with each call to fgets(). The NBUS constant sets the max number of busses to be read (the array size for your busses array).

Your alternative is to dynamically allocate storage for a block of memory to hold the busses. That also is relatively easy, and it allows you to grow the block of memory to handle however many busses are in your file without needed to know "how many" beforehand. (NEVER make two passes (full-reads) of your data file just to find out how many lines there are -- highly inefficient) However, for the parsing example, we will use a fixed array limited to holding NBUS busses.

With that in mind you can declare your busses array and read each line into a buffer, taking the filename to read as the first command-line argument to your program (or by default reading from stdin if no argument is given) like:

int main (int argc, char **argv) {
  
  char buf[MAXC] = "";                        /* read buffer */
  bus busses[NBUS] = {{ .busnumber = 0 }};    /* array of bus */
  size_t n = 0;                               /* number of busses */
  /* use filename provided as 1st argument (stdin by default) */
  FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;

  if (!fp) {  /* validate file open for reading */
      perror ("file open failed");
      return 1;
  }
  
  /* while array not full, read line */
  while (n < NBUS && fgets (buf, MAXC, fp)) {
    ...

While there are several alternatives for separating the lines on '#' delimiters, for your fixed-data, by far the simplest is using sscanf() and a carefully crafted format string. You can separate the data while protecting your array bounds with the following:

    "%d#%15[^#]#%7[^#]#%63[^#]#%63[^#]#%f#%d"

The sscanf() format string above will separate each line into:

  • an integer, followed by '#',
  • a string of no more than 15 characters followed by a '#',
  • a string of no more than 7 characters followed by a '#',
  • a string of no more than 63 characters followed by a '#',
  • a string of no more than 63 characters followed by a '#',
  • a float value followed by a '#', and finally
  • an integer.

You count the number of conversions anticipated (7 above) and you validate the return of sscanf() with that value. You can use a counter variable (n here) to track the number of busses read, and only increment n in your read-loop upon a successful separation of all values into your array of struct. You protect the busses array bounds by checking n against NBUS as part of the condition of your read loop (shown above).

Putting it altogether, your read and separation loop to read your file and fill your busses array will look like:

  /* while array not full, read line */
  while (n < NBUS && fgets (buf, MAXC, fp)) {
    /* separate line into stuct variables - VALIDATE return */
    if (sscanf (buf, "%d#%15[^#]#%7[^#]#%63[^#]#%63[^#]#%f#%d", 
                &busses[n].busnumber, busses[n].traveldate,
                busses[n].traveltime, busses[n].fromdestination,
                busses[n].todestination, &busses[n].price,
                &busses[n].capacity) == 7) {
      n++;  /* increment count only on successful separation */
    }
  }

That's all there is to it. You can now do whatever you like with your busses array.

Putting it together into a full example, you would have:

#include <stdio.h>

#define MAXC 1024   /* if you need a constant, #define one (or more) */
#define NBUS  128
#define DESTC  64
#define DATEC  16
#define TIMEC   8

typedef struct bus {
  int busnumber;
  char traveldate[DATEC];       /* use fixed arrays or allocate for each */
  char traveltime[TIMEC];
  char fromdestination[DESTC];
  char todestination[DESTC];
  float price;
  int capacity;
} bus;

int main (int argc, char **argv) {
  
  char buf[MAXC] = "";                        /* read buffer */
  bus busses[NBUS] = {{ .busnumber = 0 }};    /* array of bus */
  size_t n = 0;                               /* number of busses */
  /* use filename provided as 1st argument (stdin by default) */
  FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;

  if (!fp) {  /* validate file open for reading */
      perror ("file open failed");
      return 1;
  }
  
  /* while array not full, read line */
  while (n < NBUS && fgets (buf, MAXC, fp)) {
    /* separate line into stuct variables - VALIDATE return */
    if (sscanf (buf, "%d#%15[^#]#%7[^#]#%63[^#]#%63[^#]#%f#%d", 
                &busses[n].busnumber, busses[n].traveldate,
                busses[n].traveltime, busses[n].fromdestination,
                busses[n].todestination, &busses[n].price,
                &busses[n].capacity) == 7) {
      n++;  /* increment count only on successful separation */
    }
  }

  if (fp != stdin)   /* close file if not stdin */
      fclose (fp);
  
  for (size_t i = 0; i < n; i++) {  /* output results */
    printf ("%4d  %s  %s  %-12s  %-12s  %6.2f  %3d\n",
            busses[i].busnumber, busses[i].traveldate,
            busses[i].traveltime, busses[i].fromdestination,
            busses[i].todestination, busses[i].price,
            busses[i].capacity);
  }
}

Example Use/Output

With your sample data in the file dat/busses.txt you would get the following upon running the program:

./bin/readbusses dat/busses.txt
   1  18042022  14:30  Birzeit       Ramallah        6.00   15
   2  18042022  11:45  Birzeit       Birzeit         6.00    1
  13  19042022  14:30  Birzeit       Atara           6.00   20
  53  20042022  14:00  Birzeit       Nablus          6.00    7

There are many different ways to approach separating each line, but from a simplicity standpoint, and a robust standpoint (an error in any one line of data only effects data from that line and doesn't break the read from that point forward, such as if you attempted to use fscanf() directly on the file -- without clearing to end of line manually on error.)

Look things over and let me know if you have further questions.

使用“ fsgets”在C中如何拆分字符串并制作结构

自由范儿 2025-02-02 20:19:59

,可以使git合并的拉力重新要求 - 允许 - 无关的途径。您可以这样做:

# First, create a new branch based on main:
git switch -c history-merge main

# Next, merge your branch with the unrelated history into `history-merge`
#
# Resolve any merge conflicts at this time,
# and change the merge text to "Merge branch 'unrelated' into main".
git merge unrelated --allow-unrelated-histories

# Push your new branch:
git push -u origin history-merge

一旦完成,就可以从历史记录 - 混合使用中创建一个拉动请求到main

如果您希望它是100%无缝的,请在合并PR时选择rebase选项。这将快速向前main到原始的合并 - 命令。

It is possible to make a pull-request equivalent of git merge --allow-unrelated-histories. You can do it like so:

# First, create a new branch based on main:
git switch -c history-merge main

# Next, merge your branch with the unrelated history into `history-merge`
#
# Resolve any merge conflicts at this time,
# and change the merge text to "Merge branch 'unrelated' into main".
git merge unrelated --allow-unrelated-histories

# Push your new branch:
git push -u origin history-merge

Once that's done, you can create a pull request from history-merge into main.

If you want it to be 100% seamless, choose the rebase option when you go to merge the PR. This will fast-forward main to the original merge-commit.

如何在分支机构之间创建一个完全不同的提交历史的拉力请求

自由范儿 2025-02-02 20:04:12

tm_rgb()的选项有限。 plotRGB()函数似乎使用栅格单元格值的样本来执行拉伸。这就是为什么图像显得更明亮,更对比的原因。这是我使用tm_rgb()

fcc_nir <- setMinMax(fcc_nir)

tm_shape(fcc_nir) +
  tm_rgb(max.value = max(maxValue(fcc_nir)))

“最佳拉伸”

tm_rgb()没有min.value =选项。一个人可以输入较小的max.value,但这有点受打击和错过。我希望根据图像统计数据使用更严格的方法。

tm_shape(fcc_nir) +
  tm_rgb(max.value = 31000)

必须使用raster :: stract()或某些用户定义的拉伸功能之前先手动重新构造图像,以获得更明亮的输出。

例如:

fcc_nir_s <- stretch(fcc_nir, minv = 0, maxv = 255, minq = 0.1, maxq = 0.99)

tm_shape(fcc_nir_s) +
  tm_rgb()

制作此图像:

”拉伸图像“

tm_rgb() has limited options. The plotRGB() function appears to use a sample of raster cell values to perform a stretch. That is why images appear brighter and more contrasty. This is the best I could achieve with tm_rgb():

fcc_nir <- setMinMax(fcc_nir)

tm_shape(fcc_nir) +
  tm_rgb(max.value = max(maxValue(fcc_nir)))

best stretch

tm_rgb() has no min.value = option. One can enter a smaller max.value but this is a bit hit and miss. I would prefer to use a more rigorous approach based on image statistics.

tm_shape(fcc_nir) +
  tm_rgb(max.value = 31000)

arbitrary user-defined max.value

One has to manually rescale images beforehand using the raster::stretch() or some user-defined stretch function to get a brighter output.

For example:

fcc_nir_s <- stretch(fcc_nir, minv = 0, maxv = 255, minq = 0.1, maxq = 0.99)

tm_shape(fcc_nir_s) +
  tm_rgb()

produces this image:

stretched image

将线性拉伸应用于tmap r包装中的Landsat 8图像

自由范儿 2025-02-02 18:14:05

您可以使用

  Router,
  Switch,
  Route,
  Link

它。

在这里我为路由示例提供了一个示例,希望它对您有帮助。

you can use

  Router,
  Switch,
  Route,
  Link

for it.

here I put a example for route example, hope it will help you.

如何将React JS中的当前页面重定向到当前页面?

自由范儿 2025-02-02 14:41:55

我知道这是一个古老的问题,但是昨天我度过了一个下午,努力解决同样的问题。

事实证明,问题不是熊猫,而是我通过在导出之前检查列,在导出后在记事本中打开CSV并在Excel打开后再次检查它来验证的。值直到将其保存到Excel之后才更改。

您可以使用以下测试代码进行验证。如果您将值列表中的值更改为INT,则Excel将在打开和保存时以不同的方式将它们折叠在一起。如果是字符串,则在XLSX文件中打开时会保持不变。这可能会根据Excel版本而有所不同。

import pandas as pd

values = ['1610202324578508800']
columns = ['values']

test_df = pd.DataFrame(values, columns=columns).astype({'values':object})

test_df.to_csv('test df.csv')
test_df.to_excel('test df.xlsx')

I know this is an old question, but I spent the afternoon yesterday struggling with the same problem.

Turns out, the issue wasn't Pandas, but Excel, which I verified by checking the columns before export, opening the csv in Notepad after export, and checking it again after opening it in Excel. The values weren't changed until after it was saved in Excel.

You can use the below test code to validate. If you change the value in the values list to an int, Excel will round both of them off differently when you open and save. If it's a string, it will be unchanged when opened in an xlsx file. This may vary depending on versions of Excel.

import pandas as pd

values = ['1610202324578508800']
columns = ['values']

test_df = pd.DataFrame(values, columns=columns).astype({'values':object})

test_df.to_csv('test df.csv')
test_df.to_excel('test df.xlsx')

大熊猫近似/舍入CSV的大量

自由范儿 2025-02-02 06:39:57

程序来进行检查的方法

public static double findMax(double[] data) {
    double max = Double.MIN_VALUE;
    for (double val : data) {
        if (val > max) {
            max = val;
        }
    }
    
    return max;
}

使用数学实用程序

public static double findMax2(double[] data) {
    double max = Double.MIN_VALUE;
    for (double val : data) {
        max = Math.max(val, max);
    }
    
    return max;
}

,使用流使用

public static double findMax3(double[] data) {
    return Arrays.stream(data).max().getAsDouble();
}

实用

public static double findMin(double[] data) {
    double min = Double.MAX_VALUE;
    for (double val : data) {
        if (val < min) {
            min = val;
        }
    }
    
    return min;
}

进行数学

public static double findMin2(double[] data) {
    double min = Double.MAX_VALUE;
    for (double val : data) {
        min = Math.min(val, min);
    }
    
    return min;
}

数学实用程序使用流媒体

public static double findMin3(double[] data) {
    return Arrays.stream(data).min().getAsDouble();
}

Method to do the checks yourself

public static double findMax(double[] data) {
    double max = Double.MIN_VALUE;
    for (double val : data) {
        if (val > max) {
            max = val;
        }
    }
    
    return max;
}

Using the Math utility

public static double findMax2(double[] data) {
    double max = Double.MIN_VALUE;
    for (double val : data) {
        max = Math.max(val, max);
    }
    
    return max;
}

Using streams

public static double findMax3(double[] data) {
    return Arrays.stream(data).max().getAsDouble();
}

Doing your own checks

public static double findMin(double[] data) {
    double min = Double.MAX_VALUE;
    for (double val : data) {
        if (val < min) {
            min = val;
        }
    }
    
    return min;
}

Using Math utility

public static double findMin2(double[] data) {
    double min = Double.MAX_VALUE;
    for (double val : data) {
        min = Math.min(val, min);
    }
    
    return min;
}

Using streams

public static double findMin3(double[] data) {
    return Arrays.stream(data).min().getAsDouble();
}

在Java中的阵列中找到最大双倍

自由范儿 2025-02-01 23:03:39

由于struct D是一种聚合类型,在C ++ 20之前,您无法使用()进行初始化,例如d(10)

感谢 p0960 ,现在C ++ 20您可以从括号的值列表中初始化聚合。请注意,目前,只有以后的版本 gcc-10> gcc-10 and msvc-10 and msvc-19.28 此功能,对于clang,它将仍然抱怨

<source>:15:9: error: no matching conversion for functional-style cast from 'int' to 'D'
  D d = D(10);
        ^~~~

Since struct D is an aggregate type, before C++20 you could not use () for initialization such as D(10).

Thanks to P0960, now in C++20 you can initialize aggregates from a parenthesized list of values. Note that currently, only later versions of GCC-10 and MSVC-19.28 implement this feature, for Clang it will still complain

<source>:15:9: error: no matching conversion for functional-style cast from 'int' to 'D'
  D d = D(10);
        ^~~~

自动构造函数在C&#x2B;&#x2B; 20中的继承

自由范儿 2025-02-01 16:58:40

在项目设置中,您需要启用减压后备。之后,构建将起作用。

In the project settings you need to enable Decompression Fallback. After that the build will work.

Decompression Fallback setting

Unity webGL构建在github页面上错误:无法解析框架。

自由范儿 2025-02-01 15:53:21

未显示零条标签,因为在此日志刻度上,0无限远低于其他条形的顶部,因此从技术上讲看不见。

您当然可以手动添加标签:

ax.text(x = x_positions[2] - bar_width, 
        y = ax.get_ylim()[0] + 1, 
        s = '0',
        horizontalalignment='center')

+1是否可以匹配其他标签的padding = 3。您可能需要更改其他量表。

可以通过在所有值上进行迭代,例如这样(将两个y值设置为零进行测试)可以自动化:

month1 = [11, 1200, 0]
month2 = [55, 0, 37]
month3 = [0, 222, 300]

labels = ['a', 'b', 'c']
x_positions = np.arange(len(labels)) 
bar_width = 0.15 
y_min = 10

fig, ax = plt.subplots()
fig.tight_layout()
ax.set_yscale('log') 
ax.set_ylim(y_min, 2000)
    
rects1 = ax.bar(x_positions - bar_width, month1, bar_width, label=labels[0])
rects2 = ax.bar(x_positions, month2, bar_width, label=labels[1])
rects3 = ax.bar(x_positions + bar_width, month3, bar_width, label=labels[2])

ax.set_ylabel('Count')
ax.set_xticks(x_positions, labels)
ax.legend()
    
ax.bar_label(rects1, padding=3)
ax.bar_label(rects2, padding=3)
ax.bar_label(rects3, padding=3)

for x, month in enumerate([month1, month2, month3]):
    for x_offset, y in zip([-1, 0, 1], month):
        if y < y_min:
            ax.text(x = x + x_offset * bar_width, 
                    y = y_min + 1, 
                    s = str(y),
                    horizontalalignment='center')

”带有log轴和三个零标签的barplot和三个零标签”

The zero bar label is not shown, because on this log scale, 0 is infinitely far below the other bars' tops, so technically it can't be seen.

You can of course add a label manually:

ax.text(x = x_positions[2] - bar_width, 
        y = ax.get_ylim()[0] + 1, 
        s = '0',
        horizontalalignment='center')

The +1 is there to match the padding=3 of the other labels. You may need to change this for other scales.

This approach could be automated by iterating over all the values, e.g. like this (setting two more y values to zero for testing):

month1 = [11, 1200, 0]
month2 = [55, 0, 37]
month3 = [0, 222, 300]

labels = ['a', 'b', 'c']
x_positions = np.arange(len(labels)) 
bar_width = 0.15 
y_min = 10

fig, ax = plt.subplots()
fig.tight_layout()
ax.set_yscale('log') 
ax.set_ylim(y_min, 2000)
    
rects1 = ax.bar(x_positions - bar_width, month1, bar_width, label=labels[0])
rects2 = ax.bar(x_positions, month2, bar_width, label=labels[1])
rects3 = ax.bar(x_positions + bar_width, month3, bar_width, label=labels[2])

ax.set_ylabel('Count')
ax.set_xticks(x_positions, labels)
ax.legend()
    
ax.bar_label(rects1, padding=3)
ax.bar_label(rects2, padding=3)
ax.bar_label(rects3, padding=3)

for x, month in enumerate([month1, month2, month3]):
    for x_offset, y in zip([-1, 0, 1], month):
        if y < y_min:
            ax.text(x = x + x_offset * bar_width, 
                    y = y_min + 1, 
                    s = str(y),
                    horizontalalignment='center')

Barplot with log axis and three zero labels

使用日志轴时如何显示0个长度条的标签

自由范儿 2025-02-01 05:41:06

您可以通过使用event.preventdefault()来防止表单提交,但是如果onsubmit函数被内联分配,则必须将event作为参数传递给该函数。

您可以使用 a>在

<form action="script.php" method="post" onsubmit="validator(event)">
  <input type="number" class="votation">
  <button type="submit">Save</button>
</form>

<script>
function validator(event) {
  // get all control input values
  const values = document.querySelectorAll('.votation').map(control => control.value);
  
  // check if there are any duplicates
  if (!values.every((element, index, array) => array.indexOf(element) === index) {
    alert("Duplicate values found");

    // prevent form submission
    event.preventDefault();
  }
}
</script>

You can prevent form submission by using event.preventDefault() but if the onsubmit function is assigned inline then the event must be passed to the function as a parameter.

You can use Array.every() to find duplicates as explained in this answer.

<form action="script.php" method="post" onsubmit="validator(event)">
  <input type="number" class="votation">
  <button type="submit">Save</button>
</form>

<script>
function validator(event) {
  // get all control input values
  const values = document.querySelectorAll('.votation').map(control => control.value);
  
  // check if there are any duplicates
  if (!values.every((element, index, array) => array.indexOf(element) === index) {
    alert("Duplicate values found");

    // prevent form submission
    event.preventDefault();
  }
}
</script>

如何在JavaScript中返回布尔值

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

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