问:
Unit test Observable with delay operator
I have a hard time getting my unit test to work together with an Observable with delay operator. The application is built on Angular 2 and the tests are running in karma/jasmine. I've tried the async and fakeAsync helper methods but none of them are working.

Here's a simplified code block (without Angular 2) explaining my issue.

```<code>let mouseDownStream = Rx.Observable.fromEvent(document.body, 'mousedown');
let haveBeenCalled = false;
mouseDownStream.delay(200).subscribe(() => haveBeenCalled = true);

describe('mouse down event', () => {
  it('it should emit an event stream after 200ms', (done) => {
    document.body.dispatchEvent(new MouseEvent('mousedown'))
    expect(haveBeenCalled).toBeFalsy();

    // Don't want this setTimeout should use Angular's tick(200) method instead but it's not working.
    setTimeout(() => {
      expect(haveBeenCalled).toBeTruthy();
      done();
    }, 200)
  });
});
</code>```

JSBin

答:
Using rxjs 6 with angular 12, fakeAsync doesn't work for me.  Only using the TestScheduler did.  Modifying Ritchie's sample:

```<code>describe("mouse down event", () => {
    let testScheduler: TestScheduler;
    beforeEach(() => {
      testScheduler = new TestScheduler((act, exp) => expect(exp).toEqual(act) as any);
    });

    fit("should emit an event stream after 200ms", () => {
      let mouseDownStream = fromEvent(document.body, "mousedown");
      let haveBeenCalled = false;

      testScheduler.run(() => {
        const subscription = mouseDownStream.pipe(delay(200)).subscribe(() => (haveBeenCalled = true));
        document.body.dispatchEvent(new MouseEvent("mousedown"));
        expect(haveBeenCalled).toBeFalsy();
        testScheduler.createTime('200|');
        testScheduler.flush();
        expect(haveBeenCalled).toBeTruthy();
        subscription.unsubscribe();
      });
    });
});
</code>```

Body:
I have a hard time getting my unit test to work together with an Observable with delay operator. The application is built on Angular 2 and the tests are running in karma/jasmine. I've tried the async and fakeAsync helper methods but none of them are working.

Here's a simplified code block (without Angular 2) explaining my issue.

let mouseDownStream = Rx.Observable.fromEvent(document.body, 'mousedown');
let haveBeenCalled = false;
mouseDownStream.delay(200).subscribe(() => haveBeenCalled = true);

describe('mouse down event', () => {
  it('it should emit an event stream after 200ms', (done) => {
    document.body.dispatchEvent(new MouseEvent('mousedown'))
    expect(haveBeenCalled).toBeFalsy();

    // Don't want this setTimeout should use Angular's tick(200) method instead but it's not working.
    setTimeout(() => {
      expect(haveBeenCalled).toBeTruthy();
      done();
    }, 200)
  });
});

JSBin

Body:
Using rxjs 6 with angular 12, fakeAsync doesn't work for me.  Only using the TestScheduler did.  Modifying Ritchie's sample:

describe("mouse down event", () => {
    let testScheduler: TestScheduler;
    beforeEach(() => {
      testScheduler = new TestScheduler((act, exp) => expect(exp).toEqual(act) as any);
    });

    fit("should emit an event stream after 200ms", () => {
      let mouseDownStream = fromEvent(document.body, "mousedown");
      let haveBeenCalled = false;

      testScheduler.run(() => {
        const subscription = mouseDownStream.pipe(delay(200)).subscribe(() => (haveBeenCalled = true));
        document.body.dispatchEvent(new MouseEvent("mousedown"));
        expect(haveBeenCalled).toBeFalsy();
        testScheduler.createTime('200|');
        testScheduler.flush();
        expect(haveBeenCalled).toBeTruthy();
        subscription.unsubscribe();
      });
    });
});


来源: stackexchange

问:
Dynamic sheet name change bases on a range
I would like to get the current month weeks number on this range C3:C8. Based on that values, to rename the following tabs names: Sheet3, Sheet4, Sheet5, Sheet6, Sheet7, Sheet8

Also, I would like this script to work only on sheet name: Sheet1

Is there a google script that can acomplish this request?
I would really appreciate it.
Thank you very much!

function sheetsNames(){
  var ss = SpreadsheetApp.getActiveSpreadsheet()
  var sh = ss.getSheetByName('Sheet1')
  var values = sh.getRange('C3:C8').getValues()
  for (var i=values.length-1;i>=0;i--){
    ss.getSheets()[i+3].setName(values[i][0])
  }
}```

UPDATE: I'm trying to attach the function renameSheetTabs() into a drawing but for some reason I'm getting the following error.

答:
Try</p>
```<code>function sheetsNames(){
  var ss = SpreadsheetApp.getActiveSpreadsheet()
  var sh = ss.getSheetByName('Sheet1')
  var values = sh.getRange('C3:C8').getValues()
  for (var i=values.length-1;i>=0;i--){
    ss.getSheets()[i+3].setName(values[i][0])
  }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I would like to get the current month weeks number on this range C3:C8. Based on that values, to rename the following tabs names: Sheet3, Sheet4, Sheet5, Sheet6, Sheet7, Sheet8

Also, I would like this script to work only on sheet name: Sheet1

Is there a google script that can acomplish this request?
I would really appreciate it.
Thank you very much!

function sheetsNames(){
  var ss = SpreadsheetApp.getActiveSpreadsheet()
  var sh = ss.getSheetByName('Sheet1')
  var values = sh.getRange('C3:C8').getValues()
  for (var i=values.length-1;i>=0;i--){
    ss.getSheets()[i+3].setName(values[i][0])
  }
}

UPDATE: I'm trying to attach the function renameSheetTabs() into a drawing but for some reason I'm getting the following error.

Body:
Try

function sheetsNames(){
  var ss = SpreadsheetApp.getActiveSpreadsheet()
  var sh = ss.getSheetByName('Sheet1')
  var values = sh.getRange('C3:C8').getValues()
  for (var i=values.length-1;i>=0;i--){
    ss.getSheets()[i+3].setName(values[i][0])
  }
}


问:
How can I null-check this?
```<code>FutureBuilder(
  future: GetLiter(),
  builder: (context, snapshot) => Text(
    "Estimated bill \n\n\n" + snapshot.data * 0.00556 + " $",
    textAlign: TextAlign.center,
    style: TextStyle(fontSize: 20),
  ), // Text
), // FutureBuilder
</code>```

I have "An expression whose value can be 'null' must be null-checked before it can be dereferenced." error in snapshot.data. How can I null-check this?

GetLiter() func is here =>

```<code>Future<Object?> GetLiter() async {
  FirebaseDatabase database = FirebaseDatabase.instance;

  DatabaseReference ref = FirebaseDatabase.instance.ref("Liter");

  DatabaseEvent event = await ref.once();

  // print(event.snapshot.value);
  return event.snapshot.value;
}
</code>```

答:
You can use snapshot.hasData on your builder to check if it is null. For example:

FutureBuilder(
  future: GetLiter(),
  builder: (context, snapshot) {
    if (!snapshot.hasData) return Text('Nothing here');
    return Text(
      "Estimated bill \n\n\n" + snapshot.data * 0.00556 + " $",
      textAlign: TextAlign.center,
      style: TextStyle(fontSize: 20),
    )
  }, // Text
),
```

Title: How can I null-check this?

Body:
FutureBuilder(
  future: GetLiter(),
  builder: (context, snapshot) => Text(
    "Estimated bill \n\n\n" + snapshot.data * 0.00556 + " $",
    textAlign: TextAlign.center,
    style: TextStyle(fontSize: 20),
  ), // Text
), // FutureBuilder

I have "An expression whose value can be 'null' must be null-checked before it can be dereferenced." error in snapshot.data. How can I null-check this?

GetLiter() func is here =>

Future<Object?> GetLiter() async {
  FirebaseDatabase database = FirebaseDatabase.instance;

  DatabaseReference ref = FirebaseDatabase.instance.ref("Liter");

  DatabaseEvent event = await ref.once();

  // print(event.snapshot.value);
  return event.snapshot.value;
}


问:
How to unit test graphics with python3, CircleCI and Mayavi
I wrote a bunch of visualization functions in my python3 library using Mayavi. I am not very familiar with this library, nor am I with testing visualizations using python.

Ideally, I would just like the visualization code to generate some graphics on disk, I don't care too much about popping up windows (although I'm not sure to understand if Mayavi can work properly without popping such windows).

Anyway, my code works on local, but when I push it on develop, CircleCI fails at running the tests with the following error:

```<code>!/bin/bash -eo pipefail
python3 tests/test.py

qt.qpa.plugin: Could not load the Qt platform plugin "xcb" in "" even though it was found.
This application failed to start because no Qt platform plugin could be initialized. Reinstalling the application may fix this problem.

Available platform plugins are: eglfs, linuxfb, minimal, minimalegl, offscreen, vnc, wayland-egl, wayland, wayland-xcomposite-egl, wayland-xcomposite-glx, webgl, xcb.

Received "aborted" signal
</code>```

The Docker Image I use is the following:

```<code>FROM ubuntu:focal

ARG DEBIAN_FRONTEND=noninteractive

RUN apt-get update -y
RUN apt-get install -y --no-install-recommends\
                    vim \
                    git \
                    gcc-9 \
                    g++ \
                    build-essential \
                    libboost-all-dev \
                    cmake \
                    unzip \
                    tar \
                    ca-certificates \
                    doxygen \
                    graphviz

RUN apt-get install -y libgdal-dev g++ --no-install-recommends && \
    apt-get clean -y

ENV CPLUS_INCLUDE_PATH=/usr/include/gdal
ENV C_INCLUDE_PATH=/usr/include/gdal

RUN git clone --recurse-submodules https://github.com/Becheler/quetzal-EGGS \
&& cd quetzal-EGGS \
&&  mkdir Release \
&&  cd Release \
&& cmake .. -DCMAKE_INSTALL_PREFIX="/usr/local/quetzal-EGGS" \
&& cmake --build . --config Release --target install

RUN set -xe \
    apt-get update && apt-get install -y \
    python3-pip \
    --no-install-recommends

RUN pip3 install --upgrade pip
RUN pip3 install build twine pipenv numpy # for crumbs publishing
RUN pip3 install rasterio && \
    pip3 install matplotlib && \
    pip3 install imageio && \
    pip3 install imageio-ffmpeg && \
    pip3 install pyproj && \
    pip3 install shapely && \
    pip3 install fiona && \
    pip3 install scikit-learn && \
    pip3 install pyimpute && \
    pip3 install geopandas && \
    pip3 install pygbif

########## MAYAVI

# xcb plugin
RUN apt-get install -y --no-install-recommends libxkbcommon-x11-0 libxcb-icccm4 libxcb-image0 libxcb-keysyms1 libxcb-randr0 libxcb-render-util0 libxcb-xinerama0 && \
    apt-get clean -y

RUN python3 -m pip install vtk
RUN apt-get update && apt-get install -y python3-opencv && apt-get clean -y
RUN pip3 install opencv-python
RUN pip3 install mayavi PyQt5

RUN pip3 install GDAL==$(gdal-config --version) pyvolve==1.0.3 quetzal-crumbs==0.0.15

# Clean to make image smaller
RUN apt-get autoclean && \
    apt-get autoremove && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/*
</code>```

Am I missing some dependencies?

Should I had a -X option somewhere?

Should I deactivate the mlab.show() and imshow() calls in my
library?

答:
I missed a dependency, qt5-default. I ended up having these lines for Mayavi running on Docker/CircleCi:

```<code>########## MAYAVI

# xcb plugin
RUN apt-get install -y --no-install-recommends xvfb libxkbcommon-x11-0 libxcb-icccm4 libxcb-image0 libxcb-keysyms1 libxcb-randr0 libxcb-render-util0 libxcb-xinerama0 && \
    apt-get clean -y
# Trying to solve the weird xcfb error
RUN apt-get install -y --no-install-recommends qt5-default && \
    apt-get clean -y
RUN python3 -m pip install vtk
RUN apt-get update && apt-get install -y python3-opencv && apt-get clean -y
RUN pip3 install opencv-python
RUN pip3 install PyVirtualDisplay
RUN pip3 install mayavi PyQt5
</code>```

I am pretty sure that many of these dependencies are redundant or not required. But it works, so I will leave it this way until I have some time to make a bit of cleanup.

I also added this line in my python library:

mlab.options.offscreen = True
```

The rational for it comes from the mayavi offscreen rendering documentation

Body:
I wrote a bunch of visualization functions in my python3 library using Mayavi. I am not very familiar with this library, nor am I with testing visualizations using python.

Ideally, I would just like the visualization code to generate some graphics on disk, I don't care too much about popping up windows (although I'm not sure to understand if Mayavi can work properly without popping such windows).

Anyway, my code works on local, but when I push it on develop, CircleCI fails at running the tests with the following error:

!/bin/bash -eo pipefail
python3 tests/test.py

qt.qpa.plugin: Could not load the Qt platform plugin "xcb" in "" even though it was found.
This application failed to start because no Qt platform plugin could be initialized. Reinstalling the application may fix this problem.

Available platform plugins are: eglfs, linuxfb, minimal, minimalegl, offscreen, vnc, wayland-egl, wayland, wayland-xcomposite-egl, wayland-xcomposite-glx, webgl, xcb.

Received "aborted" signal

The Docker Image I use is the following:

FROM ubuntu:focal

ARG DEBIAN_FRONTEND=noninteractive

RUN apt-get update -y
RUN apt-get install -y --no-install-recommends\
                    vim \
                    git \
                    gcc-9 \
                    g++ \
                    build-essential \
                    libboost-all-dev \
                    cmake \
                    unzip \
                    tar \
                    ca-certificates \
                    doxygen \
                    graphviz

RUN apt-get install -y libgdal-dev g++ --no-install-recommends && \
    apt-get clean -y

ENV CPLUS_INCLUDE_PATH=/usr/include/gdal
ENV C_INCLUDE_PATH=/usr/include/gdal

RUN git clone --recurse-submodules https://github.com/Becheler/quetzal-EGGS \
&& cd quetzal-EGGS \
&&  mkdir Release \
&&  cd Release \
&& cmake .. -DCMAKE_INSTALL_PREFIX="/usr/local/quetzal-EGGS" \
&& cmake --build . --config Release --target install

RUN set -xe \
    apt-get update && apt-get install -y \
    python3-pip \
    --no-install-recommends

RUN pip3 install --upgrade pip
RUN pip3 install build twine pipenv numpy # for crumbs publishing
RUN pip3 install rasterio && \
    pip3 install matplotlib && \
    pip3 install imageio && \
    pip3 install imageio-ffmpeg && \
    pip3 install pyproj && \
    pip3 install shapely && \
    pip3 install fiona && \
    pip3 install scikit-learn && \
    pip3 install pyimpute && \
    pip3 install geopandas && \
    pip3 install pygbif

########## MAYAVI

# xcb plugin
RUN apt-get install -y --no-install-recommends libxkbcommon-x11-0 libxcb-icccm4 libxcb-image0 libxcb-keysyms1 libxcb-randr0 libxcb-render-util0 libxcb-xinerama0 && \
    apt-get clean -y

RUN python3 -m pip install vtk
RUN apt-get update && apt-get install -y python3-opencv && apt-get clean -y
RUN pip3 install opencv-python
RUN pip3 install mayavi PyQt5

RUN pip3 install GDAL==$(gdal-config --version) pyvolve==1.0.3 quetzal-crumbs==0.0.15

# Clean to make image smaller
RUN apt-get autoclean && \
    apt-get autoremove && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/*

Am I missing some dependencies?

Should I had a -X option somewhere?

Should I deactivate the mlab.show() and imshow() calls in my
library?

Body:
I missed a dependency, qt5-default. I ended up having these lines for Mayavi running on Docker/CircleCi:

########## MAYAVI

# xcb plugin
RUN apt-get install -y --no-install-recommends xvfb libxkbcommon-x11-0 libxcb-icccm4 libxcb-image0 libxcb-keysyms1 libxcb-randr0 libxcb-render-util0 libxcb-xinerama0 && \
    apt-get clean -y
# Trying to solve the weird xcfb error
RUN apt-get install -y --no-install-recommends qt5-default && \
    apt-get clean -y
RUN python3 -m pip install vtk
RUN apt-get update && apt-get install -y python3-opencv && apt-get clean -y
RUN pip3 install opencv-python
RUN pip3 install PyVirtualDisplay
RUN pip3 install mayavi PyQt5

I am pretty sure that many of these dependencies are redundant or not required. But it works, so I will leave it this way until I have some time to make a bit of cleanup.

I also added this line in my python library:

mlab.options.offscreen = True

The rational for it comes from the mayavi offscreen rendering documentation


问:
RXJS, How to watch mouse and keyboard and do something when when none has been used for some time?
I need run a function if neither the mouse has moved, nor the keyboard has been touched for 1mn.

I tried the code below but doesn't seem to work.
How can I fix it?
Thank you for your help.

```<code>mouseEvent$ = fromEvent(document, 'mouseMove');
keyPress$ = fromEvent(document, 'keyup');

merge(
    this.mouseEvent$.pipe(startWith(null)).pipe(switchMap(() => timer(10000, 1000))),
    this.keyPress$.pipe(startWith(null)).pipe(switchMap(() => timer(10000, 1000))),
).subscribe(() => console.log("----));
</code>```

答:
The first thing to notice is that you typed mouseMove incorrectly.

Here's how I might do this:

merge(
  fromEvent(document, 'mousemove'),
  fromEvent(document, 'keyup')
).pipe(
  share(),
  startWith(null),
  debounceTime(60000),
  take(1),
  retry()
).subscribe(_ => console.log("1 Minute without input"));
```

Body:
I need run a function if neither the mouse has moved, nor the keyboard has been touched for 1mn.

I tried the code below but doesn't seem to work.
How can I fix it?
Thank you for your help.

mouseEvent$ = fromEvent(document, 'mouseMove');
keyPress$ = fromEvent(document, 'keyup');

merge(
    this.mouseEvent$.pipe(startWith(null)).pipe(switchMap(() => timer(10000, 1000))),
    this.keyPress$.pipe(startWith(null)).pipe(switchMap(() => timer(10000, 1000))),
).subscribe(() => console.log("----));


问:
How to turn an HList of Const functors into a Seq?
I have a higher-kinded data type like this

```<code>case class Foo[F[_] : Functor](a: F[Int], b: F[Double])
</code>```

and a value that labels every member with some kind of string (the name of a CSV column for example):

```<code>val colNames = new Foo[Const[String, *]](a = Const("AAA"), b = Const("BBB"))
</code>```

Now I need to somehow convert colNames into a Seq[String]. There is the standard scala method productIterator of course, but it only returns Iterator[Any].

Using shapeless I can get an HList where every type in the list is Const[String, _]:

```<code>val colNamesHlist: Const[String, _] :: Const[String, _] :: HNil = Generic[Foo[Const[String, *]]].to(colNames)
</code>```

But how can I turn this into a regular list?

I am also open to any ideas not involving shapeless, though I don't think it can be avoided.

答:
You may do this:

val colNameList: List[String] =
  Generic[Foo[Const[String, *]]]
    .to(colNames)
    .toList[Const[String, A] forSome { type A }]
    .map(_.getConst)
```

You can see the code running here.

Body:
I have a higher-kinded data type like this

case class Foo[F[_] : Functor](a: F[Int], b: F[Double])

and a value that labels every member with some kind of string (the name of a CSV column for example):

val colNames = new Foo[Const[String, *]](a = Const("AAA"), b = Const("BBB"))

Now I need to somehow convert colNames into a Seq[String]. There is the standard scala method productIterator of course, but it only returns Iterator[Any].

Using shapeless I can get an HList where every type in the list is Const[String, _]:

val colNamesHlist: Const[String, _] :: Const[String, _] :: HNil = Generic[Foo[Const[String, *]]].to(colNames)

But how can I turn this into a regular list?

I am also open to any ideas not involving shapeless, though I don't think it can be avoided.

Body:
You may do this:

val colNameList: List[String] =
  Generic[Foo[Const[String, *]]]
    .to(colNames)
    .toList[Const[String, A] forSome { type A }]
    .map(_.getConst)

You can see the code running here.


问:
INSERT INTO database table, from form not working. SQL
lets get straight to my problem, the code I have written here does not write to my database and I cannot figue out why. At the moment I am simply trying to get to grips with php and sql so there is no point to this form other than learning. Here is the error i am getting(the first sentence 'connected to database' is from my if statement):

"Connected to databaseError: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''test' ('name') VALUES ('daniel')' at line 1"

The code I have may look a little confusing as some of it is from w3schools and some is from a friend. I cannot figure out why this code isn't working, I have tried many variations of the syntax based on loads of articles I have found online and on stackoverflow but none seem to work. I fear that maybe I am not even connectec to the database, although my if statement tells me otherwise, so that could be a problem?

Hopefully if this gets solved this question will clarify database connection and writing to a database from a form in one hit. Thanks in advance guys and here's my code.

HTML

```<code><form action="insert.php" method="post">
Name: <input type="text" name="namefield" />
<input type="submit" />
</form>
</code>```

PHP (insert.php)

```<code><?php
$dbhost  = 'localhost';
$dbname  = 'carbon_db';
$dbuser  = 'username';
$dbpass  = 'password';

$con = mysql_connect($dbhost, $dbuser, $dbpass);

if($con == FALSE)
{
    echo 'Cannot connect to database' . mysql_error();
}
else
{
    echo 'Connected to database';
}

mysql_select_db($dbname, $con);

$sql="INSERT INTO 'test' ('name')
VALUES ('$_POST[namefield]')";

if (!mysql_query($sql, $con))
{
    die('Error: ' . mysql_error());
}
echo "1 record added";

mysql_close($con)
?>
</code>```

答:
Remove the single quotes around your sql statement and replace with back-tics (not sure even they are necessary):</p>

```<code>$sql="INSERT INTO `test` ('name')
VALUES ('$_POST[namefield]')";
</code>```

ContentLicense: CC BY-SA 3.0

Body:
lets get straight to my problem, the code I have written here does not write to my database and I cannot figue out why. At the moment I am simply trying to get to grips with php and sql so there is no point to this form other than learning. Here is the error i am getting(the first sentence 'connected to database' is from my if statement):

"Connected to databaseError: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''test' ('name') VALUES ('daniel')' at line 1"

The code I have may look a little confusing as some of it is from w3schools and some is from a friend. I cannot figure out why this code isn't working, I have tried many variations of the syntax based on loads of articles I have found online and on stackoverflow but none seem to work. I fear that maybe I am not even connectec to the database, although my if statement tells me otherwise, so that could be a problem?

Hopefully if this gets solved this question will clarify database connection and writing to a database from a form in one hit. Thanks in advance guys and here's my code.

HTML

<form action="insert.php" method="post">
Name: <input type="text" name="namefield" />
<input type="submit" />
</form>

PHP (insert.php)

<?php
$dbhost  = 'localhost';
$dbname  = 'carbon_db';
$dbuser  = 'username';
$dbpass  = 'password';

$con = mysql_connect($dbhost, $dbuser, $dbpass);

if($con == FALSE)
{
    echo 'Cannot connect to database' . mysql_error();
}
else
{
    echo 'Connected to database';
}

mysql_select_db($dbname, $con);

$sql="INSERT INTO 'test' ('name')
VALUES ('$_POST[namefield]')";

if (!mysql_query($sql, $con))
{
    die('Error: ' . mysql_error());
}
echo "1 record added";

mysql_close($con)
?>

Body:
Remove the single quotes around your sql statement and replace with back-tics (not sure even they are necessary):

$sql="INSERT INTO `test` ('name')
VALUES ('$_POST[namefield]')";


问:
Is it possible to make a static reference to an excel sheet in AnyLogic?
I want to call an Excel with a static java function within an AnyLogic Model as shown in the picture. The function "readExcelFile" has to be static, because I want to call it from another class within my AnyLogic Project.
However, when I call the function, an error occurs: "Cannot make a static reference to the non-static field produktionssystem".
Is there a solution for this problem?

答:
It's tough to understand what is causing the error here, because I can't see inside your function.

There is no inherent issue with read/write to Excel files from within another class (i.e. within another agent, custom class, etc...).

Here is a link to a public model on the AnyLogic cloud that I found very helpful when I first started working with Excel files within AnyLogic:
https://cloud.anylogic.com/model/99d9f196-17e7-47c3-9b28-63a6f23b0dad?mode=SETTINGS


问:
With Spring Cloud Stream RabbitMQ, is it possible to zip outbound and unzip inbound message
With Spring Cloud Stream RabbitMQ application, I am trying to compress (zip) the message before sending it by defining my own RabbitTemplate bean but it does not work.

Is there a way to do it by configuration (application.properties) or by another method ?

答:
The binder configuration automatically wires in a GZipPostProcessor on the sending side and a DelegatingDecompressingPostProcessor on the consumer side.

If you want to change it to a ZipPostProcessor, use a binder customizer to set it on the binder:

/**
 * Set a {@link org.springframework.amqp.core.MessagePostProcessor} to compress
 * messages. Defaults to a
 * {@link org.springframework.amqp.support.postprocessor.GZipPostProcessor}.
 * @param compressingPostProcessor the post processor.
 */
public void setCompressingPostProcessor(
        MessagePostProcessor compressingPostProcessor) {
```

You have to set the producer binding property compress to true to enable compression on the sending side.

On the receiving side, the DelegatingDecompressingPostProcessor looks at the content encoding message property to determine whether decompression is needed and which decompressor to use.

EDIT

I've just noticed that the binder sets the compression level to 0 (NO_COMPRESSION). Use spring.cloud.stream.rabbit.binder.compression-level=9 (BEST_COMPRESSION) or spring.cloud.stream.rabbit.binder.compression-level=1 (BEST_SPEED).

See java.util.zip.Deflater for available levels.

https://github.com/spring-cloud/spring-cloud-stream-binder-rabbit/issues/353

This only applies if using gzip.

Body:
The binder configuration automatically wires in a GZipPostProcessor on the sending side and a DelegatingDecompressingPostProcessor on the consumer side.

If you want to change it to a ZipPostProcessor, use a binder customizer to set it on the binder:

/**
 * Set a {@link org.springframework.amqp.core.MessagePostProcessor} to compress
 * messages. Defaults to a
 * {@link org.springframework.amqp.support.postprocessor.GZipPostProcessor}.
 * @param compressingPostProcessor the post processor.
 */
public void setCompressingPostProcessor(
        MessagePostProcessor compressingPostProcessor) {

You have to set the producer binding property compress to true to enable compression on the sending side.

On the receiving side, the DelegatingDecompressingPostProcessor looks at the content encoding message property to determine whether decompression is needed and which decompressor to use.

EDIT

I've just noticed that the binder sets the compression level to 0 (NO_COMPRESSION). Use spring.cloud.stream.rabbit.binder.compression-level=9 (BEST_COMPRESSION) or spring.cloud.stream.rabbit.binder.compression-level=1 (BEST_SPEED).

See java.util.zip.Deflater for available levels.

https://github.com/spring-cloud/spring-cloud-stream-binder-rabbit/issues/353

This only applies if using gzip.


问:
Can't create new user (using the JWT Grant flow and scopes that mentioned in API overview)
I have a problem with creating another user by Admin API. I don't have an organization_id property in /userinfo response. I need it to create new users via my app. There I also use recommended scopes.

This response I have after call /userinfo

```<code>{
    "sub": "xxx",
    "name": "Some Name",
    "given_name": "Name",
    "family_name": "Name",
    "created": "2022-02-02T16:38:29.457",
    "email": "some.email@gmail.com",
    "accounts": [
        {
            "account_id": "xxx",
            "is_default": true,
            "account_name": "Name",
            "base_uri": "https://demo.docusign.net"
        }
    ]
}
</code>```

Also when I used Quickstart App I faced the same problem. I can't create users via this app. Because an organization_id property is missed.
Quickstart App error

Thanks.

#docusignapi

答:
To use the Admin API you have to have an organization for your account.

Once you create an organization - you will have an organizationId which is used for this API call.

How to create an organization for your DocuSign account.

Body:
I have a problem with creating another user by Admin API. I don't have an organization_id property in /userinfo response. I need it to create new users via my app. There I also use recommended scopes.

This response I have after call /userinfo

{
    "sub": "xxx",
    "name": "Some Name",
    "given_name": "Name",
    "family_name": "Name",
    "created": "2022-02-02T16:38:29.457",
    "email": "some.email@gmail.com",
    "accounts": [
        {
            "account_id": "xxx",
            "is_default": true,
            "account_name": "Name",
            "base_uri": "https://demo.docusign.net"
        }
    ]
}

Also when I used Quickstart App I faced the same problem. I can't create users via this app. Because an organization_id property is missed.
Quickstart App error

Thanks.

#docusignapi


问:
Jetpack Compose inner shadow
How to create an inner shadow with Jetpack Compose? The gradient should run from black on the outside to transparent on the inside. Modifier.shadow() is just for outer shadows. Using negative elevation is not working.

答:
This is not supported but you have alternative options:

Use a border modifier with a gradient brush

Use Android Canvas

Use a gradient and Modifier.drawBehind to draw the inset shadow underneath the content

Source

Title: Jetpack Compose inner shadow


问:
Vue router in main.js: this dependency was not found error
When I run npm run serve I get the This dependency was not found error, relating to the router that I'm trying to use in the main.js. I don't understand why this happens - the router is created and exported from src/router/router/js file and imported in the main.js file.

main.js:

```<code>import App from './App.vue'
import './assets/tailwind.css'
import Vue from 'vue'
import VueRouter from 'vue-router'
import router from 'router/router.js'

Vue.config.productionTip = false
Vue.use(VueRouter);

const app = new Vue({
  render: h => h(App),
}).$mount('#app')

app.use(router);
</code>```

router.js:

```<code>import { createRouter, createWebHistory } from 'vue-router'

import Home from '../views/Home.vue'
import About from '../views/About.vue'

const routes = [
    {
        path: '/home',
        name: 'Home',
        component: Home
    },
    {
        path: '/about',
        name: 'About',
        component: About
    }
]
const router = createRouter({
    history: createWebHistory(process.env.BASE_URL),
    routes
})
export default router
</code>```

This is my directory structure:

I get this error:

```<code>
This dependency was not found:

* router/router.js in ./src/main.js
</code>```

答:
You have not imported the router correctly, it should be like this instead:

```<code>import router from './router/router.js'
</code>```

Normally it should work now.

Edit:

Try making a new vue project with the router preset.

Body:
When I run npm run serve I get the This dependency was not found error, relating to the router that I'm trying to use in the main.js. I don't understand why this happens - the router is created and exported from src/router/router/js file and imported in the main.js file.

main.js:

import App from './App.vue'
import './assets/tailwind.css'
import Vue from 'vue'
import VueRouter from 'vue-router'
import router from 'router/router.js'

Vue.config.productionTip = false
Vue.use(VueRouter);

const app = new Vue({
  render: h => h(App),
}).$mount('#app')

app.use(router);

router.js:

import { createRouter, createWebHistory } from 'vue-router'

import Home from '../views/Home.vue'
import About from '../views/About.vue'

const routes = [
    {
        path: '/home',
        name: 'Home',
        component: Home
    },
    {
        path: '/about',
        name: 'About',
        component: About
    }
]
const router = createRouter({
    history: createWebHistory(process.env.BASE_URL),
    routes
})
export default router

This is my directory structure:

I get this error:

This dependency was not found:

* router/router.js in ./src/main.js

Body:
You have not imported the router correctly, it should be like this instead:

import router from './router/router.js'

Normally it should work now.

Edit:

Try making a new vue project with the router preset.


问:
.clipShape lose alignment when padding | SwiftUI | iOS15
I'm working on a custom Navigation Bottom Bar. I want it to be floating but I realized that when I add .padding() on it the .clipShape() inside its background loses alignment.

I have coded a simple version of the issue.

BottomNav without padding:

BottomNav with padding:

Main View:

```<code>struct ContentView: View {
var body: some View {
        VStack{
            Spacer()
            CustomBottomNav()
                .padding() // <- THIS MAKE THE SHAPE TO LOSE ALIGN
        }
}
</code>```

CustomBottomNav:

```<code>struct CustomBottomNav: View {

@State var selectedTab: Views = .HOME
@State private var xAxis: CGFloat = 0
@Namespace var animation

private let tabs: [Views] = [.SETTINGS, .RANKING, .HOME, .SALES, .SEARCHER]
private let iconSize: CGFloat = 25

private func isSelectedTab(_ tab: Views) -> Bool{
    return selectedTab == selectedTab
}

var body: some View {
    HStack(spacing: 0){
        ForEach(tabs, id: \.self){ tab in

            GeometryReader { geo in
                Button {

                    print(geo.frame(in: .global).midX)

                    withAnimation(.spring()) {
                        selectedTab = tab
                        xAxis = geo.frame(in: .global).midX
                    }
                } label: {
                    getImage(tab: tab)
                        .resizable()
                        .renderingMode(.template)
                        .aspectRatio(contentMode: .fit)
                        .frame(width: 30, height: 30)
                        .padding(isSelectedTab(tab) ? 15 : 0)
                        .background(
                            Color.orange
                                .opacity(
                                    isSelectedTab(tab) ? 1 : 0
                                ).clipShape(Circle())
                        )
                        .matchedGeometryEffect(id: tab, in: animation)
                }
                .position(x: geo.frame(in: .local).midX, y: geo.frame(in: .local).midY)
                .offset(
                    y: -60
                )
                .onAppear {
                    if isSelectedTab(tab) {
                        xAxis = geo.frame(in: .global).midX
                    }
                }
            }
            .frame(width: iconSize, height: iconSize)
            .overlay(
                Rectangle()
                    .stroke(.red)
            )

            if tab != tabs.last{
                Spacer()
            }

        }
    }
    .padding(.horizontal, 30)
    .padding(.vertical)
    .background(
        Color.yellow
            .clipShape(BottomNavShape(xAxis: xAxis))
            .cornerRadius(15)
    )
}

func getImage(tab: Views) -> Image {
    switch tab {
        case .SETTINGS:
            return Image("house")
        case .RANKING:
            return Image("house")
        case .HOME:
            return Image("house")
        case .SALES:
            return Image("house")
        case .SEARCHER:
            return Image("house")
    }
}

enum Views{
    case SETTINGS
    case RANKING
    case HOME
    case SALES
    case SEARCHER

}
}
</code>```

BottomNavShape:

```<code>struct BottomNavShape: Shape{

var xAxis: CGFloat

//Animating path
var animatableData: CGFloat{
    get{
        return xAxis
    }
    set{
        xAxis = newValue
    }
}

func path(in rect: CGRect) -> Path {
    return Path{ path in
        path.move(to: CGPoint(x: 0, y: 0))
       path.addLine(to: CGPoint(x: rect.width, y: 0))
       path.addLine(to: CGPoint(x: rect.width, y: rect.height))
       path.addLine(to: CGPoint(x: 0, y: rect.height))

       let center = CGPoint(x: xAxis, y: rect.midY)

        path.move(to: center)

        path.addArc(center: center, radius: 15, startAngle: .degrees(0), endAngle:
.degrees(1), clockwise: true)
    }
}
}
</code>```

These classes are all you need to replicate the issue.

I'm using XCode 13 and iOS 15.

答:
Its a little tricky because of the hard coded values, but
I got it to work like this:

if you use a defined padding on the outer view, e.g.

```<code>.padding(30)
</code>```

then you can subtract this value in CustomButtonNav here:

```<code>xAxis = geo.frame(in: .global).midX - 30 // subtract your outer padding here
</code>```

This appear 2 times:

in the button action & in the .onAppear

Body:
I'm working on a custom Navigation Bottom Bar. I want it to be floating but I realized that when I add .padding() on it the .clipShape() inside its background loses alignment.

I have coded a simple version of the issue.

BottomNav without padding:

BottomNav with padding:

Main View:

struct ContentView: View {
var body: some View {
        VStack{
            Spacer()
            CustomBottomNav()
                .padding() // <- THIS MAKE THE SHAPE TO LOSE ALIGN
        }
}

CustomBottomNav:

struct CustomBottomNav: View {

@State var selectedTab: Views = .HOME
@State private var xAxis: CGFloat = 0
@Namespace var animation

private let tabs: [Views] = [.SETTINGS, .RANKING, .HOME, .SALES, .SEARCHER]
private let iconSize: CGFloat = 25

private func isSelectedTab(_ tab: Views) -> Bool{
    return selectedTab == selectedTab
}

var body: some View {
    HStack(spacing: 0){
        ForEach(tabs, id: \.self){ tab in

            GeometryReader { geo in
                Button {

                    print(geo.frame(in: .global).midX)

                    withAnimation(.spring()) {
                        selectedTab = tab
                        xAxis = geo.frame(in: .global).midX
                    }
                } label: {
                    getImage(tab: tab)
                        .resizable()
                        .renderingMode(.template)
                        .aspectRatio(contentMode: .fit)
                        .frame(width: 30, height: 30)
                        .padding(isSelectedTab(tab) ? 15 : 0)
                        .background(
                            Color.orange
                                .opacity(
                                    isSelectedTab(tab) ? 1 : 0
                                ).clipShape(Circle())
                        )
                        .matchedGeometryEffect(id: tab, in: animation)
                }
                .position(x: geo.frame(in: .local).midX, y: geo.frame(in: .local).midY)
                .offset(
                    y: -60
                )
                .onAppear {
                    if isSelectedTab(tab) {
                        xAxis = geo.frame(in: .global).midX
                    }
                }
            }
            .frame(width: iconSize, height: iconSize)
            .overlay(
                Rectangle()
                    .stroke(.red)
            )

            if tab != tabs.last{
                Spacer()
            }

        }
    }
    .padding(.horizontal, 30)
    .padding(.vertical)
    .background(
        Color.yellow
            .clipShape(BottomNavShape(xAxis: xAxis))
            .cornerRadius(15)
    )
}

func getImage(tab: Views) -> Image {
    switch tab {
        case .SETTINGS:
            return Image("house")
        case .RANKING:
            return Image("house")
        case .HOME:
            return Image("house")
        case .SALES:
            return Image("house")
        case .SEARCHER:
            return Image("house")
    }
}

enum Views{
    case SETTINGS
    case RANKING
    case HOME
    case SALES
    case SEARCHER

}
}

BottomNavShape:

struct BottomNavShape: Shape{

var xAxis: CGFloat

//Animating path
var animatableData: CGFloat{
    get{
        return xAxis
    }
    set{
        xAxis = newValue
    }
}

func path(in rect: CGRect) -> Path {
    return Path{ path in
        path.move(to: CGPoint(x: 0, y: 0))
       path.addLine(to: CGPoint(x: rect.width, y: 0))
       path.addLine(to: CGPoint(x: rect.width, y: rect.height))
       path.addLine(to: CGPoint(x: 0, y: rect.height))

       let center = CGPoint(x: xAxis, y: rect.midY)

        path.move(to: center)

        path.addArc(center: center, radius: 15, startAngle: .degrees(0), endAngle:
.degrees(1), clockwise: true)
    }
}
}

These classes are all you need to replicate the issue.

I'm using XCode 13 and iOS 15.

Body:
Its a little tricky because of the hard coded values, but
I got it to work like this:

if you use a defined padding on the outer view, e.g.

.padding(30)

then you can subtract this value in CustomButtonNav here:

xAxis = geo.frame(in: .global).midX - 30 // subtract your outer padding here

This appear 2 times:

in the button action & in the .onAppear


问:
Where is ContinuationToken in Azure.Search.Documents v11
In Microsoft.Azure.Search.Data v10 when calling ISearchIndexClient.Documents.SearchAsync

I got a result with a ContinuationToken property.

In Azure.Search.Documents v11 I can't find it when calling SearchClient.SearchAsync

which - as far as I have found out - is the equal call.

答:
I don't have a good way to explain it :) but please take a look at the code below. The code below fetches all documents from an index using continuation token:</p>
```<code>using System;
using System.Threading.Tasks;
using Azure;
using Azure.Search.Documents;
using Azure.Search.Documents.Models;

namespace SO71052143
{
    class Program
    {
        private const string accountName = "account-name";
        private const string accountKey = "admin-key";
        private const string indexName = "index-name";

        static async Task Main(string[] args)
        {
            SearchClient client = new SearchClient(new Uri($"https://{accountName}.search.windows.net"), indexName,
                new AzureKeyCredential(accountKey));
            var results = (await client.SearchAsync<SearchDocument>("*"));
            var searchResults = results.Value.GetResultsAsync();
            string continuationToken = null;
            do
            {
                await foreach (var item in searchResults.AsPages(continuationToken))
                {
                    continuationToken = item.ContinuationToken;
                    var documents = item.Values;
                }
            } while (continuationToken != null);
        }
    }
}
</code>```

Body:
I don't have a good way to explain it :) but please take a look at the code below. The code below fetches all documents from an index using continuation token:

using System;
using System.Threading.Tasks;
using Azure;
using Azure.Search.Documents;
using Azure.Search.Documents.Models;

namespace SO71052143
{
    class Program
    {
        private const string accountName = "account-name";
        private const string accountKey = "admin-key";
        private const string indexName = "index-name";

        static async Task Main(string[] args)
        {
            SearchClient client = new SearchClient(new Uri($"https://{accountName}.search.windows.net"), indexName,
                new AzureKeyCredential(accountKey));
            var results = (await client.SearchAsync<SearchDocument>("*"));
            var searchResults = results.Value.GetResultsAsync();
            string continuationToken = null;
            do
            {
                await foreach (var item in searchResults.AsPages(continuationToken))
                {
                    continuationToken = item.ContinuationToken;
                    var documents = item.Values;
                }
            } while (continuationToken != null);
        }
    }
}


问:
useParams and useEffect, Parameter via ${id} in the useEffect function
This is the code, I receive the id in the console but not the response from the firestore server

```<code>import Item from './Item'
import { useState, useEffect } from "react";
import { useParams } from 'react-router-dom';
import {db} from "../Firebase"
import { collection, getDocs, query,} from "firebase/firestore";

const ContainerItems = () => {

    let idParam = useParams();
    const [ dataItem, setDataItem ] = useState([])

useEffect( () => {
    async function fetchData(){
    const querySnapshot = await getDocs(query(collection(db, `category/${(idParam)}/Items` )));
      let dataArray = []
      querySnapshot.forEach((doc) => {
        dataArray.push({...doc.data(), id: doc.id});
      });
      setDataItem(dataArray)
      console.log("Id",idParam)
    }
    fetchData();
}, [idParam])
    return (
        <>
            {dataItem.map((data)=>(
                <Item item={data} key={data.id}/>
            ))}
        </>
    )
}

export default ContainerItems;
</code>```

the request to the server works, it just doesn't work when I add ${idParam}

答:
You need to get the idParam out of the object using destructuring.

```<code>let { idParam }  = useParams();
</code>```

NOTE: Assuming you have named the path in the Route with the same name.

```<code><Route path="/category/:idParam">...</Route>
</code>```

Body:
This is the code, I receive the id in the console but not the response from the firestore server

import Item from './Item'
import { useState, useEffect } from "react";
import { useParams } from 'react-router-dom';
import {db} from "../Firebase"
import { collection, getDocs, query,} from "firebase/firestore";

const ContainerItems = () => {

    let idParam = useParams();
    const [ dataItem, setDataItem ] = useState([])

useEffect( () => {
    async function fetchData(){
    const querySnapshot = await getDocs(query(collection(db, `category/${(idParam)}/Items` )));
      let dataArray = []
      querySnapshot.forEach((doc) => {
        dataArray.push({...doc.data(), id: doc.id});
      });
      setDataItem(dataArray)
      console.log("Id",idParam)
    }
    fetchData();
}, [idParam])
    return (
        <>
            {dataItem.map((data)=>(
                <Item item={data} key={data.id}/>
            ))}
        </>
    )
}

export default ContainerItems;

the request to the server works, it just doesn't work when I add ${idParam}

Body:
You need to get the idParam out of the object using destructuring.

let { idParam }  = useParams();

NOTE: Assuming you have named the path in the Route with the same name.

<Route path="/category/:idParam">...</Route>


问:
How can I make the required roles either or instead of both
I'm setting up my commands and doing finishing touches meaning which roles are gonna have access to which commands, and I've ran into an issue where I want 2 roles to have access to the same command but I'm unsure how to do this OR that, I've tried a few different ways but it only lets me do either 1 or both of them at the same time.

this is how it looks in action meaning within the code itself

```<code>{
    permissions: [],
    requiredRoles: ['Staff', 'Rose'],
}
</code>```

and this is how it looks behind the scenes in my command handler

```<code>for (const requiredRole of requiredRoles) {
    const role = guild.roles.cache.find(
        (role) => role.name === requiredRole
    )

    if (!role || !member.roles.cache.has(role.id)) {
        message.reply(
            `You must have the "${requiredRole}" role to use this command.`
        )
        return
    }
}
</code>```

答:
Use Collection#hasAny() or Collection#hasAll()

if (!message.member.roles.cache.hasAny(requiredRoles)) // member has none of those roles
```
<p>or</p>
<pre class="lang-js prettyprint-override"><code>if (!message.member.roles.cache.hasAll(requiredRoles)) // member does not have ALL of these roles
</code>```

Body:
I'm setting up my commands and doing finishing touches meaning which roles are gonna have access to which commands, and I've ran into an issue where I want 2 roles to have access to the same command but I'm unsure how to do this OR that, I've tried a few different ways but it only lets me do either 1 or both of them at the same time.

this is how it looks in action meaning within the code itself

{
    permissions: [],
    requiredRoles: ['Staff', 'Rose'],
}

and this is how it looks behind the scenes in my command handler

for (const requiredRole of requiredRoles) {
    const role = guild.roles.cache.find(
        (role) => role.name === requiredRole
    )

    if (!role || !member.roles.cache.has(role.id)) {
        message.reply(
            `You must have the "${requiredRole}" role to use this command.`
        )
        return
    }
}

Body:
Use Collection#hasAny() or Collection#hasAll()

if (!message.member.roles.cache.hasAny(requiredRoles)) // member has none of those roles

or

if (!message.member.roles.cache.hasAll(requiredRoles)) // member does not have ALL of these roles


问:
Ignore Specific Columns Parsing a CSV File with Jackson CSV
My problem is that I need to parse CSV files with arbitrary columns/order into a known domain POJO (say Person). I can identify which columns that I need to process, ignoring the rest.

The option CsvParser.Feature.IGNORE_TRAILING_UNMAPPABLE" seemed to be exactly what I need, but the columns that I need to process are not necessarliy grouped at the start of the CSV file, and I cannot force the user to "re-order" the columns of their uploaded CSV files. Also, sometimes I do not get a header row, but the UI forces the user to identify columns & passes this information over.

For example, I have the following CSV file:

```<code>First Name,Last Name,Nickname,DOB,Occupation,Postal Code
Freddy,Benson,Ruprecht,08/14/45,Con Artist,76701
Lawrence,Jamieson,Prince,03/14/33,Con Artist,5201
Janet,Colgate,Jackal,03/13/55,Con Artist,90401
</code>```

I only need 4 of the 6 columns (First Name, Last Name, DOB, Postal Code), as my Person POJO only includes those fields:

```<code>public class Person {
    private String firstName;
    private String lastName;
    private LocalDate dob;
    private String postalCode;
}
</code>```

I have defined a CsvSchema typed for Person and specify the columns I'm interested in order (First Name, Last Name, IGNORE, DOB, IGNORE2, Postal Code), as I would like to skip columns (Nickname, Occupation). Hoever, the "IGNORE" columns get ignored during mapping in the deserializer, and I end up getting "Nickname" values for "DOB", resulting in invalid values for the DOB field.

答:
Ignoring unknown can be achieved as shown below(tested using jackson 2.13):

Annotate POJO

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.time.LocalDate;

@JsonIgnoreProperties(ignoreUnknown = true) //this is the trick to ignore all undeclared columns
public class Person {
    @JsonProperty("First Name") //declare what's needed
    private String firstName;
    private String lastName;
    private LocalDate dob;
    private String postalCode;
}
```
<ol start="2">
<li>Configure csvSchema</li>
</ol>
<pre class="lang-java prettyprint-override"><code>CsvMapper csvMapper = new CsvMapper();
CsvSchema csvSchema = csvMapper
    .schemaFor(Person.class)
    .withHeader()//header defines the order
    .withColumnReordering(true)//this allows columns to be in any order as long as there is a header
    ;
</code>```

Finally, use it to read csv file

csvMapper.readerFor(Person.class).with(csvSchema).readValues(csvFile)
```

Body:
My problem is that I need to parse CSV files with arbitrary columns/order into a known domain POJO (say Person). I can identify which columns that I need to process, ignoring the rest.

The option CsvParser.Feature.IGNORE_TRAILING_UNMAPPABLE" seemed to be exactly what I need, but the columns that I need to process are not necessarliy grouped at the start of the CSV file, and I cannot force the user to "re-order" the columns of their uploaded CSV files. Also, sometimes I do not get a header row, but the UI forces the user to identify columns & passes this information over.

For example, I have the following CSV file:

First Name,Last Name,Nickname,DOB,Occupation,Postal Code
Freddy,Benson,Ruprecht,08/14/45,Con Artist,76701
Lawrence,Jamieson,Prince,03/14/33,Con Artist,5201
Janet,Colgate,Jackal,03/13/55,Con Artist,90401

I only need 4 of the 6 columns (First Name, Last Name, DOB, Postal Code), as my Person POJO only includes those fields:

public class Person {
    private String firstName;
    private String lastName;
    private LocalDate dob;
    private String postalCode;
}

I have defined a CsvSchema typed for Person and specify the columns I'm interested in order (First Name, Last Name, IGNORE, DOB, IGNORE2, Postal Code), as I would like to skip columns (Nickname, Occupation). Hoever, the "IGNORE" columns get ignored during mapping in the deserializer, and I end up getting "Nickname" values for "DOB", resulting in invalid values for the DOB field.

Body:
Ignoring unknown can be achieved as shown below(tested using jackson 2.13):

Annotate POJO

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.time.LocalDate;

@JsonIgnoreProperties(ignoreUnknown = true) //this is the trick to ignore all undeclared columns
public class Person {
    @JsonProperty("First Name") //declare what's needed
    private String firstName;
    private String lastName;
    private LocalDate dob;
    private String postalCode;
}

Configure csvSchema

CsvMapper csvMapper = new CsvMapper();
CsvSchema csvSchema = csvMapper
    .schemaFor(Person.class)
    .withHeader()//header defines the order
    .withColumnReordering(true)//this allows columns to be in any order as long as there is a header
    ;

Finally, use it to read csv file

csvMapper.readerFor(Person.class).with(csvSchema).readValues(csvFile)


问:
Getting first day of every week in 6 months
I'm trying to figure out how can I get the the first day of week for the last 6 months and can't get to a working solution.

If I write date("Y-m-d 00:00:00", strtotime("-1 week", date("Y-m-d")); It just subtracts 7 days from the current date; what I want to do is to always return the date of Monday from that week.

Expected result:

```<code>2011-8-8 00:00:00
2011-8-1 00:00:00
2011-7-25 00:00:00
2011-7-18 00:00:00
etc
</code>```

答:
This should do it:

```<code>for ($i=0; $i<52/2; $i++)
echo date('Y-m-d', mktime(1, 0, 0, date('m'), date('d')-date('w')-$i*7+1, date('Y'))) . " 00:00:00\n";
</code>```

it's slightly changed from Mike's Post, who wants the sunday instead of the monday.

Body:
I'm trying to figure out how can I get the the first day of week for the last 6 months and can't get to a working solution.

If I write date("Y-m-d 00:00:00", strtotime("-1 week", date("Y-m-d")); It just subtracts 7 days from the current date; what I want to do is to always return the date of Monday from that week.

Expected result:

2011-8-8 00:00:00
2011-8-1 00:00:00
2011-7-25 00:00:00
2011-7-18 00:00:00
etc

Body:
This should do it:

for ($i=0; $i<52/2; $i++)
echo date('Y-m-d', mktime(1, 0, 0, date('m'), date('d')-date('w')-$i*7+1, date('Y'))) . " 00:00:00\n";

it's slightly changed from Mike's Post, who wants the sunday instead of the monday.


问:
one to many relationship query in oracle
I am trying to query a number of tables that have records with a one to many relationship.  The records I need are the myid values with the following criteria:

They have to have the attribute

firstcode with values of 1, 3, 8, 200. It can be any combination of these codes or all of them.

secondstuff is also related to the firstcode; each firstcode will have a secondstuff value.  The secondstuff values I am interested in are X, Y, Z (there are many others).

The problem I am running into is sometimes the myid record comes back, and it has 4 of the firstcode values, but not all of the firstcode values have the correct secondstuff value. Here is my query:

```<code>Select MYID
from myidtable a
where myid in (select myid1
              from dadtable b
              join  momtable c
              on b.dadid=c.momdadid
              join kidtable d
              on c.momid  = d.kidid
              where d.firstcode in (1, 3,8, 200)
              and c.secondstuff in ('X', 'Y’, 'Z')
              and thedate > to_date('12/31/2020', 'MM/DD/YYYY')
        )
</code>```

So in some cases I get a record back that has for example:

```<code>Myid  firstcode secondstuff
34      1           X
34      3           M
34      8           X
</code>```

As you can see, firstcode 3 has a secondstuff of M, as such, myid =34 shouldn’t be returned.  What I am looking for is something like the following:

```<code>Myid  firstcode secondstuff
 35    1           X
 35    3           Z
 35    8           X
</code>```

In this case, all my first codes that were associated with the myid table have the correct secondstuff values. Please note, its fine if some of the first code values are not associated with the myid table; Any two firstcodes will suffice.

答: From the information provided it seems that there are 2 columns with same name  in two different tables. You are filtering in kidtable and while displaying you are accessing column from a different table. Make sure that you filter secondstuff column from all the tables in which it is present.

Body:
I am trying to query a number of tables that have records with a one to many relationship.  The records I need are the myid values with the following criteria:

They have to have the attribute

firstcode with values of 1, 3, 8, 200. It can be any combination of these codes or all of them.

secondstuff is also related to the firstcode; each firstcode will have a secondstuff value.  The secondstuff values I am interested in are X, Y, Z (there are many others).

The problem I am running into is sometimes the myid record comes back, and it has 4 of the firstcode values, but not all of the firstcode values have the correct secondstuff value. Here is my query:

Select MYID
from myidtable a
where myid in (select myid1
              from dadtable b
              join  momtable c
              on b.dadid=c.momdadid
              join kidtable d
              on c.momid  = d.kidid
              where d.firstcode in (1, 3,8, 200)
              and c.secondstuff in ('X', 'Y’, 'Z')
              and thedate > to_date('12/31/2020', 'MM/DD/YYYY')
        )

So in some cases I get a record back that has for example:

Myid  firstcode secondstuff
34      1           X
34      3           M
34      8           X

As you can see, firstcode 3 has a secondstuff of M, as such, myid =34 shouldn’t be returned.  What I am looking for is something like the following:

Myid  firstcode secondstuff
 35    1           X
 35    3           Z
 35    8           X

In this case, all my first codes that were associated with the myid table have the correct secondstuff values. Please note, its fine if some of the first code values are not associated with the myid table; Any two firstcodes will suffice.


问:
Terraform aws_storagegateway_gateway not finding VPC Endpoint
I'm trying to launch an S3 File Gateway (AWS Storage Gateway) via Terraform, with EC2 hosting and a VPC endpoint for Storage Gateway.

I've been able to launch the Storage Gateway EC2 into a private subnet, then launch a second EC2 instance into the public subnet so that I can retrieve the gateway's activation key (https://docs.aws.amazon.com/storagegateway/latest/userguide/get-activation-key.html).

Unfortunately, when I provide a value for the activation_key in Terraform, it seems to be ignoring the gateway_vpc_endpoint, and just creates the Storage Gateway with a Public endpoint instead.

Code used:

```<code>resource "aws_storagegateway_gateway" "s3_file_gateway" {
  gateway_vpc_endpoint      = aws_vpc_endpoint.storage_gateway.dns_entry[0].dns_name
  activation_key            = "XXXX-XXXX-XXXX-XXXX-XXXX"
  gateway_name              = "Storage-Gateway"
  gateway_timezone          = var.gateway_timezone
  gateway_type              = var.gateway_type
  cloudwatch_log_group_arn  = aws_cloudwatch_log_group.storage_gateway.arn
  tags                      = var.tags

  lifecycle {
    ignore_changes = [smb_active_directory_settings, gateway_ip_address]
  }
}
</code>```

Has anyone come across this and been able to resolve it?

答:
This question is a few months old now, but when you connect onto the second EC2 to retrieve the activation key from the Gateway EC2, you're probably curling the incorrect URL.

You may have been following the instructions in this documentation:
https://docs.aws.amazon.com/storagegateway/latest/userguide/get-activation-key.html

When actually, this is the documentation that is more useful for what you're trying to achieve:
https://docs.aws.amazon.com/filegateway/latest/files3/gateway-private-link.html

This states that the format of the URL you should curl to get the activation key is:

http://VM IP
ADDRESS/?gatewayType=FILE_S3&activationRegion=REGION&vpcEndpoint=VPCEndpointDNSname&no_redirect

Body:
I'm trying to launch an S3 File Gateway (AWS Storage Gateway) via Terraform, with EC2 hosting and a VPC endpoint for Storage Gateway.

I've been able to launch the Storage Gateway EC2 into a private subnet, then launch a second EC2 instance into the public subnet so that I can retrieve the gateway's activation key (https://docs.aws.amazon.com/storagegateway/latest/userguide/get-activation-key.html).

Unfortunately, when I provide a value for the activation_key in Terraform, it seems to be ignoring the gateway_vpc_endpoint, and just creates the Storage Gateway with a Public endpoint instead.

Code used:

resource "aws_storagegateway_gateway" "s3_file_gateway" {
  gateway_vpc_endpoint      = aws_vpc_endpoint.storage_gateway.dns_entry[0].dns_name
  activation_key            = "XXXX-XXXX-XXXX-XXXX-XXXX"
  gateway_name              = "Storage-Gateway"
  gateway_timezone          = var.gateway_timezone
  gateway_type              = var.gateway_type
  cloudwatch_log_group_arn  = aws_cloudwatch_log_group.storage_gateway.arn
  tags                      = var.tags

  lifecycle {
    ignore_changes = [smb_active_directory_settings, gateway_ip_address]
  }
}

Has anyone come across this and been able to resolve it?


问:
SwiftUI Setting Bind<String> in Text field
I've got the following object that contain list of strings:

```<code>class handler: ObservableObject {
  @Published var items = [String]()
}

</code>```

In some closure, I set this list with valid values :

```<code>for item in item_list! {
  self.handler.items.append(item.stringData)
}
</code>```

and in the ContentView part I've got Picker that support to present that list of strings in realtime:

```<code>VStack {
  Picker("items", selection: $arg1) {
    ForEach($handler.items, id: \.self) {
      Text($0)
    }
  }
}
</code>```

However, it fails to compile due to the following reason :

Initializer 'init(_:)' requires that 'Binding<String>' conform to 'StringProtocol'

Any Idea how to resolve this ?

答:
You don't need binding here to loop items, instead use handler directly (ie. without $), like

```<code>ForEach(handler.items, id: \.self) {    // << here !!
  Text($0)
}
</code>```

Body:
I've got the following object that contain list of strings:

class handler: ObservableObject {
  @Published var items = [String]()
}

In some closure, I set this list with valid values :

for item in item_list! {
  self.handler.items.append(item.stringData)
}

and in the ContentView part I've got Picker that support to present that list of strings in realtime:

VStack {
  Picker("items", selection: $arg1) {
    ForEach($handler.items, id: \.self) {
      Text($0)
    }
  }
}

However, it fails to compile due to the following reason :

Initializer 'init(_:)' requires that 'Binding<String>' conform to 'StringProtocol'

Any Idea how to resolve this ?

Body:
You don't need binding here to loop items, instead use handler directly (ie. without $), like

ForEach(handler.items, id: \.self) {    // << here !!
  Text($0)
}


问:
No overload for method 'SetValue' takes 7 arguments in Umbraco 9
I am trying to download and store remote images locally as media, as a part of a Recurring Hosted Service (see here). I am following the example for Umbraco 9.0 for creating a media item from a stream:

https://our.umbraco.com/documentation/reference/management/services/mediaservice/#creating-a-new-media-item-from-a-stream

This is how my method looks:

```<code>        private void ConvertImageToLocalImage(string remoteImageUrl, string title)
        {

            var downloadFolder = $"{_hostingEnvironment.ContentRootPath}\\App_Data\\TEMP\\Images";

            var fileName = Path.GetFileName(remoteImageUrl.Split('?')[0]);

            var fileExt = Path.GetExtension(fileName);

            var downloadPath = $"{downloadFolder}\\{title.Replace(" ", "_")}{fileExt}";

            if (Directory.Exists(downloadFolder) == false)
            {
                Directory.CreateDirectory(downloadFolder);
            }

            using (var client = new WebClient())

            client.DownloadFile(remoteImageUrl, downloadPath);

            using FileStream stream = System.IO.File.OpenRead(downloadPath);

            IMedia media = _mediaService.CreateMedia(title, -1, Constants.Conventions.MediaTypes.Image);

            media.SetValue(_mediaFileManager, _shortStringHelper, _contentTypeBaseServiceProvider, _serializer, Constants.Conventions.MediaTypes.File, fileName, stream);

            _mediaService.Save(media);
        }
</code>```

However, I get the error:

No overload for method 'SetValue' takes 7 arguments

The only 'SetValue' method I appear to have access to is:

```<code>void SetValue(string propertyTypeAlias, object value, string culture = null, string segment = null);
</code>```

I'm not sure what I'm doing wrong...

I have the following using statements at the top of the file:

```<code>using Umbraco.Cms.Core;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Infrastructure.HostedServices;
</code>```

答:
Worked it out...

I needed to include:

```<code>using Umbraco.Extensions;
</code>```

And then the signiture for the overloaded method is actually really different to what the docs say, this is the signiture of the method:

```<code>void SetValue(this IContentBase content, MediaFileManager mediaFileManager, MediaUrlGeneratorCollection mediaUrlGenerators, IShortStringHelper shortStringHelper, IContentTypeBaseServiceProvider contentTypeBaseServiceProvider, string propertyTypeAlias, string filename, Stream filestream, string culture = null, string segment = null)
</code>```

Which ended up looking like this:

```<code>media.SetValue(_mediaFileManager, _mediaUrlGenerators, _shortStringHelper, _contentTypeBaseServiceProvider, "umbracoFile", fileName, stream)
</code>```

Body:
I am trying to download and store remote images locally as media, as a part of a Recurring Hosted Service (see here). I am following the example for Umbraco 9.0 for creating a media item from a stream:

https://our.umbraco.com/documentation/reference/management/services/mediaservice/#creating-a-new-media-item-from-a-stream

This is how my method looks:

        private void ConvertImageToLocalImage(string remoteImageUrl, string title)
        {

            var downloadFolder = $"{_hostingEnvironment.ContentRootPath}\\App_Data\\TEMP\\Images";

            var fileName = Path.GetFileName(remoteImageUrl.Split('?')[0]);

            var fileExt = Path.GetExtension(fileName);

            var downloadPath = $"{downloadFolder}\\{title.Replace(" ", "_")}{fileExt}";

            if (Directory.Exists(downloadFolder) == false)
            {
                Directory.CreateDirectory(downloadFolder);
            }

            using (var client = new WebClient())

            client.DownloadFile(remoteImageUrl, downloadPath);

            using FileStream stream = System.IO.File.OpenRead(downloadPath);

            IMedia media = _mediaService.CreateMedia(title, -1, Constants.Conventions.MediaTypes.Image);

            media.SetValue(_mediaFileManager, _shortStringHelper, _contentTypeBaseServiceProvider, _serializer, Constants.Conventions.MediaTypes.File, fileName, stream);

            _mediaService.Save(media);
        }

However, I get the error:

No overload for method 'SetValue' takes 7 arguments

The only 'SetValue' method I appear to have access to is:

void SetValue(string propertyTypeAlias, object value, string culture = null, string segment = null);

I'm not sure what I'm doing wrong...

I have the following using statements at the top of the file:

using Umbraco.Cms.Core;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Infrastructure.HostedServices;

Body:
Worked it out...

I needed to include:

using Umbraco.Extensions;

And then the signiture for the overloaded method is actually really different to what the docs say, this is the signiture of the method:

void SetValue(this IContentBase content, MediaFileManager mediaFileManager, MediaUrlGeneratorCollection mediaUrlGenerators, IShortStringHelper shortStringHelper, IContentTypeBaseServiceProvider contentTypeBaseServiceProvider, string propertyTypeAlias, string filename, Stream filestream, string culture = null, string segment = null)

Which ended up looking like this:

media.SetValue(_mediaFileManager, _mediaUrlGenerators, _shortStringHelper, _contentTypeBaseServiceProvider, "umbracoFile", fileName, stream)


问:
How to handle forwarded e-mails in Rails ActionMailbox?
We are using Rails 7 to build an application which, amongst other features, should perform some actions when e-mails are sent to one of its e-mail addresses (which have, for instance, the format ticket-{uuid}@ourdomain.com).

Rails' ActionMailbox's routing works fine for direct e-mails. However, when e-mails are forwarded, they are not recognized by ActionMailbox at all.

How can we ensure that forwarded e-mails are also handled and routed correctly with ActionMailbox?

EDIT: A simplified version of the code we are using:

class ApplicationMailbox < ActionMailbox::Base
  routing /^ticket-(.+)@ourdomain.com$/i => :service_tickets
end
```
<pre class="lang-rb prettyprint-override"><code>class ServiceTicketsMailbox < ApplicationMailbox
  def process
    puts "processing email: #{mail.inspect}"
    # ... and then we extract its fields
    # and store some of them in the database.
  end
end
</code>```

答:
Ok I think I found the issue:

When you send a normal e-mail the To header looks like this To: ticket-123@@ourdomain.com and this matches with /^ticket-(.+)@ourdomain.com$/i

However when you forward the e-mail the header looks like this To: John Doe <ticket-123@ourdomain.com> and this will not match with your regex.

Change the regex to /ticket-(.+)@ourdomain.com/i and it should work.

You can try it out on https://regexr.com/

Body:
We are using Rails 7 to build an application which, amongst other features, should perform some actions when e-mails are sent to one of its e-mail addresses (which have, for instance, the format ticket-{uuid}@ourdomain.com).

Rails' ActionMailbox's routing works fine for direct e-mails. However, when e-mails are forwarded, they are not recognized by ActionMailbox at all.

How can we ensure that forwarded e-mails are also handled and routed correctly with ActionMailbox?

EDIT: A simplified version of the code we are using:

class ApplicationMailbox < ActionMailbox::Base
  routing /^ticket-(.+)@ourdomain.com$/i => :service_tickets
end

class ServiceTicketsMailbox < ApplicationMailbox
  def process
    puts "processing email: #{mail.inspect}"
    # ... and then we extract its fields
    # and store some of them in the database.
  end
end


问:
Missing categorical data should be encoded with an all-zero one-hot vector
I am working on a machine learning project with very sparsely labeled data. There are several categorical features, resulting in roughly one hundred different classes between the features.

For example:

```<code>0    red
1    blue
2    <missing>

color_cat = pd.DataFrame(['red', 'blue', np.NAN])
color_enc = OneHotEncoder(sparse=True, handle_unknown='ignore')
color_one_hot = color_enc.fit_transform(color_cat)
</code>```

After I put these through scikit's OneHotEncoder I am expecting the missing data to be encoded as 00, since the docs state that handle_unknown='ignore' causes the encoder to return an all zero array. Substituting another value, such as with [SimpleImputer][1] is not an option for me.

What I expect:

```<code>0    10
1    01
2    00
</code>```

Instead OneHotEncoder treats the missing values as another category.

What I get:

```<code>0    100
1    010
2    001
</code>```

I have seen the related question: How to handle missing values (NaN) in categorical data when using scikit-learn OneHotEncoder?
But the solutions do not work for me. I explicitly require a zero vector.

答:
Never really worked with sparse matrix, but one way is to remove the column corresponding to your nan value. Get the categories_ from your model and create a Boolean mask where is it not nan (I use pd.Series.notna but probably other way) and create a new (or reassign) sparse matrix. Basically add to your code:

```<code># currently you have
color_one_hot
# <3x3 sparse matrix of type '<class 'numpy.float64'>'
#   with 3 stored elements in Compressed Sparse Row format>

# line of code to add
new_color_one_hot = color_one_hot[:,pd.Series(color_enc.categories_[0]).notna().to_numpy()]

# and now you have
new_color_one_hot
# <3x2 sparse matrix of type '<class 'numpy.float64'>'
#   with 2 stored elements in Compressed Sparse Row format>

# and
new_color_one_hot.todense()
# matrix([[0., 1.],
#         [1., 0.],
#         [0., 0.]])
</code>```

Edit: also get_dummies kind of gives similar result pd.get_dummies(color_cat[0], sparse=True)

EDIT: After looking a bit more you can specify the parameter categories in OneHotEncoder so if you do:

```<code>color_cat = pd.DataFrame(['red', 'blue', np.nan])
color_enc = OneHotEncoder(categories=[color_cat[0].dropna().unique()],  ## here
                          sparse=True, handle_unknown='ignore')
color_one_hot = color_enc.fit_transform(color_cat)
color_one_hot.todense()
# matrix([[1., 0.],
#         [0., 1.],
#         [0., 0.]])
</code>```

Body:
I am working on a machine learning project with very sparsely labeled data. There are several categorical features, resulting in roughly one hundred different classes between the features.

For example:

0    red
1    blue
2    <missing>

color_cat = pd.DataFrame(['red', 'blue', np.NAN])
color_enc = OneHotEncoder(sparse=True, handle_unknown='ignore')
color_one_hot = color_enc.fit_transform(color_cat)

After I put these through scikit's OneHotEncoder I am expecting the missing data to be encoded as 00, since the docs state that handle_unknown='ignore' causes the encoder to return an all zero array. Substituting another value, such as with [SimpleImputer][1] is not an option for me.

What I expect:

0    10
1    01
2    00

Instead OneHotEncoder treats the missing values as another category.

What I get:

0    100
1    010
2    001

I have seen the related question: How to handle missing values (NaN) in categorical data when using scikit-learn OneHotEncoder?
But the solutions do not work for me. I explicitly require a zero vector.

Body:
Never really worked with sparse matrix, but one way is to remove the column corresponding to your nan value. Get the categories_ from your model and create a Boolean mask where is it not nan (I use pd.Series.notna but probably other way) and create a new (or reassign) sparse matrix. Basically add to your code:

# currently you have
color_one_hot
# <3x3 sparse matrix of type '<class 'numpy.float64'>'
#   with 3 stored elements in Compressed Sparse Row format>

# line of code to add
new_color_one_hot = color_one_hot[:,pd.Series(color_enc.categories_[0]).notna().to_numpy()]

# and now you have
new_color_one_hot
# <3x2 sparse matrix of type '<class 'numpy.float64'>'
#   with 2 stored elements in Compressed Sparse Row format>

# and
new_color_one_hot.todense()
# matrix([[0., 1.],
#         [1., 0.],
#         [0., 0.]])

Edit: also get_dummies kind of gives similar result pd.get_dummies(color_cat[0], sparse=True)

EDIT: After looking a bit more you can specify the parameter categories in OneHotEncoder so if you do:

color_cat = pd.DataFrame(['red', 'blue', np.nan])
color_enc = OneHotEncoder(categories=[color_cat[0].dropna().unique()],  ## here
                          sparse=True, handle_unknown='ignore')
color_one_hot = color_enc.fit_transform(color_cat)
color_one_hot.todense()
# matrix([[1., 0.],
#         [0., 1.],
#         [0., 0.]])


问:
Is there a more efficient way to compare two lists in python than O(m*n)?
I am trying to find a method for comparing two lists in python in a more efficient way than what I think is the current O(m*n) runtime. Right now I have a brute force approach of iterating each item in m and comparing it to n but is anything else possible? I have tried maybe sorting the lists first for maybe something faster but I am kind of stuck on whether anything else could work here.

In my function i take each item in m and compare it to n and count the number of times the item in m is greater than the item in n.

```<code>n = [1,3,7]
m = [2,9]

def comparison(n,m):
counter = 0
for i in m:
    for j in n:
        if i >= j:
            counter += 1

return counter

</code>```

答:
Here's how you could use a binary search approach after sorting the target list:

```<code>from bisect import bisect_right

n = [1,3,7,2]
m = [2,9]

n.sort()
counter = sum(bisect_right(n,value) for value in m)

print(counter) # 6
</code>```

This should correspond to O((n+m) x log(n)) if n is not known to be sorted.  If n is always provided in sorted order, then you don't need your function to sort it and you will get O(m x log(n)) time complexity.

Body:
I am trying to find a method for comparing two lists in python in a more efficient way than what I think is the current O(m*n) runtime. Right now I have a brute force approach of iterating each item in m and comparing it to n but is anything else possible? I have tried maybe sorting the lists first for maybe something faster but I am kind of stuck on whether anything else could work here.

In my function i take each item in m and compare it to n and count the number of times the item in m is greater than the item in n.

n = [1,3,7]
m = [2,9]

def comparison(n,m):
counter = 0
for i in m:
    for j in n:
        if i >= j:
            counter += 1

return counter

Body:
Here's how you could use a binary search approach after sorting the target list:

from bisect import bisect_right

n = [1,3,7,2]
m = [2,9]

n.sort()
counter = sum(bisect_right(n,value) for value in m)

print(counter) # 6

This should correspond to O((n+m) x log(n)) if n is not known to be sorted.  If n is always provided in sorted order, then you don't need your function to sort it and you will get O(m x log(n)) time complexity.


问:
java mouse and keyboard listener, macro recording
If i read correctly, the mouse and keyboard listeners are intended to capture movement within an application. what I want to do is capture movement system wide.
Mouse movement/clicks and button presses. </p>

<p>Ideally i would like a manner of capturing this movement and being able to replay it by passing appropriate commands to the robot class. Does this seem reasonable, or am i going about this all wrong? </p>

答:
It is possible if you create transparent full screen window and capture events on it.
To replay the events use class java.awt.Robot.

Use this resource for more info how to create transparent window:
http://java.sun.com/developer/technicalArticles/GUI/translucent_shaped_windows/

Body:
If i read correctly, the mouse and keyboard listeners are intended to capture movement within an application. what I want to do is capture movement system wide.
Mouse movement/clicks and button presses.

Ideally i would like a manner of capturing this movement and being able to replay it by passing appropriate commands to the robot class. Does this seem reasonable, or am i going about this all wrong?


问:
Lua float errors
I'm fairly new to lua, but I read that it does not have integers, so all numbers are floats.
I noticed in my log that some numbers get a slight inaccuracy added to it. For instance 0.14 is written as 0.14000000059605.
In that function it doesn't really matter if the number is a little diferent, as it is a comparison with a random number. But I do a lot of equals comparisons with numbes like NumReg() == 2 where it would give a wrong result if the 2 gets unrounded.
Do do I have to account for this by rounding them down, or are non-tiny numbers not affected?</p>

答:
You can format a float for your needs.

Example to play with in an interactive Lua console...

```<code>> _VERSION
Lua 5.4
tonumber(string.format('%.3f', 0.14000000059605))
0.14
> print(tonumber(string.format('%.3f', 0.14000000059605)))
0.14
> type(tonumber(string.format('%.3f', 0.14000000059605)))
number
> math.type(tonumber(string.format('%.3f', 0.14000000059605)))
float
> tonumber(string.format('%.3f', 0.14000000059605)) == 0.140
true
</code>```

Title: Lua float errors

Body:
You can format a float for your needs.

Example to play with in an interactive Lua console...

> _VERSION
Lua 5.4
tonumber(string.format('%.3f', 0.14000000059605))
0.14
> print(tonumber(string.format('%.3f', 0.14000000059605)))
0.14
> type(tonumber(string.format('%.3f', 0.14000000059605)))
number
> math.type(tonumber(string.format('%.3f', 0.14000000059605)))
float
> tonumber(string.format('%.3f', 0.14000000059605)) == 0.140
true


问:
Adding elements to C++ vector
I want to learn more about C++ coding, especially to design and create a desktop application.

To begin, I want to create a notification app where I can make a task by giving the task a name and content. For this, I use 2 vectors (name and content).

I initialize the vectors like this:

```<code>std::vector <LPWSTR> NameTask;
std::vector <LPWSTR> ContentTask;
</code>```

After, I simply create a button to add the name and content into the vectors:

```<code>if (wmId == ID_BUTTON) {
    //local variables (only for the Button event)
    int len_name = GetWindowTextLength(TextBox_Name) + 1; //give the lenght value of the text in the textbox
    int len_content = GetWindowTextLength(TextBox_content) + 1; //give the lenght value of the text in the textbox
    wchar_t Text_name[100] = L""; //Wchar is compatible with LPWSTR
    wchar_t Text_content[100] = L""; //Wchar is compatible with LPWSTR

    // get the text of the Text edit and put it in local variable name and content
    GetWindowText(TextBox_Name, Text_name, len_name);
    GetWindowText(TextBox_content, Text_content, len_content);
    //verify if the texts are empty
    if (wcslen(Text_name) == 0 || wcslen(Text_content) == 0) {
        MessageBox(hWnd, L"name and content can't be empty", L"MessageBox", MB_OK);
    }
    else {
        NameTask.push_back(Text_name); // set name of task in vector of NameTask
        ContentTask.push_back (Text_name); // set content of task in vector of ContentTask
        //ComboBox_AddString(Combobox, Text_name); // add the title of the task in the combotext
        //SetWindowText(TextBox_Name, L""); //empty the textbox
        SetWindowText(TextBox_content, NameTask.at(0)); // visualize first element of vector name
    }
}
</code>```

The problem that I have is that, when I add a new element to the vector, and then I go to visualize it, it always shows me the last element added. Even when I use SetWindowText(TextBox_content, NameTask.at(0));

And when I use another button to visualize the name and content, it gives a strange output:

答:
The problem is that you are storing dangling pointers in your vectors.  Your if block is allocating local arrays, then storing pointers to those arrays into the vectors.  When the if block exits, the arrays are destroyed, but the vectors are still pointing at them.

You need to make a copy of the text data you are retrieving from your UI.  You can use std::wstring to handle that.

Try something more like this:

```<code>struct Task
{
    std::wstring Name;
    std::wstring Content;
};

std::vector<Task> Tasks;

...

if (wmId == ID_BUTTON) {
    int len_name = GetWindowTextLength(TextBox_Name);
    int len_content = GetWindowTextLength(TextBox_content);

    if (len_name == 0 || len_content == 0) {
        MessageBox(hWnd, L"name and content can't be empty", L"MessageBox", MB_OK);
    }
    else {
        ++len_name;
        ++len_content;

        std::wstring Text_name(L'\0', len_name);
        std::wstring Text_content(L'\0', len_content);

        len_name = GetWindowText(TextBox_Name, &Text_name[0], len_name);
        Text_name.resize(len_name);

        len_content = GetWindowText(TextBox_content, &Text_content[0], len_content);
        Text_content.resize(len_content);

        Task task;
        task.Name = Text_name;
        task.Content = Text_content;
        Tasks.push_back(task);

        //ComboBox_AddString(Combobox, Text_name.c_str());
        //SetWindowText(TextBox_Name, L"");
        SetWindowText(TextBox_content, Text_name.c_str());
    }
}

...

// use Tasks[index].Name(.c_str()) and Tasks[index].Content(.c_str()) as needed...
</code>```

Title: Adding elements to C++ vector

Body:
I want to learn more about C++ coding, especially to design and create a desktop application.

To begin, I want to create a notification app where I can make a task by giving the task a name and content. For this, I use 2 vectors (name and content).

I initialize the vectors like this:

std::vector <LPWSTR> NameTask;
std::vector <LPWSTR> ContentTask;

After, I simply create a button to add the name and content into the vectors:

if (wmId == ID_BUTTON) {
    //local variables (only for the Button event)
    int len_name = GetWindowTextLength(TextBox_Name) + 1; //give the lenght value of the text in the textbox
    int len_content = GetWindowTextLength(TextBox_content) + 1; //give the lenght value of the text in the textbox
    wchar_t Text_name[100] = L""; //Wchar is compatible with LPWSTR
    wchar_t Text_content[100] = L""; //Wchar is compatible with LPWSTR

    // get the text of the Text edit and put it in local variable name and content
    GetWindowText(TextBox_Name, Text_name, len_name);
    GetWindowText(TextBox_content, Text_content, len_content);
    //verify if the texts are empty
    if (wcslen(Text_name) == 0 || wcslen(Text_content) == 0) {
        MessageBox(hWnd, L"name and content can't be empty", L"MessageBox", MB_OK);
    }
    else {
        NameTask.push_back(Text_name); // set name of task in vector of NameTask
        ContentTask.push_back (Text_name); // set content of task in vector of ContentTask
        //ComboBox_AddString(Combobox, Text_name); // add the title of the task in the combotext
        //SetWindowText(TextBox_Name, L""); //empty the textbox
        SetWindowText(TextBox_content, NameTask.at(0)); // visualize first element of vector name
    }
}

The problem that I have is that, when I add a new element to the vector, and then I go to visualize it, it always shows me the last element added. Even when I use SetWindowText(TextBox_content, NameTask.at(0));

And when I use another button to visualize the name and content, it gives a strange output:

Body:
The problem is that you are storing dangling pointers in your vectors.  Your if block is allocating local arrays, then storing pointers to those arrays into the vectors.  When the if block exits, the arrays are destroyed, but the vectors are still pointing at them.

You need to make a copy of the text data you are retrieving from your UI.  You can use std::wstring to handle that.

Try something more like this:

struct Task
{
    std::wstring Name;
    std::wstring Content;
};

std::vector<Task> Tasks;

...

if (wmId == ID_BUTTON) {
    int len_name = GetWindowTextLength(TextBox_Name);
    int len_content = GetWindowTextLength(TextBox_content);

    if (len_name == 0 || len_content == 0) {
        MessageBox(hWnd, L"name and content can't be empty", L"MessageBox", MB_OK);
    }
    else {
        ++len_name;
        ++len_content;

        std::wstring Text_name(L'\0', len_name);
        std::wstring Text_content(L'\0', len_content);

        len_name = GetWindowText(TextBox_Name, &Text_name[0], len_name);
        Text_name.resize(len_name);

        len_content = GetWindowText(TextBox_content, &Text_content[0], len_content);
        Text_content.resize(len_content);

        Task task;
        task.Name = Text_name;
        task.Content = Text_content;
        Tasks.push_back(task);

        //ComboBox_AddString(Combobox, Text_name.c_str());
        //SetWindowText(TextBox_Name, L"");
        SetWindowText(TextBox_content, Text_name.c_str());
    }
}

...

// use Tasks[index].Name(.c_str()) and Tasks[index].Content(.c_str()) as needed...


问:
Is it possible to exclude only French tweets from a Twitter advanced search engine?
To find only tweets in French, i use:

```<code>find this words lang:fr
</code>```

But what if I want to exclude only French from the results and find all the others?

答:
very easy, just put a minus - before the lang:fr operator to exclude it :-)

```<code>find this words -lang:fr
</code>```

If i'm not mistaken all of Twitter's Advanced Search Operators, like filter:, near:, within:, include: and many more, can be negated to exclude results corresponding to the specific operator.

Body:
To find only tweets in French, i use:

find this words lang:fr

But what if I want to exclude only French from the results and find all the others?

Body:
very easy, just put a minus - before the lang:fr operator to exclude it :-)

find this words -lang:fr

If i'm not mistaken all of Twitter's Advanced Search Operators, like filter:, near:, within:, include: and many more, can be negated to exclude results corresponding to the specific operator.


问:
tabulator - how to display a loading indicator while data is fetched from db based on a prop?
I created a tabulator component in my vue app and I am passing Tabulator options data and columns via props as following:

// parent component
<template>

        <Tabulator :table-data="materialsData" :table-columns="options.columns" :is-loading="materials.isLoading" />

</template>

...
```
<pre class="lang-js prettyprint-override"><code>// Tabulator component
props: {
    tableData: {
        type: Array,
        default: function() {
            return [
                { name: "Billy Bob", age: "12" },
                { name: "Mary May", age: "1" },
            ];
        },
    },
    tableColumns: {
        type: Array,
        default: function() {
            return [
                { title: "Name", field: "name", sorter: "string", width: 200, editor: true },
                { title: "Age", field: "age", sorter: "number", align: "right", formatter: "progress" },
            ];
        },
    },
    isLoading: {
        type: Boolean,
        default: true,
    },
},
mounted() {
    // instantiate Tabulator
    this.tabulator = new Tabulator(this.$refs.table, {
        placeholder: "loading data...",
        //placeholder: "<font-awesome-icon icon='circle-notch' spin size='2x' />",
        data: this.tableData, // link data to table (passed as prop)
        columns: this.tableColumns, // define table columns (passed as prop)
    });
},
</code>```

everything works well besides indicating to the user that data is loading. I first tried using the placeholder option (http://tabulator.info/docs/4.7/layout#placeholder) but realized it is not applicable because it is also rendered when no data is displayed.

is there a way to tell Tabulator to preferably render a loading spinner or a text, based on my prop isLoading?

答:
In tabulator 5, the new option is called dataLoaderLoading. According to the documentation you can pass an 'html'. In the code, this can be a string or an html component. I think there is a bug when you pass a string and the html is not correctly generated (from what I can tell the way the Template element is used). So to get it to work I had to pass the html element, something in the lines of:

```<code>const template = document.createElement('template');
template.innerHTML = '<div style="display:inline-block;" class="d-flex flex-row">' +
                    '<div>Loading... </div>' +
                    '<div class="ml-2 activity-sm" data-role="activity" data-type="atom" data-style="dark"></div>' +
                '</div>';
const dataLoaderLoading = template.content.firstChild;
...
new Tabulator("#mytable", {
    dataLoaderLoading: dataLoaderLoading,
    ...
</code>```

Body:
I created a tabulator component in my vue app and I am passing Tabulator options data and columns via props as following:

// parent component
<template>

        <Tabulator :table-data="materialsData" :table-columns="options.columns" :is-loading="materials.isLoading" />

</template>

...

// Tabulator component
props: {
    tableData: {
        type: Array,
        default: function() {
            return [
                { name: "Billy Bob", age: "12" },
                { name: "Mary May", age: "1" },
            ];
        },
    },
    tableColumns: {
        type: Array,
        default: function() {
            return [
                { title: "Name", field: "name", sorter: "string", width: 200, editor: true },
                { title: "Age", field: "age", sorter: "number", align: "right", formatter: "progress" },
            ];
        },
    },
    isLoading: {
        type: Boolean,
        default: true,
    },
},
mounted() {
    // instantiate Tabulator
    this.tabulator = new Tabulator(this.$refs.table, {
        placeholder: "loading data...",
        //placeholder: "",
        data: this.tableData, // link data to table (passed as prop)
        columns: this.tableColumns, // define table columns (passed as prop)
    });
},

everything works well besides indicating to the user that data is loading. I first tried using the placeholder option (http://tabulator.info/docs/4.7/layout#placeholder) but realized it is not applicable because it is also rendered when no data is displayed.

is there a way to tell Tabulator to preferably render a loading spinner or a text, based on my prop isLoading?

Body:
In tabulator 5, the new option is called dataLoaderLoading. According to the documentation you can pass an 'html'. In the code, this can be a string or an html component. I think there is a bug when you pass a string and the html is not correctly generated (from what I can tell the way the Template element is used). So to get it to work I had to pass the html element, something in the lines of:

const template = document.createElement('template');
template.innerHTML = '<div style="display:inline-block;" class="d-flex flex-row">' +
                    '<div>Loading... </div>' +
                    '<div class="ml-2 activity-sm" data-role="activity" data-type="atom" data-style="dark"></div>' +
                '</div>';
const dataLoaderLoading = template.content.firstChild;
...
new Tabulator("#mytable", {
    dataLoaderLoading: dataLoaderLoading,
    ...


问:
Txt to treeView
I want to generate a tree view using text file in c#. But I am unable to apply the concept. Would you please tell me how to do it? The txt file contains the following: Separately separated:

Separator =( , ) Parents =Capital letters. Child =Lowercase letters.

A , a, b, c

B, d, e, f

C, g, h, q

答:
Pseudo code would look like this

```<code>foreach line in fileLines
{
    lineNodes = line.Split(", ")
    newParentNode = tree.Nodes.Add(new Node(lineNodes[0]))
    newParentNode.Children.Add(new Node(lineNodes[1]))
    newParentNode.Children.Add(new Node(lineNodes[2]))
    newParentNode.Children.Add(new Node(lineNodes[3]))
}
</code>```

Now, you can use c# specific syntax to implement your home work

Title: Txt to treeView

Body:
Pseudo code would look like this

foreach line in fileLines
{
    lineNodes = line.Split(", ")
    newParentNode = tree.Nodes.Add(new Node(lineNodes[0]))
    newParentNode.Children.Add(new Node(lineNodes[1]))
    newParentNode.Children.Add(new Node(lineNodes[2]))
    newParentNode.Children.Add(new Node(lineNodes[3]))
}

Now, you can use c# specific syntax to implement your home work