问:
Confused when I should and shouldn't use "const" in C
I have a dictionary that goes like this:

```<code>typedef struct dictNode {
    int key;
    char *value;
    struct dictNode *next;
} Dict;
</code>```

And a get() function that goes like this:

```<code>char *get(const Dict *dict, int key) {
    if(!dict) return NULL;

    Dict *currPtr = dict;

    while(currPtr) {
        if(currPtr->key == key) {
            return currPtr->value;
        }

        currPtr = currPtr->next;
    }
}
</code>```

Compiling this code produces the following error:

dict.c:85: warning: initialization discards qualifiers from pointer target type

This warning refers to the line:

```<code>Dict *currPtr = dict;
</code>```

If I add a "const" before that line like this:

```<code>const Dict *currPtr = dict;
</code>```

The warning goes away...

1) First thing I don't understand is this: I added "const" to the dict argument in get() so that the compiler warns me if I try to change the address dict is pointing to, otherwise I won't be able to access the dictionary in the main program cause I lost the address I was pointing too. Now, I'm creating a new pointer, currPtr, that points to the same place as dict. This way, I use this pointer instead, to traverse the dictionary and keep dict pointer intact. Why do I also need to have const for currPtr?

2) Second thing I don't understand is this: The line currPtr = currPtr->next; is changing the currPtr pointer, so, why doesn't the compile warn me about that if I added a const to currPtr?

Then I have a del() function that goes like this:

```<code>Dict *del(const Dict *dict, int key) {
    if(!dict) return NULL;

    Dict *currPtr = dict;
    Dict *prevPtr = dict;

    while(currPtr) {
        if(currPtr->key == key) {
            prevPtr->next = currPtr->next;
            free(currPtr);
        }

        prevPtr = currPtr;
        currPtr = currPtr->next;
    }

    return dict;
}
</code>```

Please note that I'm aware that this delete function code is not complete, it does not correctly work if I want to delete the first element for instance. It doesn't matter, I'll finish later, it suffices to demonstrate my problem...

3) So, in the get() function I needed to add const to currPtr but in this del() function, I don't need to add const to currPtr nor prevPtr? In both functions I am changing the currPtr pointer and in the case of the del() function I'm changing the prevPtr pointer too. Why does the get() function require me to add a const before currPtr and the del() function does not require me to add a const before currPtr and prevPtr?

I can basically resume this whole post to: When and where exactly in my get() and del() functions should I use const and why, and, when and where I shouldn't?

答:
Without a pointer, you would have

```<code>const Dict currPtr
</code>```

which is a constant Dict. Now, if you make it a pointer you have

```<code>const Dict *currPtr
</code>```

which is a pointer to a constant Dict. That does not mean that the pointer is constant. But it does mean that the Dict pointed to is treated as constant

```<code>currPtr->key = 10; // error, dict is treated as constant.
</code>```

But the pointer is not

```<code>currPtr = otherPtr; // possible: the pointer is not constant
</code>```

You would get an error for the second case if you make the pointer constant. Keeping the pointed dict constant too, this would look like this

```<code>const Dict * const currPtr = init;
</code>```

Now you can't set currPtr to point to something different, because the pointer is now constant, not just what the pointer points to is treated so. Some people like the look if the const is always right to the stuff that it makes const. This would look like this

```<code>Dict const * const currPtr = init;
</code>```

which is the same as the previous snippet. If you then read it from right to left, it tells you what it is "const pointer to a const Dict". If you have a type, it doesn't matter how you order the specifiers

```<code>int const a = 10;
const int b = 10;
</code>```

Both are constant integers. That is why we could put const right of the Dict type specifier.

Now, if you have a pointer, you can always pretend you point to a constant object, even though the object wasn't declared const. But you can't pretend to work with a non-const object if what you point to is a const object:

```<code>int const *p = NULL;
// doesn't work without a cast. Will at least provoke a warning
int *pn = p;

int *p = NULL;
// always works: pretending to point to something const doesn't harm.
int const *pc = p;
</code>```

Note that if you make the pointer itself const, the rules are different to that. They are analogous to const applied to other types:

```<code>int const i = 0;
int j = i; // works. we only read the value of i. its const doesn't matter.

int * const p = NULL;
int * q = p; // works: we only read the value of p (a null pointer).
</code>```

After copying the value into a new variable (whether pointer or not), the new variable is not connected in any way to the other variable, because the value read has no associativity to how the value was created in the first place. The const of the other variable doesn't matter.

OwnerDisplayName: Nazgulled

ContentLicense: CC BY-SA 2.5

Body:
I have a dictionary that goes like this:

typedef struct dictNode {
    int key;
    char *value;
    struct dictNode *next;
} Dict;

And a get() function that goes like this:

char *get(const Dict *dict, int key) {
    if(!dict) return NULL;

    Dict *currPtr = dict;

    while(currPtr) {
        if(currPtr->key == key) {
            return currPtr->value;
        }

        currPtr = currPtr->next;
    }
}

Compiling this code produces the following error:

dict.c:85: warning: initialization discards qualifiers from pointer target type

This warning refers to the line:

Dict *currPtr = dict;

If I add a "const" before that line like this:

const Dict *currPtr = dict;

The warning goes away...

1) First thing I don't understand is this: I added "const" to the dict argument in get() so that the compiler warns me if I try to change the address dict is pointing to, otherwise I won't be able to access the dictionary in the main program cause I lost the address I was pointing too. Now, I'm creating a new pointer, currPtr, that points to the same place as dict. This way, I use this pointer instead, to traverse the dictionary and keep dict pointer intact. Why do I also need to have const for currPtr?

2) Second thing I don't understand is this: The line currPtr = currPtr->next; is changing the currPtr pointer, so, why doesn't the compile warn me about that if I added a const to currPtr?

Then I have a del() function that goes like this:

Dict *del(const Dict *dict, int key) {
    if(!dict) return NULL;

    Dict *currPtr = dict;
    Dict *prevPtr = dict;

    while(currPtr) {
        if(currPtr->key == key) {
            prevPtr->next = currPtr->next;
            free(currPtr);
        }

        prevPtr = currPtr;
        currPtr = currPtr->next;
    }

    return dict;
}

Please note that I'm aware that this delete function code is not complete, it does not correctly work if I want to delete the first element for instance. It doesn't matter, I'll finish later, it suffices to demonstrate my problem...

3) So, in the get() function I needed to add const to currPtr but in this del() function, I don't need to add const to currPtr nor prevPtr? In both functions I am changing the currPtr pointer and in the case of the del() function I'm changing the prevPtr pointer too. Why does the get() function require me to add a const before currPtr and the del() function does not require me to add a const before currPtr and prevPtr?

I can basically resume this whole post to: When and where exactly in my get() and del() functions should I use const and why, and, when and where I shouldn't?

Body:
Without a pointer, you would have

const Dict currPtr

which is a constant Dict. Now, if you make it a pointer you have

const Dict *currPtr

which is a pointer to a constant Dict. That does not mean that the pointer is constant. But it does mean that the Dict pointed to is treated as constant

currPtr->key = 10; // error, dict is treated as constant.

But the pointer is not

currPtr = otherPtr; // possible: the pointer is not constant

You would get an error for the second case if you make the pointer constant. Keeping the pointed dict constant too, this would look like this

const Dict * const currPtr = init;

Now you can't set currPtr to point to something different, because the pointer is now constant, not just what the pointer points to is treated so. Some people like the look if the const is always right to the stuff that it makes const. This would look like this

Dict const * const currPtr = init;

which is the same as the previous snippet. If you then read it from right to left, it tells you what it is "const pointer to a const Dict". If you have a type, it doesn't matter how you order the specifiers

int const a = 10;
const int b = 10;

Both are constant integers. That is why we could put const right of the Dict type specifier.

Now, if you have a pointer, you can always pretend you point to a constant object, even though the object wasn't declared const. But you can't pretend to work with a non-const object if what you point to is a const object:

int const *p = NULL;
// doesn't work without a cast. Will at least provoke a warning
int *pn = p;

int *p = NULL;
// always works: pretending to point to something const doesn't harm.
int const *pc = p;

Note that if you make the pointer itself const, the rules are different to that. They are analogous to const applied to other types:

int const i = 0;
int j = i; // works. we only read the value of i. its const doesn't matter.

int * const p = NULL;
int * q = p; // works: we only read the value of p (a null pointer).

After copying the value into a new variable (whether pointer or not), the new variable is not connected in any way to the other variable, because the value read has no associativity to how the value was created in the first place. The const of the other variable doesn't matter.

OwnerDisplayName: litb

LastEditorDisplayName: litb


来源: stackexchange

问:
c++ heuristic for estimating function inlining benefits
In c++, what is a good heuristic for estimating the compute time benefits of inlining a function, particularly when the function is called very frequently and accounts for >= 10% of the program's execution time (eg. the evaluation function of a brute force or stochastic optimization process). Even though inlining may be ultimately beyond my control, I am still curious.</p>

答:
The behaviour here is somewhat compiler dependant.  With a recursive function obviously inlining behaviour can in theory be infinite.  The 'inline' keyword is only a hint to the compiler, it can choose it ignore if it can't do anything with it.  Some compilers will inline the recursive function to a certain depth.

As for the 'how much will this speed things up' - unfortunately we can't provide any sort of answer to that question as 'it depends' - how much work is the function doing vs the overhead of the function call mechanism itself.  Why don't you set up a test and see?

ContentLicense: CC BY-SA 3.0


问:
DeprecationWarning: Function when moving app (removed titlebar) - PySide6
I get when I move the App this Warning:

```<code>C:\Qt\Login_Test\main.py:48: DeprecationWarning: Function: 'globalPos() const' is marked as deprecated, please check the documentation for more information.
  self.dragPos = event.globalPos()
C:\Qt\Login_Test\main.py:43: DeprecationWarning: Function: 'globalPos() const' is marked as deprecated, please check the documentation for more information.
  self.move(self.pos() + event.globalPos() - self.dragPos)
C:\Qt\Login_Test\main.py:44: DeprecationWarning: Function: 'globalPos() const' is marked as deprecated, please check the documentation for more information.
  self.dragPos = event.globalPos()
</code>```

I used this code:

```<code>        self.remove_title()
        self.ui.appname_label.mouseMoveEvent = self.move_window

    def remove_title(self):
        self.setWindowFlag(QtCore.Qt.FramelessWindowHint)
        self.setAttribute(QtCore.Qt.WA_TranslucentBackground)

        self.shadow = QGraphicsDropShadowEffect(self)
        self.shadow.setBlurRadius(20)
        self.shadow.setXOffset(0)
        self.shadow.setYOffset(0)
        self.shadow.setColor(QColor(0, 0, 0, 250))

        self.ui.frame.setGraphicsEffect(self.shadow)

    def move_window(self, event):
        if event.buttons() == Qt.LeftButton:
            self.move(self.pos() + event.globalPos() - self.dragPos)
            self.dragPos = event.globalPos()
            event.accept()

    def mousePressEvent(self, event):
        self.dragPos = event.globalPos()
</code>```

Is there a way to skip this warning? It works but this warning is annoying.

答:
event.pos() is deprecated and it may be removed in future versions.

Try using event.scenePosition() to avoid shakiness.

```<code>def mousePressEvent(self, event):
    if event.button() == Qt.LeftButton:
        self.offset = QPoint(event.position().x(),event.position().y())
    else:
        super().mousePressEvent(event)

def mouseMoveEvent(self, event):
    if self.offset is not None and event.buttons() == Qt.LeftButton:

        self.move(self.pos() + QPoint(event.scenePosition().x(),event.scenePosition().y()) - self.offset)
    else:
        super().mouseMoveEvent(event)

def mouseReleaseEvent(self, event):
    self.offset = None
    super().mouseReleaseEvent(event)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I get when I move the App this Warning:

C:\Qt\Login_Test\main.py:48: DeprecationWarning: Function: 'globalPos() const' is marked as deprecated, please check the documentation for more information.
  self.dragPos = event.globalPos()
C:\Qt\Login_Test\main.py:43: DeprecationWarning: Function: 'globalPos() const' is marked as deprecated, please check the documentation for more information.
  self.move(self.pos() + event.globalPos() - self.dragPos)
C:\Qt\Login_Test\main.py:44: DeprecationWarning: Function: 'globalPos() const' is marked as deprecated, please check the documentation for more information.
  self.dragPos = event.globalPos()

I used this code:

        self.remove_title()
        self.ui.appname_label.mouseMoveEvent = self.move_window

    def remove_title(self):
        self.setWindowFlag(QtCore.Qt.FramelessWindowHint)
        self.setAttribute(QtCore.Qt.WA_TranslucentBackground)

        self.shadow = QGraphicsDropShadowEffect(self)
        self.shadow.setBlurRadius(20)
        self.shadow.setXOffset(0)
        self.shadow.setYOffset(0)
        self.shadow.setColor(QColor(0, 0, 0, 250))

        self.ui.frame.setGraphicsEffect(self.shadow)

    def move_window(self, event):
        if event.buttons() == Qt.LeftButton:
            self.move(self.pos() + event.globalPos() - self.dragPos)
            self.dragPos = event.globalPos()
            event.accept()

    def mousePressEvent(self, event):
        self.dragPos = event.globalPos()

Is there a way to skip this warning? It works but this warning is annoying.

Body:
event.pos() is deprecated and it may be removed in future versions.

Try using event.scenePosition() to avoid shakiness.

def mousePressEvent(self, event):
    if event.button() == Qt.LeftButton:
        self.offset = QPoint(event.position().x(),event.position().y())
    else:
        super().mousePressEvent(event)

def mouseMoveEvent(self, event):
    if self.offset is not None and event.buttons() == Qt.LeftButton:

        self.move(self.pos() + QPoint(event.scenePosition().x(),event.scenePosition().y()) - self.offset)
    else:
        super().mouseMoveEvent(event)

def mouseReleaseEvent(self, event):
    self.offset = None
    super().mouseReleaseEvent(event)


问:
parent element take margin of child element in html css?
strong text

i dont understand why my header go down when i give to his child (.navigation) margin-top?
if i give padding its okay my header stays on the top
but why not by giving margin

i did research that ovorflow: auto fix the problem (yes it is) but why? can someone explain please

/* RESET */

* {
 margin: 0;
 padding: 0;
 box-sizing: border-box;
}

/* VARIABLES */

:root {
    --pimery_color: #fff;
    --accent: #FBD784;
}

/* BODY */

body {
    font-family: 'Gilroy';
    font-weight: 700;
    font-style: normal;
    font-size: 18px;
    color: var(--pimery_color);
    background-color: #0B1D26;
}

/* HEADER */

.header {
    background-color: red;
}

.navigation {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top:100px;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header class="header">
      <div class="navigation">
        <p class="logo">MNTN</p>
        <nav class="nav">
          <ul>
            Equipment
          </ul>
          <ul>
            About us
          </ul>
          <ul>
            Blog
          </ul>
        </nav>
        <div class="account">
          <img src="./img/svg/acc.png" alt="account logo for login" />
          Account
        </div>
      </div>
    </header></code>```

答:
That's an instance of a more general problem known as margin collapsing.
If you have a parent element and a child element and you give the child element some margins, then these margins won't be contained by the parent element and they will go to the outside of the parent element.

There are ways to prevent this behaviour. One way to do that is adding some padding to the parent element: if you do that, the parent element padding will contain the child element margins on the inside.

Body:
strong text

i dont understand why my header go down when i give to his child (.navigation) margin-top?
if i give padding its okay my header stays on the top
but why not by giving margin

i did research that ovorflow: auto fix the problem (yes it is) but why? can someone explain please

/* RESET */

* {
 margin: 0;
 padding: 0;
 box-sizing: border-box;
}

/* VARIABLES */

:root {
    --pimery_color: #fff;
    --accent: #FBD784;
}

/* BODY */

body {
    font-family: 'Gilroy';
    font-weight: 700;
    font-style: normal;
    font-size: 18px;
    color: var(--pimery_color);
    background-color: #0B1D26;
}

/* HEADER */

.header {
    background-color: red;
}

.navigation {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top:100px;

}

MNTN

            Equipment

            About us

            Blog

          Account


问:
replica Set mongo docker-compose
I'm trying to configure a mongodb replicaSet using docker-compose, but when I stop the master container it seems that it doesn't pass to the secondary.

```<code>redis:
 image: redis
 ports:
  - "6379:6379"

mongo3:
 hostname: mongo3
 image: mongo
 entrypoint: [ "/usr/bin/mongod", "--replSet", "rs", "--journal","--dbpath","/data/db","--smallfiles", "--rest" ]
 volumes:
  - ./data/mongo3:/data/db
 ports:
  - "27018:27017"
  - "28018:28017"
 restart: always

mongo2:
 hostname: mongo2
 image: mongo
 entrypoint: [ "/usr/bin/mongod", "--replSet", "rs", "--journal","--dbpath","/data/db","--smallfiles", "--rest" ]
 volumes:
  - ./data/mongo2:/data/db
 ports:
  - "27019:27017"
  - "28019:28017"
 restart: always

mongo1:
 hostname: mongo1
 image: mongo
 entrypoint: [ "/usr/bin/mongod", "--replSet", "rs", "--journal","--dbpath","/data/db","--smallfiles", "--rest" ]
 volumes:
  - ./data/mongo1:/data/db
ports:
  - "27017:27017"
  - "28017:28017"
links:
 - mongo2:mongo2
 - mongo3:mongo3
restart: always

web:
 build: .
 ports:
  - "2000:2000"
 volumes:
  - .:/vip
 links:
  - redis
  - mongo1
  - mongo2
  - mongo3

nginx:
 restart: always
 build: ./nginx/
 ports:
  - "80:80"
 links:
  - web:web

mongosetup:
 image: mongo
 links:
  - mongo1:mongo1
  - mongo2:mongo2
  - mongo3:mongo3
 volumes:
  - ./scripts:/scripts
 entrypoint: [ "/scripts/setup.sh" ]
</code>```

setup.sh :

```<code>#!/bin/bash

MONGODB1=`ping -c 1 mongo1 | head -1  | cut -d "(" -f 2 | cut -d ")" -f 1`
MONGODB2=`ping -c 1 mongo2 | head -1  | cut -d "(" -f 2 | cut -d ")" -f 1`
MONGODB3=`ping -c 1 mongo3 | head -1  | cut -d "(" -f 2 | cut -d ")" -f 1`

echo "**********************************************" ${MONGODB1}
echo "Waiting for startup.."
until curl http://${MONGODB1}:28017/serverStatus\?text\=1 2>&1 | grep uptime | head -1; do
  printf '.'
  sleep 1
done

echo curl http://${MONGODB1}:28017/serverStatus\?text\=1 2>&1 | grep uptime | head -1
echo "Started.."

echo SETUP.sh time now: `date +"%T" `
mongo --host ${MONGODB1}:27017 <<EOF
var cfg = {
    "_id": "rs",
    "version": 1,
    "members": [
        {
            "_id": 0,
            "host": "${MONGODB1}:27017",
            "priority": 2
        },
        {
            "_id": 1,
            "host": "${MONGODB2}:27017",
            "priority": 0
        },
        {
            "_id": 2,
            "host": "${MONGODB3}:27017",
            "priority": 0
        }
    ],settings: {chainingAllowed: true}
};
rs.initiate(cfg, { force: true });
rs.reconfig(cfg, { force: true });
rs.slaveOk();
db.getMongo().setReadPref('nearest');
db.getMongo().setSlaveOk();
EOF
</code>```

答:
This setup works for me. I have also setup everything in https://github.com/nguyenduyhust/docker-mongodb-replica-set.

Great if that's what you're looking for.

Dockerfile

```<code>FROM mongo
RUN mkdir /config
WORKDIR /config
COPY wait-for-it.sh .
COPY mongo-setup.js .
COPY mongo-setup.sh .
RUN chmod +x /config/wait-for-it.sh
RUN chmod +x /config/mongo-setup.sh
CMD [ "bash", "-c", "/config/wait-for-it.sh mongodb1:27011 -- /config/mongo-setup.sh"]
</code>```

docker-compose.yml

```<code>version: "3"

services:
  mongodb1:
    container_name: mongo1
    image: mongo
    restart: always
    volumes:
      - ./volumes/mongodb1:/data/db
    ports:
      - "27011:27011"
    expose:
      - "27011"
    entrypoint:
      [
        "/usr/bin/mongod",
        "--port", "27011",
        "--replSet", "rs0",
        "--bind_ip_all",
      ]

  mongodb2:
    container_name: mongo2
    image: mongo
    restart: always
    volumes:
      - ./volumes/mongodb2:/data/db
    ports:
      - "27012:27012"
    expose:
      - "27012"
    entrypoint:
      [
        "/usr/bin/mongod",
        "--port", "27012",
        "--replSet", "rs0",
        "--bind_ip_all",
      ]

  mongodb3:
    container_name: mongo3
    image: mongo
    restart: always
    volumes:
      - ./volumes/mongodb3:/data/db
    ports:
      - "27013:27013"
    expose:
      - "27013"
    entrypoint:
      [
        "/usr/bin/mongod",
        "--port", "27013",
        "--replSet", "rs0",
        "--bind_ip_all",
      ]

  mongosetup:
    container_name: mongosetup
    image: "mongo-setup"
    build: "./mongo-setup"
    depends_on:
      - mongodb1

  mongo-express:
    container_name: mongo-express
    image: mongo-express
    environment:
      ME_CONFIG_MONGODB_URL: mongodb://mongodb1:27011,mongodb2:27012,mongodb3:27013/?replicaSet=rs0
    ports:
      - 8081:8081
    restart: always
    depends_on:
      - mongodb1
      - mongosetup
</code>```

mongo-setup.js

```<code>rsconf = {
  _id : "rs0",
  members: [
      {
          "_id": 0,
          "host": "mongodb1:27011",
          "priority": 3
      },
      {
          "_id": 1,
          "host": "mongodb2:27012",
          "priority": 2
      },
      {
          "_id": 2,
          "host": "mongodb3:27013",
          "priority": 1
      }
  ]
}

rs.initiate(rsconf);
</code>```

mongo-setup.sh

```<code>#!/usr/bin/env bash

if [ ! -f /data/mongo-init.flag ]; then
    echo "Init replicaset"
    mongo mongodb://mongodb1:27011 mongo-setup.js
    touch /data/mongo-init.flag
else
    echo "Replicaset already initialized"
fi
</code>```

Title: replica Set mongo docker-compose

Body:
I'm trying to configure a mongodb replicaSet using docker-compose, but when I stop the master container it seems that it doesn't pass to the secondary.

redis:
 image: redis
 ports:
  - "6379:6379"

mongo3:
 hostname: mongo3
 image: mongo
 entrypoint: [ "/usr/bin/mongod", "--replSet", "rs", "--journal","--dbpath","/data/db","--smallfiles", "--rest" ]
 volumes:
  - ./data/mongo3:/data/db
 ports:
  - "27018:27017"
  - "28018:28017"
 restart: always

mongo2:
 hostname: mongo2
 image: mongo
 entrypoint: [ "/usr/bin/mongod", "--replSet", "rs", "--journal","--dbpath","/data/db","--smallfiles", "--rest" ]
 volumes:
  - ./data/mongo2:/data/db
 ports:
  - "27019:27017"
  - "28019:28017"
 restart: always

mongo1:
 hostname: mongo1
 image: mongo
 entrypoint: [ "/usr/bin/mongod", "--replSet", "rs", "--journal","--dbpath","/data/db","--smallfiles", "--rest" ]
 volumes:
  - ./data/mongo1:/data/db
ports:
  - "27017:27017"
  - "28017:28017"
links:
 - mongo2:mongo2
 - mongo3:mongo3
restart: always

web:
 build: .
 ports:
  - "2000:2000"
 volumes:
  - .:/vip
 links:
  - redis
  - mongo1
  - mongo2
  - mongo3

nginx:
 restart: always
 build: ./nginx/
 ports:
  - "80:80"
 links:
  - web:web

mongosetup:
 image: mongo
 links:
  - mongo1:mongo1
  - mongo2:mongo2
  - mongo3:mongo3
 volumes:
  - ./scripts:/scripts
 entrypoint: [ "/scripts/setup.sh" ]

setup.sh :

#!/bin/bash

MONGODB1=`ping -c 1 mongo1 | head -1  | cut -d "(" -f 2 | cut -d ")" -f 1`
MONGODB2=`ping -c 1 mongo2 | head -1  | cut -d "(" -f 2 | cut -d ")" -f 1`
MONGODB3=`ping -c 1 mongo3 | head -1  | cut -d "(" -f 2 | cut -d ")" -f 1`

echo "**********************************************" ${MONGODB1}
echo "Waiting for startup.."
until curl http://${MONGODB1}:28017/serverStatus\?text\=1 2>&1 | grep uptime | head -1; do
  printf '.'
  sleep 1
done

echo curl http://${MONGODB1}:28017/serverStatus\?text\=1 2>&1 | grep uptime | head -1
echo "Started.."

echo SETUP.sh time now: `date +"%T" `
mongo --host ${MONGODB1}:27017 <<EOF
var cfg = {
    "_id": "rs",
    "version": 1,
    "members": [
        {
            "_id": 0,
            "host": "${MONGODB1}:27017",
            "priority": 2
        },
        {
            "_id": 1,
            "host": "${MONGODB2}:27017",
            "priority": 0
        },
        {
            "_id": 2,
            "host": "${MONGODB3}:27017",
            "priority": 0
        }
    ],settings: {chainingAllowed: true}
};
rs.initiate(cfg, { force: true });
rs.reconfig(cfg, { force: true });
rs.slaveOk();
db.getMongo().setReadPref('nearest');
db.getMongo().setSlaveOk();
EOF

Body:
This setup works for me. I have also setup everything in https://github.com/nguyenduyhust/docker-mongodb-replica-set.

Great if that's what you're looking for.

Dockerfile

FROM mongo
RUN mkdir /config
WORKDIR /config
COPY wait-for-it.sh .
COPY mongo-setup.js .
COPY mongo-setup.sh .
RUN chmod +x /config/wait-for-it.sh
RUN chmod +x /config/mongo-setup.sh
CMD [ "bash", "-c", "/config/wait-for-it.sh mongodb1:27011 -- /config/mongo-setup.sh"]

docker-compose.yml

version: "3"

services:
  mongodb1:
    container_name: mongo1
    image: mongo
    restart: always
    volumes:
      - ./volumes/mongodb1:/data/db
    ports:
      - "27011:27011"
    expose:
      - "27011"
    entrypoint:
      [
        "/usr/bin/mongod",
        "--port", "27011",
        "--replSet", "rs0",
        "--bind_ip_all",
      ]

  mongodb2:
    container_name: mongo2
    image: mongo
    restart: always
    volumes:
      - ./volumes/mongodb2:/data/db
    ports:
      - "27012:27012"
    expose:
      - "27012"
    entrypoint:
      [
        "/usr/bin/mongod",
        "--port", "27012",
        "--replSet", "rs0",
        "--bind_ip_all",
      ]

  mongodb3:
    container_name: mongo3
    image: mongo
    restart: always
    volumes:
      - ./volumes/mongodb3:/data/db
    ports:
      - "27013:27013"
    expose:
      - "27013"
    entrypoint:
      [
        "/usr/bin/mongod",
        "--port", "27013",
        "--replSet", "rs0",
        "--bind_ip_all",
      ]

  mongosetup:
    container_name: mongosetup
    image: "mongo-setup"
    build: "./mongo-setup"
    depends_on:
      - mongodb1

  mongo-express:
    container_name: mongo-express
    image: mongo-express
    environment:
      ME_CONFIG_MONGODB_URL: mongodb://mongodb1:27011,mongodb2:27012,mongodb3:27013/?replicaSet=rs0
    ports:
      - 8081:8081
    restart: always
    depends_on:
      - mongodb1
      - mongosetup

mongo-setup.js

rsconf = {
  _id : "rs0",
  members: [
      {
          "_id": 0,
          "host": "mongodb1:27011",
          "priority": 3
      },
      {
          "_id": 1,
          "host": "mongodb2:27012",
          "priority": 2
      },
      {
          "_id": 2,
          "host": "mongodb3:27013",
          "priority": 1
      }
  ]
}

rs.initiate(rsconf);

mongo-setup.sh

#!/usr/bin/env bash

if [ ! -f /data/mongo-init.flag ]; then
    echo "Init replicaset"
    mongo mongodb://mongodb1:27011 mongo-setup.js
    touch /data/mongo-init.flag
else
    echo "Replicaset already initialized"
fi


问:
Getting attribute's value in Nokogiri to extract link URLs
I have a document which look like this:

```<code><div id="block">
    <a href="http://google.com">link</a>
</div>
</code>```

I can't get Nokogiri to get me the value of href attribute. I'd like to store the address in a Ruby variable as a string.

答:
```<code>doc = Nokogiri::HTML("HTML ...")
href = doc.css("div[id='block'] > a")
result = href['href'] #http://google.com
</code>```

Body:
I have a document which look like this:

    link

I can't get Nokogiri to get me the value of href attribute. I'd like to store the address in a Ruby variable as a string.


问:
How to find model records having some or no associated model records in rails?
I am creating an Employee Management System app using Rails 7. Here I have one Employee model, one Document model having a list of all documents and these two are associated through the EmployeeDocuments model which has Employee ID and Document ID. Now I want to use an action mailer to send a list of employees with documents they have not submitted. The problem is I cannot get the Employee list with some or no documents submitted in a single query.
I can get Employees with no submitted documents like this:

```<code>Employee.includes(:documents).where(documents: {id: nil})
</code>```

and Employees with some or all documents submitted by:

```<code>Employee.includes(:documents).where.not(documents: {id: nil})
</code>```

I want the list so that I can iterate through their missing documents by:

```<code>Document.where.not(id: employee.documents.pluck(:id))
</code>```

and send the list.
Currently, my mailer looks like this:

```<code>class DocsNotifierMailer < ApplicationMailer
  default from: 'user@email.com'

  def notification_email
    @employees = Employee.all
    mail(to: 'recipient@email.com',
      subject: 'Reminder for missing documents')
  end
end
</code>```

So I can get the list of all employees in my HTML template and there I am using an If statement like this:

```<code><% if employee.documents.length < Document.all.count %>
</code>```

to filter out the employees with all documents.
But I want to filter them in the mailer itself.
Since I am a beginner, can not find a way out of this. Please help.

答:
I think the following might work for you:</p>
```<code>Employee
  .left_outer_joins(:documents)
  .group('employees.id')
  .having("COUNT(documents.id) < #{Document.count}")

</code>```

Body:
I am creating an Employee Management System app using Rails 7. Here I have one Employee model, one Document model having a list of all documents and these two are associated through the EmployeeDocuments model which has Employee ID and Document ID. Now I want to use an action mailer to send a list of employees with documents they have not submitted. The problem is I cannot get the Employee list with some or no documents submitted in a single query.
I can get Employees with no submitted documents like this:

Employee.includes(:documents).where(documents: {id: nil})

and Employees with some or all documents submitted by:

Employee.includes(:documents).where.not(documents: {id: nil})

I want the list so that I can iterate through their missing documents by:

Document.where.not(id: employee.documents.pluck(:id))

and send the list.
Currently, my mailer looks like this:

class DocsNotifierMailer < ApplicationMailer
  default from: 'user@email.com'

  def notification_email
    @employees = Employee.all
    mail(to: 'recipient@email.com',
      subject: 'Reminder for missing documents')
  end
end

So I can get the list of all employees in my HTML template and there I am using an If statement like this:

<% if employee.documents.length < Document.all.count %>

to filter out the employees with all documents.
But I want to filter them in the mailer itself.
Since I am a beginner, can not find a way out of this. Please help.

Body:
I think the following might work for you:

Employee
  .left_outer_joins(:documents)
  .group('employees.id')
  .having("COUNT(documents.id) < #{Document.count}")


问:
convert float to datetime when month is decimal place (YYYY.MM float)
This is my data:

```<code>d = pd.DataFrame({'date': [2021.01, 2021.02, 2021.03, 2021.04],
                   'value': [2, 3, 4, 1]})

d
</code>```

I want to convert the date column to date. It is currently float with months in decimal place (YYYY.mm)

This does not work:

```<code>pd.to_datetime(d['date'], format='%Y.%m', errors='coerce').dt.to_period('m')
</code>```

答:
You can multiply by 100 and use an integer as input for to_datetime:

pd.to_datetime(d['date'].mul(100).astype(int), format='%Y%m').dt.to_period('m')
```
<p><em>NB. it seems to work even without conversion to integer, but I would still do it, or use <code>round</code> to avoid floating point ambiguity (depending on the wanted output)</em></p>
<p>output:</p>
```0    2021-01
1    2021-02
2    2021-03
3    2021-04
Name: date, dtype: period[M]
```

Body:
This is my data:

d = pd.DataFrame({'date': [2021.01, 2021.02, 2021.03, 2021.04],
                   'value': [2, 3, 4, 1]})

d

I want to convert the date column to date. It is currently float with months in decimal place (YYYY.mm)

This does not work:

pd.to_datetime(d['date'], format='%Y.%m', errors='coerce').dt.to_period('m')

Body:
You can multiply by 100 and use an integer as input for to_datetime:

pd.to_datetime(d['date'].mul(100).astype(int), format='%Y%m').dt.to_period('m')

NB. it seems to work even without conversion to integer, but I would still do it, or use round to avoid floating point ambiguity (depending on the wanted output)

output:

0    2021-01
1    2021-02
2    2021-03
3    2021-04
Name: date, dtype: period[M]


问:
Python code to execute a SQL script and create a CSV file with a customised name
I have stored a list of snowflake SQL queries in an excel. Attached a sample format but the original excel has more than 50 rows.

I have written a python code to read and execute these queries but the output is not as i was expecting. The intention here is to read the excel and execute the query from the 'query' column and save the query result in an CSV with the file name mentioned in the 'Scenario' column from the excel.

The python code i have written executes and creates different files in the output path but all the CSV file is having the result of last query, i.e  the customer_count.csv file also has the same data of customer_attribute.csv

If my excel has 50 different scenarios, it creates 50 different CSV files but the data inside all these files are the result of the 50th Query

Below is my code and i'm not sure where its going wrong. Could someone help me out here please

```<code>  from EXCEL_CONNECTION import *
  from SNOWFLAKE_CONNECTION import *
  import pandas
  import openpyxl

  wb = openpyxl.load_workbook("QUERY.xlsx")
  ws = wb.get_sheet_by_name('Sheet1')

  cur = ctx.cursor()

  for col in ws.iter_rows(min_row=2, min_col=2, max_col=2):
      for cell2 in col:
          df1 = (cell2.value)
      for row in ws.iter_rows(min_row=2, min_col=3, max_col=3):
          for cell in row:
              cur.execute(cell.value)
              df = cur.fetch_pandas_all()
      df.to_csv(r"target path" + df1 + r".csv")
</code>```

答:
I cannot spot the problem by eye. So I would do the next best thing... add some debugging and see what is actually happening:

```<code>  for col in ws.iter_rows(min_row=2, min_col=2, max_col=2):
      print('col', col)
      for cell2 in col:
          print('cell2', cell2.value)
          df1 = (cell2.value)
      for row in ws.iter_rows(min_row=2, min_col=3, max_col=3):
          print('row', row)
          for cell in row:
              print('cell', cell.value)
              cur.execute(cell.value)
              df = cur.fetch_pandas_all()
      print('to_csv', r"target path" + df1 + r".csv")
      df.to_csv(r"target path" + df1 + r".csv")
</code>```

I am puzzled why you are put the name of the file into a tuple (cell2.value) instead of using it directly. The SQL cell is used directly?

But you will ether see you N execute's with different files names, and then it will be a "are the results actually different" OR you we see that while you are loop X you are not step over Y, or you are doing every X for each Y (which sounds like the output you are getting).

And when you know exactly what is happening, you can ask a more targeted question. simplified repo like:

```<code>from EXCEL_CONNECTION import *
from SNOWFLAKE_CONNECTION import *

cur = ctx.cursor()
cur.execute('select count(*) from customer')
df = cur.fetch_pandas_all()
df.to_csv(r"target path\customer_count.csv")

cur.execute('select * from customer')
df = cur.fetch_pandas_all()
df.to_csv(r"target path\customer_attribute.csv")
</code>```

Body:
I have stored a list of snowflake SQL queries in an excel. Attached a sample format but the original excel has more than 50 rows.

I have written a python code to read and execute these queries but the output is not as i was expecting. The intention here is to read the excel and execute the query from the 'query' column and save the query result in an CSV with the file name mentioned in the 'Scenario' column from the excel.

The python code i have written executes and creates different files in the output path but all the CSV file is having the result of last query, i.e  the customer_count.csv file also has the same data of customer_attribute.csv

If my excel has 50 different scenarios, it creates 50 different CSV files but the data inside all these files are the result of the 50th Query

Below is my code and i'm not sure where its going wrong. Could someone help me out here please

  from EXCEL_CONNECTION import *
  from SNOWFLAKE_CONNECTION import *
  import pandas
  import openpyxl

  wb = openpyxl.load_workbook("QUERY.xlsx")
  ws = wb.get_sheet_by_name('Sheet1')

  cur = ctx.cursor()

  for col in ws.iter_rows(min_row=2, min_col=2, max_col=2):
      for cell2 in col:
          df1 = (cell2.value)
      for row in ws.iter_rows(min_row=2, min_col=3, max_col=3):
          for cell in row:
              cur.execute(cell.value)
              df = cur.fetch_pandas_all()
      df.to_csv(r"target path" + df1 + r".csv")

Body:
I cannot spot the problem by eye. So I would do the next best thing... add some debugging and see what is actually happening:

  for col in ws.iter_rows(min_row=2, min_col=2, max_col=2):
      print('col', col)
      for cell2 in col:
          print('cell2', cell2.value)
          df1 = (cell2.value)
      for row in ws.iter_rows(min_row=2, min_col=3, max_col=3):
          print('row', row)
          for cell in row:
              print('cell', cell.value)
              cur.execute(cell.value)
              df = cur.fetch_pandas_all()
      print('to_csv', r"target path" + df1 + r".csv")
      df.to_csv(r"target path" + df1 + r".csv")

I am puzzled why you are put the name of the file into a tuple (cell2.value) instead of using it directly. The SQL cell is used directly?

But you will ether see you N execute's with different files names, and then it will be a "are the results actually different" OR you we see that while you are loop X you are not step over Y, or you are doing every X for each Y (which sounds like the output you are getting).

And when you know exactly what is happening, you can ask a more targeted question. simplified repo like:

from EXCEL_CONNECTION import *
from SNOWFLAKE_CONNECTION import *

cur = ctx.cursor()
cur.execute('select count(*) from customer')
df = cur.fetch_pandas_all()
df.to_csv(r"target path\customer_count.csv")

cur.execute('select * from customer')
df = cur.fetch_pandas_all()
df.to_csv(r"target path\customer_attribute.csv")


问:
How to end a function that hangs sometimes?
I have written a function f like this:

```<code>void f()
{
   f1();   // Pre-Work
   f2();   // the actual work
   f3();   // Post-Work
}
</code>```

f1 and f3 are my own functions, but f2 comes from a library I have no control of. f is called periodically from some controller.

All works fine, but once a week f2 hangs, and does not return for unknown reasons. What is the design pattern to handle this? Probably, f should be run in an extra Task, or can I use async/await pattern? What is with memory that might be allocated in f2?

答:
if f2 actually hangs and never returns, there are a few things that can be done.

Start by ensuring that the method is used correctly, i.e. that any parameters are always correct, and there is no synchronization issue going on, i.e. ensure the library is used in a thread safe way.

If that does not help, contact the authors of the library. It might help if you can reproduce the issue, so writing a minimal reproducible example might help. Callstacks, memory dumps and other supporting information might also help. If the library is open source you might have the option of fixing the issue yourself.

If nothing else works, move the call to a separate process. This will let you close the process without cooperation from the function. There is some more details in What's wrong with using Thread.Abort(). This will add some complexity, but there libraries that can make this easier. A message queue like NetMq would probably work, you might also consider something like gRPC, there are ton of options to chose from.

Body:
I have written a function f like this:

void f()
{
   f1();   // Pre-Work
   f2();   // the actual work
   f3();   // Post-Work
}

f1 and f3 are my own functions, but f2 comes from a library I have no control of. f is called periodically from some controller.

All works fine, but once a week f2 hangs, and does not return for unknown reasons. What is the design pattern to handle this? Probably, f should be run in an extra Task, or can I use async/await pattern? What is with memory that might be allocated in f2?


问:
Spring Config Server - No such label: master
I have a simple Spring Cloud Config Server which consume configuration from git server.

ConfigServer bootstrap.yml :

```<code>spring:
  application:
    name: config-service
  cloud:
    config:
      server:
        git:
          uri: ssh://git@mydomain:myport/myrepo.git
          searchPaths: "configurations/{application}/{profile}"
server:
  port: 8888
</code>```

When I deploy ConfigServer on local, I can retrieve configuration from http://localhost:8888/myapp/test. But when I deploy ConfigServer on test server, it throws No such label: master when I hit http://testserverip:8888/myapp/test.

Any help would be most appreciated!

答:
This is what I found when I too had a similar issue.

Issue/Mistake#1 >> I created the properties file using notepad(I am on Windows OS).
The file was created with .txt extension. Hence the cloud config was not picking up the changes.
Fix: changed the extension from .txt to .properties

Issue/Mistake#2 >> The .properties file name was different from what is mentioned.
The file should be named:

servicename.properties

```<code>  matching the servicename defined in the *application.properties* as below:
</code>```

spring.application.name=<<servicename>>

In my example:

```<code> spring.application.name=limits-service
</code>```

Hence the file should be named **limits-service.properties**,
but I created with the name limits-service-service.properties

```<code>enter code here
</code>```

Fix: renamed the file to: limits-service.properties

Now I am able to see the configurations from the spring-cloud-config and it is picking the values from the configured GIT repository.

Body:
I have a simple Spring Cloud Config Server which consume configuration from git server.

ConfigServer bootstrap.yml :

spring:
  application:
    name: config-service
  cloud:
    config:
      server:
        git:
          uri: ssh://git@mydomain:myport/myrepo.git
          searchPaths: "configurations/{application}/{profile}"
server:
  port: 8888

When I deploy ConfigServer on local, I can retrieve configuration from http://localhost:8888/myapp/test. But when I deploy ConfigServer on test server, it throws No such label: master when I hit http://testserverip:8888/myapp/test.

Any help would be most appreciated!

Body:
This is what I found when I too had a similar issue.

Issue/Mistake#1 >> I created the properties file using notepad(I am on Windows OS).
The file was created with .txt extension. Hence the cloud config was not picking up the changes.
Fix: changed the extension from .txt to .properties

Issue/Mistake#2 >> The .properties file name was different from what is mentioned.
The file should be named:

servicename.properties

  matching the servicename defined in the *application.properties* as below:

spring.application.name=<<servicename>>

In my example:

 spring.application.name=limits-service

Hence the file should be named **limits-service.properties**,
but I created with the name limits-service-service.properties

enter code here

Fix: renamed the file to: limits-service.properties

Now I am able to see the configurations from the spring-cloud-config and it is picking the values from the configured GIT repository.


问:
Redis Graph Bulk Loader Issue
I have created redis cloud subscription and followed the instructions as mentioned in this document https://github.com/RedisGraph/redisgraph-bulk-loader. I am seeing error when I followed the instructions. I have also tried to use example2 csv but received the same error. Error : "Python int too large to convert to C long"

```<code>redisgraph-bulk-insert GRAPH_DEMO -n example/Person.csv -n example/Country.csv -r example/KNOWS.csv -r example/VISITED.csv
-h ***** -p ***** -a ********
</code>```

答: I also received this message while trying to insert csv data (all data was quoted to be imported as string) into a graph. So what I did was to simply comment this line csv.field_size_limit(sys.maxsize) in entity_file.py. It worked in my case, but I don’t think this would be safe for every use case.

Title: Redis Graph Bulk Loader Issue

Body:
I have created redis cloud subscription and followed the instructions as mentioned in this document https://github.com/RedisGraph/redisgraph-bulk-loader. I am seeing error when I followed the instructions. I have also tried to use example2 csv but received the same error. Error : "Python int too large to convert to C long"

redisgraph-bulk-insert GRAPH_DEMO -n example/Person.csv -n example/Country.csv -r example/KNOWS.csv -r example/VISITED.csv
-h ***** -p ***** -a ********


问:
Terraform Include parent uri with dynamic parameter in child uri for AWS API Gateway
I want to create a endpoint like user/<user_id>/info through aws_api_gateway using terraform

I am able to create endpoint till /user/<user_id>

But how to include <user_id> in the resource for "info"

Here is the code for "info" part:

```<code>resource "aws_api_gateway_resource" "info" {
  rest_api_id = aws_api_gateway_rest_api.app.id
  parent_id   = aws_api_gateway_resource.user.id
  path_part   = "info"
}

resource "aws_api_gateway_method" "info" {
  rest_api_id   = aws_api_gateway_rest_api.app.id
  resource_id   = aws_api_gateway_resource.info.id
  http_method   = "GET"
  authorization = "NONE"
}

resource "aws_api_gateway_integration" "info" {
  rest_api_id          = aws_api_gateway_rest_api.app.id
  resource_id          = aws_api_gateway_resource.info.id
  http_method          = aws_api_gateway_method.info.http_method
  type                 = "HTTP_PROXY"
  uri                  = "http://root_api/user/<user_id>/info"

</code>```

When I try this, the url for info resolves to http://root_api/user/<user_id>/info.
Any help on how to inject <user_id> in this url ??

Thanks

答:
Terraform interpolates variables in strings: documentation.

In your case:

```<code>uri = "http://root_api/user/${aws_api_gateway_resource.user.id}/info"
</code>```

Body:
I want to create a endpoint like user/<user_id>/info through aws_api_gateway using terraform

I am able to create endpoint till /user/<user_id>

But how to include <user_id> in the resource for "info"

Here is the code for "info" part:

resource "aws_api_gateway_resource" "info" {
  rest_api_id = aws_api_gateway_rest_api.app.id
  parent_id   = aws_api_gateway_resource.user.id
  path_part   = "info"
}

resource "aws_api_gateway_method" "info" {
  rest_api_id   = aws_api_gateway_rest_api.app.id
  resource_id   = aws_api_gateway_resource.info.id
  http_method   = "GET"
  authorization = "NONE"
}

resource "aws_api_gateway_integration" "info" {
  rest_api_id          = aws_api_gateway_rest_api.app.id
  resource_id          = aws_api_gateway_resource.info.id
  http_method          = aws_api_gateway_method.info.http_method
  type                 = "HTTP_PROXY"
  uri                  = "http://root_api/user/<user_id>/info"

When I try this, the url for info resolves to http://root_api/user/<user_id>/info.
Any help on how to inject <user_id> in this url ??

Thanks

Body:
Terraform interpolates variables in strings: documentation.

In your case:

uri = "http://root_api/user/${aws_api_gateway_resource.user.id}/info"


问:
Read from a string until specific char in Android
How can I read numbers from a string until I find a specific char, in my case - a dot.

For example I have a

```<code>String date = "18.8.2011"
int mDay = 0;
int mMonth = 0;
int mYear = 0;
</code>```

And I want to make mDay = 18, mMonth = 8 and mYear = 2011 - I want to be able to copy the digits until I find a dot.

答:
Use split method of String class.

```<code>String []ar=date.split("[.]");
int mDay=Integer.parseInt(ar[0]);
..
</code>```

Body:
How can I read numbers from a string until I find a specific char, in my case - a dot.

For example I have a

String date = "18.8.2011"
int mDay = 0;
int mMonth = 0;
int mYear = 0;

And I want to make mDay = 18, mMonth = 8 and mYear = 2011 - I want to be able to copy the digits until I find a dot.

Body:
Use split method of String class.

String []ar=date.split("[.]");
int mDay=Integer.parseInt(ar[0]);
..


问:
The problem occurs after the flutter sdk is updated. How can I fix it?
```<code>Launching lib/main.dart on Android SDK built for arm64 in debug mode...
e: /Users/madol.eeee/.gradle/caches/transforms-3/0fbf638dbdf70ad1725fe71b315a2ef4/transformed/jetified-window-1.0.0-beta04-api.jar!/META-INF/window_release.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: /Users/madol.eeee/.gradle/caches/transforms-3/2066b23b9b64ad3895a698a6d1fc8c5f/transformed/jetified-kotlin-stdlib-jdk7-1.5.30.jar!/META-INF/kotlin-stdlib-jdk7.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: /Users/madol.eeee/.gradle/caches/transforms-3/2a1bbf32034612557ecc12fcd06b65de/transformed/jetified-kotlin-stdlib-common-1.5.31.jar!/META-INF/kotlin-stdlib-common.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: /Users/madol.eeee/.gradle/caches/transforms-3/38348b600f1be8b91fdb7c7730bf1eb5/transformed/jetified-kotlin-stdlib-jdk8-1.5.30.jar!/META-INF/kotlin-stdlib-jdk8.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: /Users/madol.eeee/.gradle/caches/transforms-3/5a29260d2a646236c4d0b2d60a4d47d8/transformed/jetified-kotlinx-coroutines-android-1.5.2.jar!/META-INF/kotlinx-coroutines-android.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: /Users/madol.eeee/.gradle/caches/transforms-3/74bfffd4e61971b016e3f927bbbd7521/transformed/jetified-kotlin-stdlib-1.5.31.jar!/META-INF/kotlin-stdlib.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: /Users/madol.eeee/.gradle/caches/transforms-3/7cde7f72a0842ac95e9281eb78688076/transformed/jetified-window-java-1.0.0-beta04-api.jar!/META-INF/window-java_release.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: /Users/madol.eeee/.gradle/caches/transforms-3/e84741d2b04d8859553c8e0a19bf4026/transformed/jetified-kotlinx-coroutines-core-jvm-1.5.2.jar!/META-INF/kotlinx-coroutines-core.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:compileDebugKotlin'.
> Compilation error. See log for more details

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 8s
┌─ Flutter Fix ────────────────────────────────────────────────────────────────────────────────┐
│ [!] Your project requires a newer version of the Kotlin Gradle plugin.                       │
│ Find the latest version on https://kotlinlang.org/docs/gradle.html#plugin-and-versions, then │
│ update /Users/madol.eeee/project/traveling/flutter_traveling/android/build.gradle:           │
│ ext.kotlin_version = '<latest-version>'                                                      │
└──────────────────────────────────────────────────────────────────────────────────────────────┘
Exception: Gradle task assembleDebug failed with exit code 1
Exited (sigterm)
</code>```

i updated flutter sdk version 2.8.1 to 2.10.1 and get error after updated

i don't know why this hapening,  how can i fix that?

sorry and thank you

答:
first of all i solved this problem with FrancescoPenasa's help thanks!!

the solution is follows,

build.gradle file add follows

```<code>buildscript {
    ext.kotlin_version = '1.6.10'
    repositories {
        google()
        mavenCentral()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:4.1.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}
</code>```

after add code get another errer like this

```<code>Flutter multidex handling is disabled. If you wish to let the tool configure multidex, use the --mutidex flag.
</code>```

app/build.gradle file add code

```<code>dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.android.support:multidex:1.0.3'
}
</code>```

Body:
Launching lib/main.dart on Android SDK built for arm64 in debug mode...
e: /Users/madol.eeee/.gradle/caches/transforms-3/0fbf638dbdf70ad1725fe71b315a2ef4/transformed/jetified-window-1.0.0-beta04-api.jar!/META-INF/window_release.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: /Users/madol.eeee/.gradle/caches/transforms-3/2066b23b9b64ad3895a698a6d1fc8c5f/transformed/jetified-kotlin-stdlib-jdk7-1.5.30.jar!/META-INF/kotlin-stdlib-jdk7.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: /Users/madol.eeee/.gradle/caches/transforms-3/2a1bbf32034612557ecc12fcd06b65de/transformed/jetified-kotlin-stdlib-common-1.5.31.jar!/META-INF/kotlin-stdlib-common.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: /Users/madol.eeee/.gradle/caches/transforms-3/38348b600f1be8b91fdb7c7730bf1eb5/transformed/jetified-kotlin-stdlib-jdk8-1.5.30.jar!/META-INF/kotlin-stdlib-jdk8.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: /Users/madol.eeee/.gradle/caches/transforms-3/5a29260d2a646236c4d0b2d60a4d47d8/transformed/jetified-kotlinx-coroutines-android-1.5.2.jar!/META-INF/kotlinx-coroutines-android.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: /Users/madol.eeee/.gradle/caches/transforms-3/74bfffd4e61971b016e3f927bbbd7521/transformed/jetified-kotlin-stdlib-1.5.31.jar!/META-INF/kotlin-stdlib.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: /Users/madol.eeee/.gradle/caches/transforms-3/7cde7f72a0842ac95e9281eb78688076/transformed/jetified-window-java-1.0.0-beta04-api.jar!/META-INF/window-java_release.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: /Users/madol.eeee/.gradle/caches/transforms-3/e84741d2b04d8859553c8e0a19bf4026/transformed/jetified-kotlinx-coroutines-core-jvm-1.5.2.jar!/META-INF/kotlinx-coroutines-core.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:compileDebugKotlin'.
> Compilation error. See log for more details

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 8s
┌─ Flutter Fix ────────────────────────────────────────────────────────────────────────────────┐
│ [!] Your project requires a newer version of the Kotlin Gradle plugin.                       │
│ Find the latest version on https://kotlinlang.org/docs/gradle.html#plugin-and-versions, then │
│ update /Users/madol.eeee/project/traveling/flutter_traveling/android/build.gradle:           │
│ ext.kotlin_version = '<latest-version>'                                                      │
└──────────────────────────────────────────────────────────────────────────────────────────────┘
Exception: Gradle task assembleDebug failed with exit code 1
Exited (sigterm)

i updated flutter sdk version 2.8.1 to 2.10.1 and get error after updated

i don't know why this hapening,  how can i fix that?

sorry and thank you

Body:
first of all i solved this problem with FrancescoPenasa's help thanks!!

the solution is follows,

build.gradle file add follows

buildscript {
    ext.kotlin_version = '1.6.10'
    repositories {
        google()
        mavenCentral()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:4.1.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

after add code get another errer like this

Flutter multidex handling is disabled. If you wish to let the tool configure multidex, use the --mutidex flag.

app/build.gradle file add code

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.android.support:multidex:1.0.3'
}


问:
Hangfire in asp.net core webapi problem with DI
When I execute background job, and I try to resolve all dependencies, I get the exception:

Microsoft.EntityFrameworkCore.Query[10100]

An exception occurred while iterating over the results of a query for context type 'MyProj.DAL.ApplicationContext'.

System.ObjectDisposedException: Cannot access a disposed context instance. A common cause of this error is disposing a context instance that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling 'Dispose' on the context instance, or wrapping it in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.

Object name: 'ApplicationContext'

at Microsoft.EntityFrameworkCore.DbContext.CheckDisposed()

at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()

My code - in ConfigureServices(IServiceCollection services):

```<code>services.AddHangfire(cfg => cfg
     .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
     .UseSimpleAssemblyNameTypeSerializer()
     .UseRecommendedSerializerSettings()
     .UseMemoryStorage());

services.AddHangfireServer();
</code>```

in Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider provider):

```<code>GlobalConfiguration.Configuration.UseActivator(new ContainerJobActivator(provider));

app.UseHangfireDashboard()
</code>```

and

```<code>public class ContainerJobActivator : JobActivator
{
    private IServiceProvider _container;

    public ContainerJobActivator(IServiceProvider container)
    {
        _container = container;
    }

    public override object ActivateJob(Type type)
    {
        return _container.GetService(type);
    }
}
</code>```

My DBContext

```<code>services.AddEntityFrameworkNpgsql().
            AddDbContext<ApplicationContext>(opt =>
            opt.UseNpgsql("server=localhost;port=5432;database=database;uid=root;password=password;"));
</code>```

答:
We need resolve IServiceScopeFactory in our job, than get our service</p>
```<code>using (var scope = _factoryScope.CreateScope())
{
      _articleRepository = scope.ServiceProvider.GetService<IArticleRepository>() ?? throw new ArgumentNullException();

     // your job here.....

 }
</code>```

Body:
When I execute background job, and I try to resolve all dependencies, I get the exception:

Microsoft.EntityFrameworkCore.Query[10100]

An exception occurred while iterating over the results of a query for context type 'MyProj.DAL.ApplicationContext'.

System.ObjectDisposedException: Cannot access a disposed context instance. A common cause of this error is disposing a context instance that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling 'Dispose' on the context instance, or wrapping it in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.

Object name: 'ApplicationContext'

at Microsoft.EntityFrameworkCore.DbContext.CheckDisposed()

at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()

My code - in ConfigureServices(IServiceCollection services):

services.AddHangfire(cfg => cfg
     .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
     .UseSimpleAssemblyNameTypeSerializer()
     .UseRecommendedSerializerSettings()
     .UseMemoryStorage());

services.AddHangfireServer();

in Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider provider):

GlobalConfiguration.Configuration.UseActivator(new ContainerJobActivator(provider));

app.UseHangfireDashboard()

and

public class ContainerJobActivator : JobActivator
{
    private IServiceProvider _container;

    public ContainerJobActivator(IServiceProvider container)
    {
        _container = container;
    }

    public override object ActivateJob(Type type)
    {
        return _container.GetService(type);
    }
}

My DBContext

services.AddEntityFrameworkNpgsql().
            AddDbContext<ApplicationContext>(opt =>
            opt.UseNpgsql("server=localhost;port=5432;database=database;uid=root;password=password;"));

Body:
We need resolve IServiceScopeFactory in our job, than get our service

using (var scope = _factoryScope.CreateScope())
{
      _articleRepository = scope.ServiceProvider.GetService<IArticleRepository>() ?? throw new ArgumentNullException();

     // your job here.....

 }


问:
Request Body Missing in Spring while updating using PATCH API in react js
Spring shows - Resolved [org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public com.cg.bookstore.entities.OrderDetails com.cg.bookstore.controller.OrderDetailsController.updateDeliveryStatus(int,java.lang.String)]

Console shows  - Uncaught (in promise) Error: Request failed with status code 400

```<code>class UpdateOrder extends Component {

state = {
        deliveryStatus:""
 }

handleChange = (event) => {
    const deliveryStatus = { ...this.state.deliveryStatus };
    this.setState({ deliveryStatus: event.target.value });
  };

  handleSubmit = (event) => {
    // Prevents default behaviour of submit button
    event.preventDefault();
    console.log(this.state.deliveryStatus)
    console.log()

    OrderService.updateDeliveryStatus(this.props.match.params.orderDetailsId,this.state.deliveryStatus)
    .then((res) => {
      this.props.history.push("/admin/orders");
    });
  };
</code>```

In OrderService I call the updateDeliveryStatus

```<code>async updateDeliveryStatus(orderId,deliveryStatus){
    return await axios.patch(BASE_URL+"/"+orderId,deliveryStatus)

}
</code>```

The updateDeliveryStatus service in spring

```<code>@Override
public OrderDetails updateDeliveryStatus(int orderId, String deliveryStatus)
{
    Optional<OrderDetails> opt = orderDetailsRepo.findById(orderId);
    OrderDetails od;
    if (opt.isPresent())
    {
        od = opt.get();
        od.setDeliveryStatus(deliveryStatus);
        orderDetailsRepo.save(od);
    } else
    {

        throw new OrderDetailsNotFoundException("Order is not found");
    }
    return od;
}
</code>```

While I was testing backend in POSTMAN , I pass the input as plain string and it works fine. Is it because the input in not in form of json the issue? How to fix this ?

答:
Usually, when using @PutMethod and wanting to update a resource you need to provide both ID of the resource you want to update and the new body, which in this case I presume is 'OrderDetails', error suggests is missing there.

Without java controller code it's only assumptions though.

Body:
Spring shows - Resolved [org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public com.cg.bookstore.entities.OrderDetails com.cg.bookstore.controller.OrderDetailsController.updateDeliveryStatus(int,java.lang.String)]

Console shows  - Uncaught (in promise) Error: Request failed with status code 400

class UpdateOrder extends Component {

state = {
        deliveryStatus:""
 }

handleChange = (event) => {
    const deliveryStatus = { ...this.state.deliveryStatus };
    this.setState({ deliveryStatus: event.target.value });
  };

  handleSubmit = (event) => {
    // Prevents default behaviour of submit button
    event.preventDefault();
    console.log(this.state.deliveryStatus)
    console.log()

    OrderService.updateDeliveryStatus(this.props.match.params.orderDetailsId,this.state.deliveryStatus)
    .then((res) => {
      this.props.history.push("/admin/orders");
    });
  };

In OrderService I call the updateDeliveryStatus

async updateDeliveryStatus(orderId,deliveryStatus){
    return await axios.patch(BASE_URL+"/"+orderId,deliveryStatus)

}

The updateDeliveryStatus service in spring

@Override
public OrderDetails updateDeliveryStatus(int orderId, String deliveryStatus)
{
    Optional<OrderDetails> opt = orderDetailsRepo.findById(orderId);
    OrderDetails od;
    if (opt.isPresent())
    {
        od = opt.get();
        od.setDeliveryStatus(deliveryStatus);
        orderDetailsRepo.save(od);
    } else
    {

        throw new OrderDetailsNotFoundException("Order is not found");
    }
    return od;
}

While I was testing backend in POSTMAN , I pass the input as plain string and it works fine. Is it because the input in not in form of json the issue? How to fix this ?


问:
Android kotlin two way databinding on androidx.viewpager.widget.ViewPager::currentTab
I've tried tutorials on the Internet to add adapter on androidx.viewpager.widget.ViewPager to get two way databinding on current tab.
I arrived to that adapter

// adapter file
@BindingAdapter("currentTab")
@JvmStatic
fun setTab(pager: ViewPager, itemLiveData: MutableLiveData<Int>) {
   itemLiveData.value?.let {

        if (pager.currentItem != it) {
            pager.setCurrentItem(it, true)
        }
    }
}

@InverseBindingAdapter(attribute = "currentItem")
@JvmStatic
fun getTab(pager: ViewPager) = pager.currentItem
```

<pre class="lang-xml prettyprint-override"><code><!-- layout file -->
<androidx.viewpager.widget.ViewPager
    android:id="@+id/viewPager"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_marginTop="70dp"
    app:adapter="@{viewModel.adapter}"
    app:currentTab="@={viewModel.currentItem}"
    app:layout_constraintBottom_toTopOf="@+id/tabLayout"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">
</code>```

When I try to build the app, I got this error (with the --stacktrace option) :

Could not find event 'currentItemAttrChanged' on View type 'androidx.viewpager.widget.ViewPager'

I can't find any tutorials/answer so I ask here if anyone have an answer to that.
Thanks

EDIT :
I tried with @InverseBindingAdapter(attribute = "currentTab") but it give me the same kind of error : Could not find event 'currentTabAttrChanged' on View type 'androidx.viewpager.widget.ViewPager'.

The problem is that I don't know the event name call when currentTab change.

答:
2-way binding always required 3 adapters. The first (regular) one hauls data from vm to the view, the second (inverse) hauls the opposite way and the third (event) one tells the second when to fire. @InverseBindingAdapter has 2 attributes: attribute and event. If you don't specify the latter, it defaults to attribute name + "AttrChanged". Because it cannot work without the third. That's what the error message is saying.

ViewPager doesn't provide specialized "onPageChanged" listener. Instead, it has 3-fold OnPageChangeListener. But it's trivial to create a required event:

```<code>@BindingAdapter("currentTabAttrChanged")
public static void currentTabAttrChanged(@NonNull ViewPager viewpagerView, @Nullable InverseBindingListener listener) {
    if (listener != null) {
        viewpagerView.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                listener.onChange();
            }
        });
    }
}
</code>```

Body:
I've tried tutorials on the Internet to add adapter on androidx.viewpager.widget.ViewPager to get two way databinding on current tab.
I arrived to that adapter

// adapter file
@BindingAdapter("currentTab")
@JvmStatic
fun setTab(pager: ViewPager, itemLiveData: MutableLiveData<Int>) {
   itemLiveData.value?.let {

        if (pager.currentItem != it) {
            pager.setCurrentItem(it, true)
        }
    }
}

@InverseBindingAdapter(attribute = "currentItem")
@JvmStatic
fun getTab(pager: ViewPager) = pager.currentItem

<androidx.viewpager.widget.ViewPager
    android:id="@+id/viewPager"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_marginTop="70dp"
    app:adapter="@{viewModel.adapter}"
    app:currentTab="@={viewModel.currentItem}"
    app:layout_constraintBottom_toTopOf="@+id/tabLayout"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">

When I try to build the app, I got this error (with the --stacktrace option) :

Could not find event 'currentItemAttrChanged' on View type 'androidx.viewpager.widget.ViewPager'

I can't find any tutorials/answer so I ask here if anyone have an answer to that.
Thanks

EDIT :
I tried with @InverseBindingAdapter(attribute = "currentTab") but it give me the same kind of error : Could not find event 'currentTabAttrChanged' on View type 'androidx.viewpager.widget.ViewPager'.

The problem is that I don't know the event name call when currentTab change.

Body:
2-way binding always required 3 adapters. The first (regular) one hauls data from vm to the view, the second (inverse) hauls the opposite way and the third (event) one tells the second when to fire. @InverseBindingAdapter has 2 attributes: attribute and event. If you don't specify the latter, it defaults to attribute name + "AttrChanged". Because it cannot work without the third. That's what the error message is saying.

ViewPager doesn't provide specialized "onPageChanged" listener. Instead, it has 3-fold OnPageChangeListener. But it's trivial to create a required event:

@BindingAdapter("currentTabAttrChanged")
public static void currentTabAttrChanged(@NonNull ViewPager viewpagerView, @Nullable InverseBindingListener listener) {
    if (listener != null) {
        viewpagerView.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                listener.onChange();
            }
        });
    }
}


问:
.NET Core 3.1 - Dependency resolution failed for component - AWS Mock Lambda Test Tools
I create a new AWS Lambda .NET Core 3.1 project, then run it using AWS Lambda Test Tools, then I get this page as expected:

However, if I install one of these packages:

Microsoft.EntityFrameworkCore.SqlServer

Microsoft.Data.SqlClient

When I run, I get this error and the test page won't open:

```<code>AWS .NET Core 3.1 Mock Lambda Test Tool (0.10.0)
Unknown error occurred causing process exit: Dependency resolution failed for component C:\Users\siri\repos\bolao-futebol\website-core\AWSLambda1\bin\Debug\netcoreapp3.1\AWSLambda1.dll with error code -2147450740. Detailed error: Error:
An assembly specified in the application dependencies manifest (AWSLambda1.deps.json) was not found:
package: 'runtime.win-x64.runtime.native.System.Data.SqlClient.sni', version: '4.4.0'
path: 'runtimes/win-x64/native/sni.dll'

at System.Runtime.Loader.AssemblyDependencyResolver..ctor(String componentAssemblyPath)
at Amazon.Lambda.TestTool.Runtime.LambdaAssemblyLoadContext..ctor(String lambdaPath) in C:\codebuild\tmp\output\src142363207\src\Tools\LambdaTestTool\src\Amazon.Lambda.TestTool\Runtime\LambdaAssemblyLoadContext.cs:line 28
at Amazon.Lambda.TestTool.Runtime.LocalLambdaRuntime.Initialize(String directory, IAWSService awsService) in C:\codebuild\tmp\output\src142363207\src\Tools\LambdaTestTool\src\Amazon.Lambda.TestTool\Runtime\LocalLambdaRuntime.cs:line 71
at Amazon.Lambda.TestTool.Runtime.LocalLambdaRuntime.Initialize(String directory) in C:\codebuild\tmp\output\src142363207\src\Tools\LambdaTestTool\src\Amazon.Lambda.TestTool\Runtime\LocalLambdaRuntime.cs:line 46
at Amazon.Lambda.TestTool.TestToolStartup.Startup(String productName, Action`2 uiStartup, String[] args, RunConfiguration runConfiguration) in C:\codebuild\tmp\output\src142363207\src\Tools\LambdaTestTool\src\Amazon.Lambda.TestTool\TestToolStartup.cs:line 77
</code>```

I have a .NET Core 2.1 Lambda project with this package and it works fine, it only fails in .NET Core 3.1.

Below is my .csproj in case anyone wants to give a try.

```<code><Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>
    <AWSProjectType>Lambda</AWSProjectType>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Amazon.Lambda.Core" Version="1.1.0" />
    <PackageReference Include="Amazon.Lambda.Serialization.SystemTextJson" Version="1.0.0" />
    <PackageReference Include="Amazon.Lambda.SQSEvents" Version="1.1.0" />
    <PackageReference Include="Amazon.Lambda.AspNetCoreServer" Version="5.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.0" />
  </ItemGroup>
</Project>
</code>```

This works fine deployed on AWS Lambda, it only fails running it locally with the Mock Tools.

Removing Microsoft.EntityFrameworkCore.SqlServer makes it work again.

This was also posted in github a while ago, I'm hoping someone else ran into this and has a fix.

答:
I had the same issue, but in my case I had the tool installed but somehaow it got broken, so I have to uninstall it, deleting the file
"C:\Users\{USERNAME}\.dotnet\tools\dotnet-lambda-test-tool-3.1.exe"

Then I could reinstall it running
"dotnet tool install -g Amazon.Lambda.TestTool-3.1"

Body:
I create a new AWS Lambda .NET Core 3.1 project, then run it using AWS Lambda Test Tools, then I get this page as expected:

However, if I install one of these packages:

Microsoft.EntityFrameworkCore.SqlServer

Microsoft.Data.SqlClient

When I run, I get this error and the test page won't open:

AWS .NET Core 3.1 Mock Lambda Test Tool (0.10.0)
Unknown error occurred causing process exit: Dependency resolution failed for component C:\Users\siri\repos\bolao-futebol\website-core\AWSLambda1\bin\Debug\netcoreapp3.1\AWSLambda1.dll with error code -2147450740. Detailed error: Error:
An assembly specified in the application dependencies manifest (AWSLambda1.deps.json) was not found:
package: 'runtime.win-x64.runtime.native.System.Data.SqlClient.sni', version: '4.4.0'
path: 'runtimes/win-x64/native/sni.dll'

at System.Runtime.Loader.AssemblyDependencyResolver..ctor(String componentAssemblyPath)
at Amazon.Lambda.TestTool.Runtime.LambdaAssemblyLoadContext..ctor(String lambdaPath) in C:\codebuild\tmp\output\src142363207\src\Tools\LambdaTestTool\src\Amazon.Lambda.TestTool\Runtime\LambdaAssemblyLoadContext.cs:line 28
at Amazon.Lambda.TestTool.Runtime.LocalLambdaRuntime.Initialize(String directory, IAWSService awsService) in C:\codebuild\tmp\output\src142363207\src\Tools\LambdaTestTool\src\Amazon.Lambda.TestTool\Runtime\LocalLambdaRuntime.cs:line 71
at Amazon.Lambda.TestTool.Runtime.LocalLambdaRuntime.Initialize(String directory) in C:\codebuild\tmp\output\src142363207\src\Tools\LambdaTestTool\src\Amazon.Lambda.TestTool\Runtime\LocalLambdaRuntime.cs:line 46
at Amazon.Lambda.TestTool.TestToolStartup.Startup(String productName, Action`2 uiStartup, String[] args, RunConfiguration runConfiguration) in C:\codebuild\tmp\output\src142363207\src\Tools\LambdaTestTool\src\Amazon.Lambda.TestTool\TestToolStartup.cs:line 77

I have a .NET Core 2.1 Lambda project with this package and it works fine, it only fails in .NET Core 3.1.

Below is my .csproj in case anyone wants to give a try.

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>
    <AWSProjectType>Lambda</AWSProjectType>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Amazon.Lambda.Core" Version="1.1.0" />
    <PackageReference Include="Amazon.Lambda.Serialization.SystemTextJson" Version="1.0.0" />
    <PackageReference Include="Amazon.Lambda.SQSEvents" Version="1.1.0" />
    <PackageReference Include="Amazon.Lambda.AspNetCoreServer" Version="5.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.0" />
  </ItemGroup>
</Project>

This works fine deployed on AWS Lambda, it only fails running it locally with the Mock Tools.

Removing Microsoft.EntityFrameworkCore.SqlServer makes it work again.

This was also posted in github a while ago, I'm hoping someone else ran into this and has a fix.


问:
When I use the JavaScript On Screen Menu example, the button of OnScreenMenuButtonType doesn't show the icon
I don't know why, the example in the document can display the icon, but the one I wrote does not display
enter image description here</p>
```<code>this.SpecChart.addOnScreenMenu(
        [
          [
            // Default buttons
            OnScreenMenuButtonType.ZoomInX,
            OnScreenMenuButtonType.ZoomOutX,
            OnScreenMenuButtonType.ZoomInY,
            OnScreenMenuButtonType.ZoomOutY,
            OnScreenMenuButtonType.ZoomToFit,
            OnScreenMenuButtonType.ToggleAnimations,
            // cusrom button
            {
              dimensions: { rows: 1, columns: 1 },
              label: "Show Heatmap",
              opacity: "1",
              color: "blue",
              shape: OnScreenMenuButtonShape.RoundedRectangle,
              action: this.show,
            },
          ],
        ],
        OnScreenMenuButtonShape.RoundedRectangle
      );
</code>```

答:
Probably this is caused by LightningChart not having access to its resources folder. The OnScreenMenu pictures are distributed in a resources folder along with the library, but the library itself doesn't know where it is located.

Here's a link to the related item in API documentation to learn more: https://www.arction.com/lightningchart-js-api-documentation/v3.4.0/interfaces/lightningchartoptions.html#resourcesbaseurl

A quick and dirty fix you can try is the following code snippet which tells LightningChart to look for the resources folder from a CDN service - this is super slow and I would not advise to do this in any long term solution.

```<code>const chart = lightningChart({
   resourcesBaseUrl: "https://cdn.jsdelivr.net/npm/@arction/lcjs@3.4.0/dist/resources",
}).ChartXY();

// ... add OnScreenMenu inside the chart ...
</code>```

For a long term solution, you'll have to download the resources folder to your project, setup a file server and supply the URL to the file server with resourcesBaseUrl option.

Body:
I don't know why, the example in the document can display the icon, but the one I wrote does not display
enter image description here

this.SpecChart.addOnScreenMenu(
        [
          [
            // Default buttons
            OnScreenMenuButtonType.ZoomInX,
            OnScreenMenuButtonType.ZoomOutX,
            OnScreenMenuButtonType.ZoomInY,
            OnScreenMenuButtonType.ZoomOutY,
            OnScreenMenuButtonType.ZoomToFit,
            OnScreenMenuButtonType.ToggleAnimations,
            // cusrom button
            {
              dimensions: { rows: 1, columns: 1 },
              label: "Show Heatmap",
              opacity: "1",
              color: "blue",
              shape: OnScreenMenuButtonShape.RoundedRectangle,
              action: this.show,
            },
          ],
        ],
        OnScreenMenuButtonShape.RoundedRectangle
      );

Body:
Probably this is caused by LightningChart not having access to its resources folder. The OnScreenMenu pictures are distributed in a resources folder along with the library, but the library itself doesn't know where it is located.

Here's a link to the related item in API documentation to learn more: https://www.arction.com/lightningchart-js-api-documentation/v3.4.0/interfaces/lightningchartoptions.html#resourcesbaseurl

A quick and dirty fix you can try is the following code snippet which tells LightningChart to look for the resources folder from a CDN service - this is super slow and I would not advise to do this in any long term solution.

const chart = lightningChart({
   resourcesBaseUrl: "https://cdn.jsdelivr.net/npm/@arction/lcjs@3.4.0/dist/resources",
}).ChartXY();

// ... add OnScreenMenu inside the chart ...

For a long term solution, you'll have to download the resources folder to your project, setup a file server and supply the URL to the file server with resourcesBaseUrl option.


问:
Can Gradle fail the build if the jar is too big?
What is a good way for gradle to warn the developer that the code/dependency change they’re making makes the built jar too big?

We’re making updates to a repo that builds a jar that’s deployed in an AWS Lambda function. We are limited to 50MB for the executable. We’d ideally like the devs to get this feedback much before our CI/CD tries to upload to a lambda function and fails.

答:
You could define and use a custom task to implement the file size check, and create a dependency between this task and the task that produces the Jar.

Assuming you are using Sprinboot, you could create a finalizer task that will be executed just after the bootJar task and make the build fail when jar size exceeds a certain limit.

Simple implementation as example:

```<code>task jarSizeChecker() {
    def maxSize = 15_000_000  // jar size limit in bytes
    group "verification"
    description "Checks that the produced jar size does not exceed the defined limit"
    doLast {
        println " checking jar size"
        def jarFileSize = bootJar.archiveFile.get().getAsFile().length()
        println " fileSize is ${jarFileSize}"
        if (jarFileSize > maxSize) {
            throw new GradleException("Jar size exceed the defined limit")
        }

    }
}

bootJar.finalizedBy(jarSizeChecker)
</code>```

Result:

```<code>$ ./gradlew bootJar

[...]
> Task :bootJar

> Task :jarSizeChecker FAILED
 checking jar size
 fileSize is 17333895
7 actionable tasks: 5 executed, 2 from cache

FAILURE: Build failed with an exception.

* Where:
Build file 'C:\dev\workspaces\...\build.gradle'

* What went wrong:
Execution failed for task ':jarSizeChecker'.
> Jar size exceed the defined limit
</code>```

Body:
You could define and use a custom task to implement the file size check, and create a dependency between this task and the task that produces the Jar.

Assuming you are using Sprinboot, you could create a finalizer task that will be executed just after the bootJar task and make the build fail when jar size exceeds a certain limit.

Simple implementation as example:

task jarSizeChecker() {
    def maxSize = 15_000_000  // jar size limit in bytes
    group "verification"
    description "Checks that the produced jar size does not exceed the defined limit"
    doLast {
        println " checking jar size"
        def jarFileSize = bootJar.archiveFile.get().getAsFile().length()
        println " fileSize is ${jarFileSize}"
        if (jarFileSize > maxSize) {
            throw new GradleException("Jar size exceed the defined limit")
        }

    }
}

bootJar.finalizedBy(jarSizeChecker)

Result:

$ ./gradlew bootJar

[...]
> Task :bootJar

> Task :jarSizeChecker FAILED
 checking jar size
 fileSize is 17333895
7 actionable tasks: 5 executed, 2 from cache

FAILURE: Build failed with an exception.

* Where:
Build file 'C:\dev\workspaces\...\build.gradle'

* What went wrong:
Execution failed for task ':jarSizeChecker'.
> Jar size exceed the defined limit


问:
Use the same query for multiple tables
I have this two similar queries for different tables, one for loan_offers table and one for special_offers table

for loan_offers

```<code>@Query(
        value = "SELECT " +
                "CAST(o.id AS VARCHAR), o.user_id, " +
                "o.partner_key, o.partner_name, " +
                "o.originator_key, o.originator_name, " +
                "o.type, o.response, " +
                "COALESCE(lo.recommendation_score, 0) AS recommendation_score " +
                "FROM offers o " +
                "INNER JOIN loan_offers lo " +
                "ON lo.offer_id = o.id " +
                "WHERE o.created_at > EXTRACT(epoch FROM now() - INTERVAL '30' DAY) * 1000 " +
                "AND o.user_id = ?1 " +
                "ORDER BY recommendation_score DESC",
        nativeQuery = true)
List<OffersResponse> fetchLoanOffers(String userId);
</code>```

for special_offers

```<code>@Query(
        value = "SELECT " +
                "CAST(o.id AS VARCHAR), o.user_id, " +
                "o.partner_key, o.partner_name, " +
                "o.originator_key, o.originator_name, " +
                "o.type, o.response, " +
                "COALESCE(so.recommendation_score, 0) AS recommendation_score " +
                "FROM offers o " +
                "INNER JOIN special_offers so " +
                "ON so.offer_id = o.id " +
                "WHERE o.created_at > EXTRACT(epoch FROM now() - INTERVAL '30' DAY) * 1000 " +
                "AND o.user_id = ?1 " +
                "ORDER BY recommendation_score DESC",
        nativeQuery = true)
List<OffersResponse> fetchSpecialOffers(String userId);
</code>```

So my question is how not to write so much similar code, maybe by using UDF or there is a better solution.

答:
Use a variable to declare which table you want and use the variable in the query string. Change the alias of the table to be the same and it looks like it'd be the same query.

I don't really recommend it though as they are different tables that could change and the circumstances for the need. Its better to have the defined query for its use in a business object or something.
But we do these things to save typing some times.

Title: Use the same query for multiple tables

Body:
I have this two similar queries for different tables, one for loan_offers table and one for special_offers table

for loan_offers

@Query(
        value = "SELECT " +
                "CAST(o.id AS VARCHAR), o.user_id, " +
                "o.partner_key, o.partner_name, " +
                "o.originator_key, o.originator_name, " +
                "o.type, o.response, " +
                "COALESCE(lo.recommendation_score, 0) AS recommendation_score " +
                "FROM offers o " +
                "INNER JOIN loan_offers lo " +
                "ON lo.offer_id = o.id " +
                "WHERE o.created_at > EXTRACT(epoch FROM now() - INTERVAL '30' DAY) * 1000 " +
                "AND o.user_id = ?1 " +
                "ORDER BY recommendation_score DESC",
        nativeQuery = true)
List<OffersResponse> fetchLoanOffers(String userId);

for special_offers

@Query(
        value = "SELECT " +
                "CAST(o.id AS VARCHAR), o.user_id, " +
                "o.partner_key, o.partner_name, " +
                "o.originator_key, o.originator_name, " +
                "o.type, o.response, " +
                "COALESCE(so.recommendation_score, 0) AS recommendation_score " +
                "FROM offers o " +
                "INNER JOIN special_offers so " +
                "ON so.offer_id = o.id " +
                "WHERE o.created_at > EXTRACT(epoch FROM now() - INTERVAL '30' DAY) * 1000 " +
                "AND o.user_id = ?1 " +
                "ORDER BY recommendation_score DESC",
        nativeQuery = true)
List<OffersResponse> fetchSpecialOffers(String userId);

So my question is how not to write so much similar code, maybe by using UDF or there is a better solution.


问:
Frequency table and proportions stored in different dataframes
I am having a dataframe that has around 20 variables which are numeric and 1 which is categorical.
For simplicity I made a very small one. I want to calculate the frequency of each number per category and also the proportion (%) of each number per category.

Then, those tables should be stored in a different dataframe for each variable from the original dataframe.

My data look like that:

```<code>df <- data.frame(categories = c(1,2,3,3,4,1),
             X1 = c(0,11,13,2,0,5),
             X2 = c(2,0,NA,1,3,7))
</code>```

And I want something like that stored in two different dataframes:

For X1

```<code>      1  2  3  4
 0    1  0  0  0
 2    1  0  0  0
 5    0  0  1  0
 11   0  1  0  0
 13   0  0  1  0
</code>```

for X2

```<code>      1  2  3  4
  0   0  1  0  0
  1   0  0  1  0
  2   1  0  0  0
  3   0  0  0  1
  7   1  0  0  0
</code>```

Also, if possible they should include a (%) next to each category.

Can we achieve the following with a loop as well?

Thank you very much.

Body:
I am having a dataframe that has around 20 variables which are numeric and 1 which is categorical.
For simplicity I made a very small one. I want to calculate the frequency of each number per category and also the proportion (%) of each number per category.

Then, those tables should be stored in a different dataframe for each variable from the original dataframe.

My data look like that:

df <- data.frame(categories = c(1,2,3,3,4,1),
             X1 = c(0,11,13,2,0,5),
             X2 = c(2,0,NA,1,3,7))

And I want something like that stored in two different dataframes:

For X1

      1  2  3  4
 0    1  0  0  0
 2    1  0  0  0
 5    0  0  1  0
 11   0  1  0  0
 13   0  0  1  0

for X2

      1  2  3  4
  0   0  1  0  0
  1   0  0  1  0
  2   1  0  0  0
  3   0  0  0  1
  7   1  0  0  0

Also, if possible they should include a (%) next to each category.

Can we achieve the following with a loop as well?

Thank you very much.

Body:
base

df <- data.frame(categories = c(1,2,3,3,4,1),
                 X1 = c(0,11,13,2,0,5),
                 X2 = c(2,0,NA,1,3,7))

lapply(df[grep("^X\\d+", names(df))], function(x) table(x, df$categories))

#> $X1
#>
#> x    1 2 3 4
#>   0  1 0 0 1
#>   2  0 0 1 0
#>   5  1 0 0 0
#>   11 0 1 0 0
#>   13 0 0 1 0
#>
#> $X2
#>
#> x   1 2 3 4
#>   0 0 1 0 0
#>   1 0 0 1 0
#>   2 1 0 0 0
#>   3 0 0 0 1
#>   7 1 0 0 0

Created on 2022-02-11 by the reprex package (v2.0.1)

Created on 2022-02-11 by the reprex package (v2.0.1)

tidyverse

df <- data.frame(categories = c(1,2,3,3,4,1),
                 X1 = c(0,11,13,2,0,5),
                 X2 = c(2,0,NA,1,3,7))

library(tidyverse)

map(
  .x = str_subset(names(df), pattern = "^X\\d+"),
  .f = ~ pivot_wider(
    data = df,
    id_cols = all_of(.x),
    names_from = categories,
    values_from = categories,
    values_fn = length,
    values_fill = 0
  ) %>%
    arrange(!!sym(.x)) %>%
    drop_na
)
#> [[1]]
#> # A tibble: 5 x 5
#>      X1   `1`   `2`   `3`   `4`
#>   <dbl> <int> <int> <int> <int>
#> 1     0     1     0     0     1
#> 2     2     0     0     1     0
#> 3     5     1     0     0     0
#> 4    11     0     1     0     0
#> 5    13     0     0     1     0
#>
#> [[2]]
#> # A tibble: 5 x 5
#>      X2   `1`   `2`   `3`   `4`
#>   <dbl> <int> <int> <int> <int>
#> 1     0     0     1     0     0
#> 2     1     0     0     1     0
#> 3     2     1     0     0     0
#> 4     3     0     0     0     1
#> 5     7     1     0     0     0

Created on 2022-02-11 by the reprex package (v2.0.1)


问:
How can I specify the minor version of a .Net 6 target application to 6.0.1
I have a .Net 6 application that is deployed to a large number of desktops. Our IT infrastructure team installs a specific version of the .Net 6 (6.0.1)

When I compile this in Visual Studio or in a Azure DevOps pipeline the latest available .Net 6 version is taken. This is problematic because we don't want to keep on updating the .Net6 version on our many desktops

In the csproj file

```<code><TargetFramework>net6.0-windows</TargetFramework>
</code>```

Ideally I would like to specify something like

```<code><TargetFramework>net6.0-windows;netcoreapp6.0.1</TargetFramework>
</code>```

But this does not work. How can I specify that the target should be .Net 6.0.1 in Visual Studio or in the Build step in my Build Pipeline?

答:
In Azure DevOps pipeline, the Use .NET Core task may help you. You can add this task before build.

Use this task to acquire a specific version of .NET Core from the
Internet or the tools cache and add it to the PATH.

You can also use this task to change the version of .NET Core used in
subsequent tasks like .NET Core cli task.

```<code>steps:
- task: UseDotNet@2
  displayName: 'Use .NET Core sdk'
  inputs:
    packageType: sdk
    version: 6.0.1
    installationPath: $(Agent.ToolsDirectory)/dotnet
</code>```

Body:
I have a .Net 6 application that is deployed to a large number of desktops. Our IT infrastructure team installs a specific version of the .Net 6 (6.0.1)

When I compile this in Visual Studio or in a Azure DevOps pipeline the latest available .Net 6 version is taken. This is problematic because we don't want to keep on updating the .Net6 version on our many desktops

In the csproj file

<TargetFramework>net6.0-windows</TargetFramework>

Ideally I would like to specify something like

<TargetFramework>net6.0-windows;netcoreapp6.0.1</TargetFramework>

But this does not work. How can I specify that the target should be .Net 6.0.1 in Visual Studio or in the Build step in my Build Pipeline?

Body:
In Azure DevOps pipeline, the Use .NET Core task may help you. You can add this task before build.

Use this task to acquire a specific version of .NET Core from the
Internet or the tools cache and add it to the PATH.

You can also use this task to change the version of .NET Core used in
subsequent tasks like .NET Core cli task.

steps:
- task: UseDotNet@2
  displayName: 'Use .NET Core sdk'
  inputs:
    packageType: sdk
    version: 6.0.1
    installationPath: $(Agent.ToolsDirectory)/dotnet


问:
Swiper image slider - how to center images inside a slide?
I am developing an Ionic/Angular application and have to show an image slider. I did this with swiper ([https://swiperjs.com/get-started#install-from-npm]). Now my slides look like this (images have different widths and heights):
actual looking

My question is: Is there a way to center these images horizontally and vertically? This would be so much better looking!
Thank you in advance.

答: The idea of swiperjs is to turn the entire div into a slider slider. You can do whatever layout you want inside that div. My advice is to design it separately, with some tool and then add it to the div with the swiper-slide class.</p>