问:
Setting up a React application and NodeJS backend in Kubernetes?
I am trying to setup a sample React application wired to a NodeJS backend as two pods in Kubernetes. This is the (mostly) the default CRA and NodeJS application with Express i.e. npx create-react-app my_app.

Both application runs fine locally through yarn start and npm app.js respectively. The React application uses a proxy defined in package.json to communicate with the NodeJS back-end.

React package.json

```<code>...
  "proxy": "http://localhost:3001/"
...
</code>```

React Dockerfile

```<code>FROM node:10
WORKDIR /usr/src/app
COPY package*.json ./
RUN yarn
COPY . .
CMD [ "yarn", "start" ]
</code>```

NodeJS Dockerfile

```<code>FROM node:10
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3001
CMD [ "node", "app.js" ]
</code>```

ui-deployment

```<code>apiVersion: extensions/v1beta1
kind: Deployment
metadata:
    name: sample-ui
    namespace: my_namespace
spec:
  replicas: 1
  selector:
    matchLabels:
      app: my_namespace
      component: sample-ui
  template:
    metadata:
      labels:
        app: my_namespace
        component: sample-ui
    spec:
      containers:
      -
        name: sample-ui
        image: xxx
        imagePullPolicy: IfNotPresent
        ports:
        - containerPort: 3000
          name: http
          protocol: TCP
        resources:
          limits:
            cpu: 100m
            memory: 128Mi
          requests:
            cpu: 100m
            memory: 128Mi
</code>```

server-deployment

```<code>apiVersion: extensions/v1beta1
kind: Deployment
metadata:
    name: sample-server
    namespace: my_namespace
spec:
  replicas: 1
  selector:
    matchLabels:
      app: my_namespace
      component: sample-server
  template:
    metadata:
      labels:
        app: my_namespace
        component: sample-server
    spec:
      containers:
      -
        name: sample-server
        image: xxx
        imagePullPolicy: IfNotPresent
        ports:
        - containerPort: 3001
          name: http
          protocol: TCP
        resources:
          limits:
            cpu: 100m
            memory: 128Mi
          requests:
            cpu: 100m
            memory: 128Mi
</code>```

ui-service

```<code>apiVersion: v1
kind: Service
metadata:
  name: sample-ui
  namespace: my_namespace
  labels: {app: sample-ui}
spec:
  type: LoadBalancer
  selector:
    component: sample-ui
  ports:
  - name: listen
    protocol: TCP
    port: 3000
</code>```

server-service

```<code>apiVersion: v1
kind: Service
metadata:
  name: sample-server
  namespace: my_namespace
  labels: {app: sample-server}
spec:
  selector:
    component: sample-server
  ports:
  - name: listen
    protocol: TCP
    port: 3001
</code>```

Both services run fine on my system.

get svc

```<code>sample-server            ClusterIP      10.19.255.171   <none>           3001/TCP                     26m
sample-ui                LoadBalancer   10.19.242.42    34.82.235.125    3000:31074/TCP               26m
</code>```

However, my deployment for the CRA crashes multiple time despite indicating it is still running.

get pods

```<code>sample-server-598776c5fc-55jsz                     1/1     Running     0          42m
sample-ui-c75ccb746-qppk2                          1/1     Running     4          2m38s
</code>```

I suspect that my React Dockerfile is improperly configured but I'm not sure how to write it to work with a NodeJS backend in kubernetes.

a) How can I setup my Dockerfile for my CRA such that it will run in a pod?

b) How can I setup my docker services and pods such that they communicate?

答:
a) How can I setup my Dockerfile for my CRA such that it will run in a
pod?

React docker file is looking good you need to check why container of pod is failing.

Using kubectl describe pod <POD name> or debug more logs using the command kubectl logs <pod name>

How can I setup my docker services and pods such that they
communicate?

For this, you are on right track, how server and frontend will communicate in Kubernetes using the service name.

This might weird at first level but Kubernetes DNS takes care of it.

How if you have two service frontend (sample-ui) and backend (sample-server)

sample-ui will send the request to sample-server so they get connected that way.

You can also try this by going inside the sample-ui POD(container)

```<code>kubect exec -it sample-ui-c75ccb746-qppk2 -- /bin/bash
</code>```

now you are inside of sample-ui container let's send request to sample-server from here

if curl not exist you can install it using the apk install curl or apt-get install curl or yum install curl

```<code>curl http://sample-server:3001
</code>```

Magic you might see response from server.

So your while flow goes like

user coming to frontend load balancer service > calling sample-ui service > internally inside kubernetes cluster now your sample-ui calling the sample-server

All the service that you create inside the K8s will be accesible by it's name.

Body:
I am trying to setup a sample React application wired to a NodeJS backend as two pods in Kubernetes. This is the (mostly) the default CRA and NodeJS application with Express i.e. npx create-react-app my_app.

Both application runs fine locally through yarn start and npm app.js respectively. The React application uses a proxy defined in package.json to communicate with the NodeJS back-end.

React package.json

...
  "proxy": "http://localhost:3001/"
...

React Dockerfile

FROM node:10
WORKDIR /usr/src/app
COPY package*.json ./
RUN yarn
COPY . .
CMD [ "yarn", "start" ]

NodeJS Dockerfile

FROM node:10
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3001
CMD [ "node", "app.js" ]

ui-deployment

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
    name: sample-ui
    namespace: my_namespace
spec:
  replicas: 1
  selector:
    matchLabels:
      app: my_namespace
      component: sample-ui
  template:
    metadata:
      labels:
        app: my_namespace
        component: sample-ui
    spec:
      containers:
      -
        name: sample-ui
        image: xxx
        imagePullPolicy: IfNotPresent
        ports:
        - containerPort: 3000
          name: http
          protocol: TCP
        resources:
          limits:
            cpu: 100m
            memory: 128Mi
          requests:
            cpu: 100m
            memory: 128Mi

server-deployment

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
    name: sample-server
    namespace: my_namespace
spec:
  replicas: 1
  selector:
    matchLabels:
      app: my_namespace
      component: sample-server
  template:
    metadata:
      labels:
        app: my_namespace
        component: sample-server
    spec:
      containers:
      -
        name: sample-server
        image: xxx
        imagePullPolicy: IfNotPresent
        ports:
        - containerPort: 3001
          name: http
          protocol: TCP
        resources:
          limits:
            cpu: 100m
            memory: 128Mi
          requests:
            cpu: 100m
            memory: 128Mi

ui-service

apiVersion: v1
kind: Service
metadata:
  name: sample-ui
  namespace: my_namespace
  labels: {app: sample-ui}
spec:
  type: LoadBalancer
  selector:
    component: sample-ui
  ports:
  - name: listen
    protocol: TCP
    port: 3000

server-service

apiVersion: v1
kind: Service
metadata:
  name: sample-server
  namespace: my_namespace
  labels: {app: sample-server}
spec:
  selector:
    component: sample-server
  ports:
  - name: listen
    protocol: TCP
    port: 3001

Both services run fine on my system.

get svc

sample-server            ClusterIP      10.19.255.171   <none>           3001/TCP                     26m
sample-ui                LoadBalancer   10.19.242.42    34.82.235.125    3000:31074/TCP               26m

However, my deployment for the CRA crashes multiple time despite indicating it is still running.

get pods

sample-server-598776c5fc-55jsz                     1/1     Running     0          42m
sample-ui-c75ccb746-qppk2                          1/1     Running     4          2m38s

I suspect that my React Dockerfile is improperly configured but I'm not sure how to write it to work with a NodeJS backend in kubernetes.

a) How can I setup my Dockerfile for my CRA such that it will run in a pod?

b) How can I setup my docker services and pods such that they communicate?

Body:
a) How can I setup my Dockerfile for my CRA such that it will run in a
pod?

React docker file is looking good you need to check why container of pod is failing.

Using kubectl describe pod <POD name> or debug more logs using the command kubectl logs <pod name>

How can I setup my docker services and pods such that they
communicate?

For this, you are on right track, how server and frontend will communicate in Kubernetes using the service name.

This might weird at first level but Kubernetes DNS takes care of it.

How if you have two service frontend (sample-ui) and backend (sample-server)

sample-ui will send the request to sample-server so they get connected that way.

You can also try this by going inside the sample-ui POD(container)

kubect exec -it sample-ui-c75ccb746-qppk2 -- /bin/bash

now you are inside of sample-ui container let's send request to sample-server from here

if curl not exist you can install it using the apk install curl or apt-get install curl or yum install curl

curl http://sample-server:3001

Magic you might see response from server.

So your while flow goes like

user coming to frontend load balancer service > calling sample-ui service > internally inside kubernetes cluster now your sample-ui calling the sample-server

All the service that you create inside the K8s will be accesible by it's name.


来源: stackexchange

问:
How does jmock and mockito create wrappers?
For example, I have the following code:

```<code>SomeClass stub = Mockito.mock(SomeClass.class);
</code>```

After that, stub is a normal implementation of SomeClass, but with its own behavior (default is to just throw some exception, but that's ok)

How can I do the same thing for my library? I would like to be able to wrap some classes, or even better instances with some wrap() method, to mix-in my behavior there.

答:
Both jmock and Mockito (which uses jmock code) use cglib internally to create their stubs/proxies. See ClassImposterizer.

For simple cases, you can use Java's Proxy mechanism to create dynamic proxies (really just invocation handlers) of interfaces you want to stub or mock.

ContentLicense: CC BY-SA 3.0

Body:
For example, I have the following code:

SomeClass stub = Mockito.mock(SomeClass.class);

After that, stub is a normal implementation of SomeClass, but with its own behavior (default is to just throw some exception, but that's ok)

How can I do the same thing for my library? I would like to be able to wrap some classes, or even better instances with some wrap() method, to mix-in my behavior there.


问:
Can I change a element state in react without changing every element state?
im making a portfolio website and have multiple different buttons with skills which contain an img and p tag. I want to show the description of each tag everytime a user clicks on the button. how can I do this? right now everytime user clicks it, all buttons show description.

const Skills = () => {
const [state, setState] = useState(false)

```<code>let skills = [
    { id: 1, desc: 'HTML5', state: false, img: htmlIcon },
    { id: 2, desc: 'CSS3', state: false, img: cssIcon },
    { etc....}

const showDesc = (id) => {
    console.log(skills[id-1] = !state);
    setState(!state)
    }
return (
{skills.map(skill => (
    <button onClick={(id) => showDesc(skill.id)}>
        <img style={ state ? {display:'none'} : {display:'block'}} src={skill.img} />
        <p style={ state ? {display:'block'} : {display:'none'}}>{skill.desc}</p>
    </button>
))}
</code>```

答:
I recommend to manipulate element state instead of entry list. But if you really need to manipulate entry list you should add that list to your state. Then when you want to show/hide specific item, you need to find that item in state and correctly update entry list by making a copy of that list (with updated item). For example you can do it like this:

```<code>import React, { useState } from 'react';

const Skills = () => {
  const [skills, setSkills] = useState([
    {
      id: 1,
      desc: 'HTML5',
      state: false,
      img: htmlIcon, // your icon
    },
    {
      id: 2,
      desc: 'CSS3',
      state: false,
      img: cssIcon, // your icon
    },
  ]);

  const showDesc = (id) => {
    const newSkills = skills.map((item) => {
      if (item.id === id) {
        return {
          ...item,
          state: !item.state,
        };
      }

      return item;
    });

    setSkills(newSkills);
  };
  return (
    <div>
      {skills.map(({
        id,
        img,
        state,
        desc,
      }) => (
        <button type="button" key={id} onClick={() => showDesc(id)}>
          <img alt="img" style={state ? { display: 'none' } : { display: 'block' }} src={img} />
          <p style={state ? { display: 'block' } : { display: 'none' }}>{desc}</p>
        </button>
      ))}
    </div>
  );
};
</code>```

Instead of manipulating all list, you can try to move show/hide visibility to list item itself. Create separate component for item and separate component for rendering that items. It will help you to simplify logic and make individual component responsible for it visibility.

About list rendering you can read more here

For example you can try something like this as alternative:

```<code>import React, { useState } from 'react';

const skills = [
  {
    id: 1,
    desc: 'HTML5',
    img: htmlIcon, // your icon
  },
  {
    id: 2,
    desc: 'CSS3',
    img: cssIcon, // your icon
  },
];

const SkillItem = ({
  img,
  desc = '',
}) => {
  const [visibility, setVisibility] = useState(false);

  const toggleVisibility = () => {
    setVisibility(!visibility);
  };

  const content = visibility
    ? <p>{desc}</p>
    : <img alt="img" src={img} />;

  return (
    <div>
      <button type="button" onClick={toggleVisibility}>
        {content}
      </button>
    </div>
  );
};

const SkillList = () => skills.map(({
  id,
  img,
  desc,
}) => <SkillItem img={img} desc={desc} key={id} />);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
im making a portfolio website and have multiple different buttons with skills which contain an img and p tag. I want to show the description of each tag everytime a user clicks on the button. how can I do this? right now everytime user clicks it, all buttons show description.

const Skills = () => {
const [state, setState] = useState(false)

let skills = [
    { id: 1, desc: 'HTML5', state: false, img: htmlIcon },
    { id: 2, desc: 'CSS3', state: false, img: cssIcon },
    { etc....}

const showDesc = (id) => {
    console.log(skills[id-1] = !state);
    setState(!state)
    }
return (
{skills.map(skill => (
    <button onClick={(id) => showDesc(skill.id)}>

{skill.desc}

    </button>
))}

Body:
I recommend to manipulate element state instead of entry list. But if you really need to manipulate entry list you should add that list to your state. Then when you want to show/hide specific item, you need to find that item in state and correctly update entry list by making a copy of that list (with updated item). For example you can do it like this:

import React, { useState } from 'react';

const Skills = () => {
  const [skills, setSkills] = useState([
    {
      id: 1,
      desc: 'HTML5',
      state: false,
      img: htmlIcon, // your icon
    },
    {
      id: 2,
      desc: 'CSS3',
      state: false,
      img: cssIcon, // your icon
    },
  ]);

  const showDesc = (id) => {
    const newSkills = skills.map((item) => {
      if (item.id === id) {
        return {
          ...item,
          state: !item.state,
        };
      }

      return item;
    });

    setSkills(newSkills);
  };
  return (
    <div>
      {skills.map(({
        id,
        img,
        state,
        desc,
      }) => (
        <button type="button" key={id} onClick={() => showDesc(id)}>
          <img alt="img" style={state ? { display: 'none' } : { display: 'block' }} src={img} />
          <p style={state ? { display: 'block' } : { display: 'none' }}>{desc}</p>
        </button>
      ))}
    </div>
  );
};

Instead of manipulating all list, you can try to move show/hide visibility to list item itself. Create separate component for item and separate component for rendering that items. It will help you to simplify logic and make individual component responsible for it visibility.

About list rendering you can read more here

For example you can try something like this as alternative:

import React, { useState } from 'react';

const skills = [
  {
    id: 1,
    desc: 'HTML5',
    img: htmlIcon, // your icon
  },
  {
    id: 2,
    desc: 'CSS3',
    img: cssIcon, // your icon
  },
];

const SkillItem = ({
  img,
  desc = '',
}) => {
  const [visibility, setVisibility] = useState(false);

  const toggleVisibility = () => {
    setVisibility(!visibility);
  };

  const content = visibility
    ? <p>{desc}</p>
    : <img alt="img" src={img} />;

  return (
    <div>
      <button type="button" onClick={toggleVisibility}>
        {content}
      </button>
    </div>
  );
};

const SkillList = () => skills.map(({
  id,
  img,
  desc,
}) => <SkillItem img={img} desc={desc} key={id} />);


问:
Dayjs is not updating in vue v-for
In a component template I have the following code:

```<code><v-col cols="6" v-for="(value, idx) in data[workingYear].monthValues" :key="idx">
  {{ idx }}
  <v-row class="ai-center">
    <!-- Month -->
    <v-col cols="2">{{
      dayjs(idx + 1, "M").format("MMM").ucfirst()
    }}</v-col>
    <!-- Value -->
    <v-col cols="10">
      <v-text-field
        class="mt-0 pt-0"
        hide-details="auto"
        min="0"
        suffix=",00"
        type="number"
        v-model="data[workingYear].monthValues[idx]"
        :label="$t('set')"
        :prefix="getCurrency(true)"
        :ref="'monthValue' + idx"
        :rules="[rules.required, rules.invalid]"
      />
    </v-col>
  </v-row>
</v-col>
</code>```

data[workingYear].monthValues is initialized as new Array(12).fill("") so it is an array of 12 empty string elements; ucfirst() is a custom extension to String.prototype that capitalize the first char of a string.

I'm aspecting to find in the first v-col block an incremented month, but the result is the following:

So, why {{ idx }} is incremented for every cycle as aspected but the month is always January? How can I fix this?

答:
I suggest to use a computed property that returns a function which takes the index as parameter and return the month:

    <v-col cols="2">{{
      getMonth(idx)
    }}</v-col>

```
<p>script:</p>
<pre class="lang-js prettyprint-override"><code>computed:{
  getMonth(){
   return (idx)=>dayjs(`${idx + 1}`, "M").format("MMM").ucfirst()
 }
}
</code>```

Title: Dayjs is not updating in vue v-for

Body:
In a component template I have the following code:

<v-col cols="6" v-for="(value, idx) in data[workingYear].monthValues" :key="idx">
  {{ idx }}
  <v-row class="ai-center">

    <v-col cols="2">{{
      dayjs(idx + 1, "M").format("MMM").ucfirst()
    }}</v-col>

    <v-col cols="10">
      <v-text-field
        class="mt-0 pt-0"
        hide-details="auto"
        min="0"
        suffix=",00"
        type="number"
        v-model="data[workingYear].monthValues[idx]"
        :label="$t('set')"
        :prefix="getCurrency(true)"
        :ref="'monthValue' + idx"
        :rules="[rules.required, rules.invalid]"
      />
    </v-col>
  </v-row>
</v-col>

data[workingYear].monthValues is initialized as new Array(12).fill("") so it is an array of 12 empty string elements; ucfirst() is a custom extension to String.prototype that capitalize the first char of a string.

I'm aspecting to find in the first v-col block an incremented month, but the result is the following:

So, why {{ idx }} is incremented for every cycle as aspected but the month is always January? How can I fix this?

Body:
I suggest to use a computed property that returns a function which takes the index as parameter and return the month:

    <v-col cols="2">{{
      getMonth(idx)
    }}</v-col>

script:

computed:{
  getMonth(){
   return (idx)=>dayjs(`${idx + 1}`, "M").format("MMM").ucfirst()
 }
}


问:
What values are passed to the fragment shaders for inner fragments of a triangle when only having defined values per point
I have the following very basic shaders.

Vertex shader:

```<code>attribute vec4 a_foo;

varying vec4 v_foo;

void main()
{
    v_foo = a_foo;
    gl_Position =  a_foo;
}
</code>```

Fragment shader:

```<code>varying vec4 v_foo;

uniform sampler2D u_texture;

void main()
{
    gl_FragColor = texture2D(u_texture, v_foo.xy);
}
</code>```

The attribute a_foo I provide as a vector for each point. It is passed to the fragment shader as v_foo.

When my mesh consists of only single points (GL_POINTS) it is clear that I can expect v_foo to match a_foo. But what happens in case of having a triangle (GL_TRIANGLES) consisting of three points, when I have much more fragments (texels?) than points?

Will a_foo get interpolated for fragments between the fragments of the points?
Does this happen for all types of varying that I can pass between vertex and fragment shader?

答:
Each primitive is rasterized so every "visible" (not clipped) pixel of your triangle will invoke a fragment shader and pass values interpolated (because you used varying) from the 3 triangle control points based on fragment relative position to the 3 control points.

The interpolation might be linear or perspective corrected linear depends on your OpenGL pipeline settings.

For more info about rasterization of convex polygons see:

how to rasterize rotated rectangle in 2d

However gfx cards use barycentric coordinates and test all pixels inside BBOX if inside polygon or not by simple winding rule test to take advantage of parallelism...

Body:
I have the following very basic shaders.

Vertex shader:

attribute vec4 a_foo;

varying vec4 v_foo;

void main()
{
    v_foo = a_foo;
    gl_Position =  a_foo;
}

Fragment shader:

varying vec4 v_foo;

uniform sampler2D u_texture;

void main()
{
    gl_FragColor = texture2D(u_texture, v_foo.xy);
}

The attribute a_foo I provide as a vector for each point. It is passed to the fragment shader as v_foo.

When my mesh consists of only single points (GL_POINTS) it is clear that I can expect v_foo to match a_foo. But what happens in case of having a triangle (GL_TRIANGLES) consisting of three points, when I have much more fragments (texels?) than points?

Will a_foo get interpolated for fragments between the fragments of the points?
Does this happen for all types of varying that I can pass between vertex and fragment shader?


问:
dyld: Library not loaded despite correct rpath
I am debugging a problem where I am trying to link against a dylib, and set the program's rpath to a directory containing the library.

I have narrowed this to the following MWE:

```<code>> ls deps/include/spinnaker/
AVIRecorder.h    Camera.h      CameraPtr.h    Exception.h …bunch of headers
> ls deps/lib/libSpinnaker.dylib*
deps/lib/libSpinnaker.dylib  deps/lib/libSpinnaker.dylib.1.24.0.60
> cat test.cpp
#include <cstddef>
#include <Event.h>          // for CameraList
#include <CameraList.h>          // for CameraList
#include <CameraPtr.h>           // for CameraPtr
#include <ImagePtr.h>            // for ImagePtr
#include <SystemPtr.h>           // for SystemPtr

int main()
{
  const auto system_ptr = Spinnaker::System::GetInstance();

}
</code>```

I compile this with

```<code>clang++ -std=c++14 -o wat -I deps/include/spinnaker/ -L deps/lib/ -lSpinnaker -Wl,-rpath,./deps/lib test.cpp
</code>```

And thus libSpinnaker gets referenced as shown by

```<code>[…]
Load command 9
     cmd LC_UUID
 cmdsize 24
    uuid B4498482-D872-3270-AC47-102914DDBCBE
Load command 10
      cmd LC_BUILD_VERSION
  cmdsize 32
 platform 1
    minos 10.15
      sdk 10.15.6
   ntools 1
     tool 3
  version 609.8
Load command 11
      cmd LC_SOURCE_VERSION
  cmdsize 16
  version 0.0
Load command 12
       cmd LC_MAIN
   cmdsize 24
  entryoff 16224
 stacksize 0
Load command 13
          cmd LC_LOAD_DYLIB
      cmdsize 56
         name libSpinnaker.dylib.1.24.0.60 (offset 24)
   time stamp 2 Thu Jan  1 01:00:02 1970
      current version 0.0.0
compatibility version 0.0.0
Load command 14
          cmd LC_LOAD_DYLIB
      cmdsize 48
         name /usr/lib/libc++.1.dylib (offset 24)
   time stamp 2 Thu Jan  1 01:00:02 1970
      current version 902.1.0
compatibility version 1.0.0
Load command 15
          cmd LC_LOAD_DYLIB
      cmdsize 56
         name /usr/lib/libSystem.B.dylib (offset 24)
   time stamp 2 Thu Jan  1 01:00:02 1970
      current version 1281.100.1
compatibility version 1.0.0
Load command 16
          cmd LC_RPATH
      cmdsize 24
         path ./deps/lib (offset 12)
Load command 17
      cmd LC_FUNCTION_STARTS
  cmdsize 16
  dataoff 49312
 datasize 8
Load command 18
      cmd LC_DATA_IN_CODE
  cmdsize 16
  dataoff 49320
 datasize 0
</code>```

So the LC_RPATH is included, the library is present at the specified path, but still I get

```<code>dyld: Library not loaded: libSpinnaker.dylib.1.24.0.60
  Referenced from: <binary-path>
  Reason: image not found
Abort trap: 6
</code>```

when running it.

Now my observation is that @rpath is missing before the reference to libSpinnaker in the otool output – for other libraries its always there when I look at my larger cmake-based project. I would expect the line

```<code>         name @rpath/libSpinnaker.dylib.1.24.0.60 (offset 24)
</code>```

instead of what i am seeing.
I can set DYLD_LIBRARY_PATH and that'll work, but I want to bake this into the binary with the rpath  mechanism.

Question: Is the fact that @rpath is missing here indicative of a problem? And if so, how can I get it added with the compiler or CMake? If this is not the problem, what is it?

答:
```<code>install_name_tool -id @rpath/libSpinnaker.dylib.1.24.0.60 deps/lib/libSpinnaker.dylib.1.24.0.60

install_name_tool -change libSpinnaker.dylib.1.24.0.60 @rpath/libSpinnaker.dylib.1.24.0.60 wat
</code>```

You noticed that the @rpath was missing from the installed name of the library. install_name_tool is the command which allows you to change the installed pathnames, add or remove @rpaths, etc. Because of the modifications, install_name_tool should be used before codesign.  Apple documentation has an example of how to setup this type of relative structure.

Body:
I am debugging a problem where I am trying to link against a dylib, and set the program's rpath to a directory containing the library.

I have narrowed this to the following MWE:

> ls deps/include/spinnaker/
AVIRecorder.h    Camera.h      CameraPtr.h    Exception.h …bunch of headers
> ls deps/lib/libSpinnaker.dylib*
deps/lib/libSpinnaker.dylib  deps/lib/libSpinnaker.dylib.1.24.0.60
> cat test.cpp
#include <cstddef>
#include <Event.h>          // for CameraList
#include <CameraList.h>          // for CameraList
#include <CameraPtr.h>           // for CameraPtr
#include <ImagePtr.h>            // for ImagePtr
#include <SystemPtr.h>           // for SystemPtr

int main()
{
  const auto system_ptr = Spinnaker::System::GetInstance();

}

I compile this with

clang++ -std=c++14 -o wat -I deps/include/spinnaker/ -L deps/lib/ -lSpinnaker -Wl,-rpath,./deps/lib test.cpp

And thus libSpinnaker gets referenced as shown by

[…]
Load command 9
     cmd LC_UUID
 cmdsize 24
    uuid B4498482-D872-3270-AC47-102914DDBCBE
Load command 10
      cmd LC_BUILD_VERSION
  cmdsize 32
 platform 1
    minos 10.15
      sdk 10.15.6
   ntools 1
     tool 3
  version 609.8
Load command 11
      cmd LC_SOURCE_VERSION
  cmdsize 16
  version 0.0
Load command 12
       cmd LC_MAIN
   cmdsize 24
  entryoff 16224
 stacksize 0
Load command 13
          cmd LC_LOAD_DYLIB
      cmdsize 56
         name libSpinnaker.dylib.1.24.0.60 (offset 24)
   time stamp 2 Thu Jan  1 01:00:02 1970
      current version 0.0.0
compatibility version 0.0.0
Load command 14
          cmd LC_LOAD_DYLIB
      cmdsize 48
         name /usr/lib/libc++.1.dylib (offset 24)
   time stamp 2 Thu Jan  1 01:00:02 1970
      current version 902.1.0
compatibility version 1.0.0
Load command 15
          cmd LC_LOAD_DYLIB
      cmdsize 56
         name /usr/lib/libSystem.B.dylib (offset 24)
   time stamp 2 Thu Jan  1 01:00:02 1970
      current version 1281.100.1
compatibility version 1.0.0
Load command 16
          cmd LC_RPATH
      cmdsize 24
         path ./deps/lib (offset 12)
Load command 17
      cmd LC_FUNCTION_STARTS
  cmdsize 16
  dataoff 49312
 datasize 8
Load command 18
      cmd LC_DATA_IN_CODE
  cmdsize 16
  dataoff 49320
 datasize 0

So the LC_RPATH is included, the library is present at the specified path, but still I get

dyld: Library not loaded: libSpinnaker.dylib.1.24.0.60
  Referenced from: <binary-path>
  Reason: image not found
Abort trap: 6

when running it.

Now my observation is that @rpath is missing before the reference to libSpinnaker in the otool output – for other libraries its always there when I look at my larger cmake-based project. I would expect the line

         name @rpath/libSpinnaker.dylib.1.24.0.60 (offset 24)

instead of what i am seeing.
I can set DYLD_LIBRARY_PATH and that'll work, but I want to bake this into the binary with the rpath  mechanism.

Question: Is the fact that @rpath is missing here indicative of a problem? And if so, how can I get it added with the compiler or CMake? If this is not the problem, what is it?

Body:
install_name_tool -id @rpath/libSpinnaker.dylib.1.24.0.60 deps/lib/libSpinnaker.dylib.1.24.0.60

install_name_tool -change libSpinnaker.dylib.1.24.0.60 @rpath/libSpinnaker.dylib.1.24.0.60 wat

You noticed that the @rpath was missing from the installed name of the library. install_name_tool is the command which allows you to change the installed pathnames, add or remove @rpaths, etc. Because of the modifications, install_name_tool should be used before codesign.  Apple documentation has an example of how to setup this type of relative structure.


问:
Escape ampersand in PL/SQL Developer
I'm trying a simple INSERT statement against an Oracle database.  One of the values is a VARCHAR2 field and the insert statement contains an ampersand.  How do I do this?  I've tried the following methods:

Escape the & as \& with set escape on

set scan off (this causes an ORA-00922 missing or invalid option error)

set define off (this causes an ORA-00922 missing or invalid option error)

Any other ideas?

答:
One of the features of PL/SQL Developer which it takes time to get familiar with is the plethora of different window types.

One of these is the COMMAND window, which is basically a SQL*Plus emulator.  We can run SQL*Plus commands as well as SQL, so SET ESCAPE, SET DEFINE  and indeed SET SCAN OFF work in that window.

Title: Escape ampersand in PL/SQL Developer


问:
How to pass api data from one method to another within an object?
I made a simple oject called 'weather' that has method inside.
The weather object should have three methods.

getWeather: Get weather data which is getWeather method which uses xmlhttprequest api to pull weather info and pass the weatherdata which is xhr.responseText to another method (callback) so that in the second method, I can destructure the weather data and save them to variables.

callback: Like explained, the callback method should get data from the getWeather method. However, i get an error saying "uncaught TypeError: callBack is not a function at XMLHttpRequest.xhr.onload".

search is there to pass the function to the getWeather method when the eventListener is fired when clicked.

In summary, I just want to extract data from the getWeather method and pass that data to the callback

I want to do this without fetch.then or without promisifying my xmlhttprequest.

```<code>let weather = {

apiKey:'dcaa6d5ea6bc87524fd5e38257edabba',
city: 'montreal',

getWeather: function (city, callBack) {
    const xhr = new XMLHttpRequest();
    xhr.open(
        'get'
        ,`https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${this.apiKey}`
        , true)

        xhr.onload = function () {
        if (xhr.status >= 200 && xhr.status < 300) {
            const weatherData = JSON.parse(xhr.responseText);
            // console.log(weatherData);
            console.log(weatherData);
            callBack()
        }

    }
    xhr.send()
},

callback: function () {
    console.log('weatherData')
},

search: function () {
    this.getWeather('new york')
}

</code>```

};

```<code>document
.querySelector('.button')
.addEventListener('click', () => weather.search())
</code>```

答:
The error is caused because the JavaScript engine cannot resolve what the value of the callback parameter of getWeather is when it is invoked in weather.search and also when the function you assigned to xhr.onload is eventually invoked when the request completes successfully.

There are several ways you can make sure the callback parameter or variable successfully resolves to the callback method of the weather object, which appears to be what you intended.

One: By supplying the argument for getWeather's second parameter: callback or by using default parameter value syntax to give that parameter a fallback value if it isn't supplied.

```<code>let weather = {

    apiKey:'dcaa6d5ea6bc87524fd5e38257edabba',
    city: 'montreal',

    getWeather: function (city, callback = this.callback) {
        const xhr = new XMLHttpRequest();
        xhr.open(
            'get',
            'https://randomuser.me/api/'
    // There is a 401 error interpreted as unauthorized for the api below, thus why the above api is used to test
    //         ,`https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${this.apiKey}`
            , true)

            xhr.onload = function () {
                if (xhr.status >= 200 && xhr.status < 300) {
                    const weatherData = JSON.parse(xhr.responseText);
                    callback(weatherData)
                }

            }
        xhr.send()
    },

    callback: function (weatherData) {
        console.log(weatherData)
    },

    search: function () {
        this.getWeather('new york', this.callback);
        // the below also works
        //this.getWeather('new york');
    }

}
</code>```

Two: By eager supply of some or all arguments of a function prior to invoking it via the engine provisioned closure method called bind on Function prototype.

In your case, a single parameter can be supplied to getWeather: which is city while a new parameter is given to the function assigned to xhr.onload, and that can be supplied a hard argument of this.callback by using Function.prototype.bind.

```<code>let weather = {

    apiKey:'dcaa6d5ea6bc87524fd5e38257edabba',
    city: 'montreal',

    getWeather: function (city) {
        const xhr = new XMLHttpRequest();
        xhr.open(
            'get',
            'https://randomuser.me/api/'
    // There is a 401 error interpreted as unauthorized for the api below, thus why the above api is used to test
    //         ,`https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${this.apiKey}`
            , true)

            xhr.onload = function (xhrCallback) {
                if (xhr.status >= 200 && xhr.status < 300) {
                    const weatherData = JSON.parse(xhr.responseText);
                    xhrCallback(weatherData)
                }

            }.bind(null, this.callback)
        xhr.send()
    },

    callback: function (weatherData) {
        console.log(weatherData)
    },

    search: function () {
        this.getWeather('new york')
    }

}
</code>```

Finally, note that I had to use a randomuser api because the api in your question is not authorizing and you can swap it in back as needed.

Body:
I made a simple oject called 'weather' that has method inside.
The weather object should have three methods.

getWeather: Get weather data which is getWeather method which uses xmlhttprequest api to pull weather info and pass the weatherdata which is xhr.responseText to another method (callback) so that in the second method, I can destructure the weather data and save them to variables.

callback: Like explained, the callback method should get data from the getWeather method. However, i get an error saying "uncaught TypeError: callBack is not a function at XMLHttpRequest.xhr.onload".

search is there to pass the function to the getWeather method when the eventListener is fired when clicked.

In summary, I just want to extract data from the getWeather method and pass that data to the callback

I want to do this without fetch.then or without promisifying my xmlhttprequest.

let weather = {

apiKey:'dcaa6d5ea6bc87524fd5e38257edabba',
city: 'montreal',

getWeather: function (city, callBack) {
    const xhr = new XMLHttpRequest();
    xhr.open(
        'get'
        ,`https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${this.apiKey}`
        , true)

        xhr.onload = function () {
        if (xhr.status >= 200 && xhr.status < 300) {
            const weatherData = JSON.parse(xhr.responseText);
            // console.log(weatherData);
            console.log(weatherData);
            callBack()
        }

    }
    xhr.send()
},

callback: function () {
    console.log('weatherData')
},

search: function () {
    this.getWeather('new york')
}

};

document
.querySelector('.button')
.addEventListener('click', () => weather.search())

Body:
The error is caused because the JavaScript engine cannot resolve what the value of the callback parameter of getWeather is when it is invoked in weather.search and also when the function you assigned to xhr.onload is eventually invoked when the request completes successfully.

There are several ways you can make sure the callback parameter or variable successfully resolves to the callback method of the weather object, which appears to be what you intended.

One: By supplying the argument for getWeather's second parameter: callback or by using default parameter value syntax to give that parameter a fallback value if it isn't supplied.

let weather = {

    apiKey:'dcaa6d5ea6bc87524fd5e38257edabba',
    city: 'montreal',

    getWeather: function (city, callback = this.callback) {
        const xhr = new XMLHttpRequest();
        xhr.open(
            'get',
            'https://randomuser.me/api/'
    // There is a 401 error interpreted as unauthorized for the api below, thus why the above api is used to test
    //         ,`https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${this.apiKey}`
            , true)

            xhr.onload = function () {
                if (xhr.status >= 200 && xhr.status < 300) {
                    const weatherData = JSON.parse(xhr.responseText);
                    callback(weatherData)
                }

            }
        xhr.send()
    },

    callback: function (weatherData) {
        console.log(weatherData)
    },

    search: function () {
        this.getWeather('new york', this.callback);
        // the below also works
        //this.getWeather('new york');
    }

}

Two: By eager supply of some or all arguments of a function prior to invoking it via the engine provisioned closure method called bind on Function prototype.

In your case, a single parameter can be supplied to getWeather: which is city while a new parameter is given to the function assigned to xhr.onload, and that can be supplied a hard argument of this.callback by using Function.prototype.bind.

let weather = {

    apiKey:'dcaa6d5ea6bc87524fd5e38257edabba',
    city: 'montreal',

    getWeather: function (city) {
        const xhr = new XMLHttpRequest();
        xhr.open(
            'get',
            'https://randomuser.me/api/'
    // There is a 401 error interpreted as unauthorized for the api below, thus why the above api is used to test
    //         ,`https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${this.apiKey}`
            , true)

            xhr.onload = function (xhrCallback) {
                if (xhr.status >= 200 && xhr.status < 300) {
                    const weatherData = JSON.parse(xhr.responseText);
                    xhrCallback(weatherData)
                }

            }.bind(null, this.callback)
        xhr.send()
    },

    callback: function (weatherData) {
        console.log(weatherData)
    },

    search: function () {
        this.getWeather('new york')
    }

}

Finally, note that I had to use a randomuser api because the api in your question is not authorizing and you can swap it in back as needed.


问:
Adding some value on top of stacked barplot - Bars disappear when defining aes(y) in geom_text
I want to produce a stacked barplot and the percentage change between the years on top of the stacked bars.

My data:

```<code>my_data <- structure(list(year = c(2016, 2016, 2016, 2016, 2017, 2017, 2017,
2017, 2018, 2018, 2018, 2018, 2019, 2019, 2019, 2019, 2020, 2020,
2020, 2020, 2021, 2021, 2021, 2021), some_data = c(700.884929,
123.61278, 91.331399, 5.800863, 709.664147, 5.255171, 125.568917,
94.289424, 721.353624, 2.440006, 130.295319, 96.372448, 726.963262,
0.875374, 129.695907, 97.54507, 764.370595, 0.876399, 126.677571,
105.180633, 801.974246, 0.787544, 131.254017, 109.521045), some_letters = c("B",
"A", "D", "C", "B", "C", "A", "D", "B", "C", "A", "D", "B", "C",
"A", "D", "B", "C", "A", "D", "B", "C", "A", "D")), row.names = c(NA,
-24L), class = c("tbl_df", "tbl", "data.frame"))
</code>```

Percentage change information:

```<code>for_label <- structure(list(year = c(2016, 2017, 2018, 2019, 2020, 2021),
    pct_change = c(NA, 0.0142656905848388, 0.0167780411191876,
    0.00485892011456412, 0.0440021799523009, 0.0465664546661004
    ), my_pos = c(921629971, 934777659, 950461397, 955079613,
    997105198, 1043536852)), row.names = c(NA, -6L), class = c("tbl_df",
"tbl", "data.frame"))
</code>```

Now I try to plot the data and add the percentages:

```<code>library(tidyverse)

my_data %>%
  ggplot(aes(x = year, y = some_data, fill = some_letters))+
  geom_bar(position = "stack", stat = "identity") +
  scale_x_continuous(breaks = 2016:2021)+
  geom_text(
    data = for_label,
    aes(x = year, y = pct_change, label = percent(pct_change), fill = NULL),
    position = "stack")
</code>```

However, the values are on on the bottom of the plot:

Alternatively I change the pct_change to my_pos in geom_text(aes(y = )). Then I get the percentages at the right position but the bars disappear. How to solve this problem? I tried to play around with position = position_stack() but never got it to work.

答:
I'll first combine my_data and for_label into a single dataframe before plotting, then they can use the same data in ggplot.

This method will give labels in every stacked portion of some_letters, we can use a ifelse statement to only include label for A so that the labels are on top.

```<code>left_join(my_data, for_label, by = "year") %>%
  ggplot(aes(x = year, y = some_data, fill = some_letters))+
  geom_bar(position = "stack", stat = "identity") +
  scale_x_continuous(breaks = 2016:2021)+
  geom_text(aes(label = ifelse(some_letters == "A", percent(pct_change), NA), fill = NULL),
    position = "stack", check_overlap = T, vjust = -4)
</code>```

Body:
I want to produce a stacked barplot and the percentage change between the years on top of the stacked bars.

My data:

my_data <- structure(list(year = c(2016, 2016, 2016, 2016, 2017, 2017, 2017,
2017, 2018, 2018, 2018, 2018, 2019, 2019, 2019, 2019, 2020, 2020,
2020, 2020, 2021, 2021, 2021, 2021), some_data = c(700.884929,
123.61278, 91.331399, 5.800863, 709.664147, 5.255171, 125.568917,
94.289424, 721.353624, 2.440006, 130.295319, 96.372448, 726.963262,
0.875374, 129.695907, 97.54507, 764.370595, 0.876399, 126.677571,
105.180633, 801.974246, 0.787544, 131.254017, 109.521045), some_letters = c("B",
"A", "D", "C", "B", "C", "A", "D", "B", "C", "A", "D", "B", "C",
"A", "D", "B", "C", "A", "D", "B", "C", "A", "D")), row.names = c(NA,
-24L), class = c("tbl_df", "tbl", "data.frame"))

Percentage change information:

for_label <- structure(list(year = c(2016, 2017, 2018, 2019, 2020, 2021),
    pct_change = c(NA, 0.0142656905848388, 0.0167780411191876,
    0.00485892011456412, 0.0440021799523009, 0.0465664546661004
    ), my_pos = c(921629971, 934777659, 950461397, 955079613,
    997105198, 1043536852)), row.names = c(NA, -6L), class = c("tbl_df",
"tbl", "data.frame"))

Now I try to plot the data and add the percentages:

library(tidyverse)

my_data %>%
  ggplot(aes(x = year, y = some_data, fill = some_letters))+
  geom_bar(position = "stack", stat = "identity") +
  scale_x_continuous(breaks = 2016:2021)+
  geom_text(
    data = for_label,
    aes(x = year, y = pct_change, label = percent(pct_change), fill = NULL),
    position = "stack")

However, the values are on on the bottom of the plot:

Alternatively I change the pct_change to my_pos in geom_text(aes(y = )). Then I get the percentages at the right position but the bars disappear. How to solve this problem? I tried to play around with position = position_stack() but never got it to work.

Body:
I'll first combine my_data and for_label into a single dataframe before plotting, then they can use the same data in ggplot.

This method will give labels in every stacked portion of some_letters, we can use a ifelse statement to only include label for A so that the labels are on top.

left_join(my_data, for_label, by = "year") %>%
  ggplot(aes(x = year, y = some_data, fill = some_letters))+
  geom_bar(position = "stack", stat = "identity") +
  scale_x_continuous(breaks = 2016:2021)+
  geom_text(aes(label = ifelse(some_letters == "A", percent(pct_change), NA), fill = NULL),
    position = "stack", check_overlap = T, vjust = -4)


问:
How to lock wellpanel/sidebar vertically but not horizontally? rShiny
So I have a wellpanel thats serving as a sidebar that I want fixed when I scroll down vertically but that I want to "disapear"/ move to the side when I scroll horizontally.

Currently I have the vertical part down, but when I scroll horizontally the wellpanel merges with my datatable.

My code:

```<code>column(2,
 wellPanel(style = "position: fixed;",
                                                            dateInput(inputId = "cpayReconstrtdate", label = "Start Date",  value = (Sys.Date() - days(10))),
                                                            dateInput(inputId = "cpayReconenddate", label = "End Date"),
                                                            checkboxInput(inputId = "cpayReconCheck", label = "Filter by Date?"),
                                                            checkboxInput(inputId = "cpfailed", label = "Include Failed Transactions?"),
                                                            checkboxInput(inputId = "cpayAnomFilter", label = "Filter by Anomalies?"),
                                                            actionButton(inputId = "cpayReconFilterBTN", label = "Filter"),
                                                            downloadButton("cpayReconDownload")
                                                            )
                                                   ),
                                            column(10,
                                                   dataTableOutput("CPTable")
                                                   )
</code>```

Here is an image of the problem:

As you can see the wellpanel is fixed but when I scrolled horizontally to view the rest of the datatable it clipped in.

So is there any way to lock the wellpanel vertically but not horizontally?

答:
Solved it by wrapping everything in a div with display:flex and adding position sticky to the wellpanel.</p>
```<code>div(style = "display: flex",
                                            column(2,
                                                   wellPanel(style = "position: sticky; top: 100px",
                                                            dateInput(inputId = "cpayReconstrtdate", label = "Start Date",  value = (Sys.Date() - days(10))),
                                                            dateInput(inputId = "cpayReconenddate", label = "End Date"),
                                                            checkboxInput(inputId = "cpayReconCheck", label = "Filter by Date?"),
                                                            checkboxInput(inputId = "cpfailed", label = "Include Failed Transactions?"),
                                                            checkboxInput(inputId = "cpayAnomFilter", label = "Filter by Anomalies?"),
                                                            actionButton(inputId = "cpayReconFilterBTN", label = "Filter"),
                                                            downloadButton("cpayReconDownload")
                                                            )
                                                   ),
                                            column(10,
                                                   dataTableOutput("CPTable")
                                                   )
                                            )
                                            ),
</code>```

Body:
So I have a wellpanel thats serving as a sidebar that I want fixed when I scroll down vertically but that I want to "disapear"/ move to the side when I scroll horizontally.

Currently I have the vertical part down, but when I scroll horizontally the wellpanel merges with my datatable.

My code:

column(2,
 wellPanel(style = "position: fixed;",
                                                            dateInput(inputId = "cpayReconstrtdate", label = "Start Date",  value = (Sys.Date() - days(10))),
                                                            dateInput(inputId = "cpayReconenddate", label = "End Date"),
                                                            checkboxInput(inputId = "cpayReconCheck", label = "Filter by Date?"),
                                                            checkboxInput(inputId = "cpfailed", label = "Include Failed Transactions?"),
                                                            checkboxInput(inputId = "cpayAnomFilter", label = "Filter by Anomalies?"),
                                                            actionButton(inputId = "cpayReconFilterBTN", label = "Filter"),
                                                            downloadButton("cpayReconDownload")
                                                            )
                                                   ),
                                            column(10,
                                                   dataTableOutput("CPTable")
                                                   )

Here is an image of the problem:

As you can see the wellpanel is fixed but when I scrolled horizontally to view the rest of the datatable it clipped in.

So is there any way to lock the wellpanel vertically but not horizontally?

Body:
Solved it by wrapping everything in a div with display:flex and adding position sticky to the wellpanel.

div(style = "display: flex",
                                            column(2,
                                                   wellPanel(style = "position: sticky; top: 100px",
                                                            dateInput(inputId = "cpayReconstrtdate", label = "Start Date",  value = (Sys.Date() - days(10))),
                                                            dateInput(inputId = "cpayReconenddate", label = "End Date"),
                                                            checkboxInput(inputId = "cpayReconCheck", label = "Filter by Date?"),
                                                            checkboxInput(inputId = "cpfailed", label = "Include Failed Transactions?"),
                                                            checkboxInput(inputId = "cpayAnomFilter", label = "Filter by Anomalies?"),
                                                            actionButton(inputId = "cpayReconFilterBTN", label = "Filter"),
                                                            downloadButton("cpayReconDownload")
                                                            )
                                                   ),
                                            column(10,
                                                   dataTableOutput("CPTable")
                                                   )
                                            )
                                            ),


问:
What is the best way to hide some of the content in my gallery without utilizing java script?
i am currently using a java script show more hide less button but the problem i cant use the same button in same page i did change the id and still didn't work for me i might missed up with java cause i am not that expert but the thing i want somthing different than java script to have same functionaliy with the one i am using now also i want it to work perfectly on col grid so i dont want want the order to be messed up thanks a lot for any help

function toggleText() {
    var showMoreText = document.getElementById("more");
    var buttonText = document.querySelector("#moreButton span");
    var moreIcon = document.querySelector("#moreButton img");

    if (startpoint.style.display === "none") {
        showMoreText.style.display = "none";
        startpoint.style.display = "table-cell";
        buttonText.innerHTML = "Show More";
        buttonText.classList.remove('less');
        moreIcon.classList.remove('less');
    } else {
        showMoreText.style.display = "table-cell";
        startpoint.style.display = "none";
        buttonText.innerHTML = "Show Less";
        buttonText.classList.add('less');
        moreIcon.classList.add('less');
    }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.pink{
  color: #FF7B5F;
}

#more {
  display: none;
}
#moreButton{
  background-color:transparent;
  border-color: transparent;
}
.less{
  color: #FF7B5F;
}

img.more.less {
  transform: rotate(180deg);
}</code>```

<!DOCTYPE html>

      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Welcome to My Homepage</title>
      <link rel="stylesheet" href="https://unpkg.com/aos@next/dist/aos.css" />
      <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
      <link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous"/>

      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/assets/owl.carousel.min.css">
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/assets/owl.theme.default.css">
      <link rel="stylesheet" href="./css/style01.css">

                  <button onclick="toggleText()" id="moreButton">
                  Show More

                  </button>

```

答:
There is a very basic Show/Hide function in Bootstrap with no need at all for extra JS. The feature is called Collapse. Here is the most basic version of it which you can copy over to your page (as long as you are calling Bootstrap 5 JS too)....

```<code><p>
  <a class="btn btn-primary" data-bs-toggle="collapse" href="#collapseExample"
  role="button" aria-expanded="false" aria-controls="collapseExample">
  Show/Hide
  </a>
</p>

<div class="collapse" id="collapseExample">
  <div class="card card-body">
    This panel is hidden by default but revealed when the user activates the Show/Hide link above.
  </div>
</div>
</code>```

And here are the docs if you want to add more or edit a little. https://getbootstrap.com/docs/5.0/components/collapse/

Body:
i am currently using a java script show more hide less button but the problem i cant use the same button in same page i did change the id and still didn't work for me i might missed up with java cause i am not that expert but the thing i want somthing different than java script to have same functionaliy with the one i am using now also i want it to work perfectly on col grid so i dont want want the order to be messed up thanks a lot for any help

function toggleText() {
    var showMoreText = document.getElementById("more");
    var buttonText = document.querySelector("#moreButton span");
    var moreIcon = document.querySelector("#moreButton img");

    if (startpoint.style.display === "none") {
        showMoreText.style.display = "none";
        startpoint.style.display = "table-cell";
        buttonText.innerHTML = "Show More";
        buttonText.classList.remove('less');
        moreIcon.classList.remove('less');
    } else {
        showMoreText.style.display = "table-cell";
        startpoint.style.display = "none";
        buttonText.innerHTML = "Show Less";
        buttonText.classList.add('less');
        moreIcon.classList.add('less');
    }
}

.pink{
  color: #FF7B5F;
}

#more {
  display: none;
}
#moreButton{
  background-color:transparent;
  border-color: transparent;
}
.less{
  color: #FF7B5F;
}

img.more.less {
  transform: rotate(180deg);
}

<!DOCTYPE html>

      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Welcome to My Homepage</title>
      <link rel="stylesheet" href="https://unpkg.com/aos@next/dist/aos.css" />
      <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
      <link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous"/>

      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/assets/owl.carousel.min.css">
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/assets/owl.theme.default.css">
      <link rel="stylesheet" href="./css/style01.css">

                  <button onclick="toggleText()" id="moreButton">
                  Show More

                  </button>

Body:
There is a very basic Show/Hide function in Bootstrap with no need at all for extra JS. The feature is called Collapse. Here is the most basic version of it which you can copy over to your page (as long as you are calling Bootstrap 5 JS too)....

<p>
  <a class="btn btn-primary" data-bs-toggle="collapse" href="#collapseExample"
  role="button" aria-expanded="false" aria-controls="collapseExample">
  Show/Hide
  </a>
</p>

<div class="collapse" id="collapseExample">
  <div class="card card-body">
    This panel is hidden by default but revealed when the user activates the Show/Hide link above.
  </div>
</div>

And here are the docs if you want to add more or edit a little. https://getbootstrap.com/docs/5.0/components/collapse/


问:
Unresolved Reference in Kotlin for an Interface defined in Base Class when addressed using Child Class
Hi I am trying to address an interface "CallbackTest" which is defined in my AudioBase.java using AudioChild.java which inherits the AudioBase.java. But it gives compilation error of Unresolved reference when trying to do so.

Here are my class definitions:

AudioBase.java

```<code>package com.testapp.kotlinexample.classes;

public class AudioBase {

    public interface CallbackTest {
        void onCall(int var1);
    }

}
</code>```

Child Class AudioChild.java

```<code>package com.testapp.kotlinexample.classes;

import android.util.Log;

public class AudioChild extends AudioBase{

    private static final String TAG = "AudioChild";

    public void someOtherMethod() {
        Log.i(TAG, "in someOtherMethod()");
    }

}
</code>```

MainActivity.kt

```<code>import android.content.Context
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.testapp.kotlinexample.classes.AudioChild

class MainActivity : AppCompatActivity() {

    private val TAG = "TestApp"
    private var mContext: Context? = null
    private val stateCallback =
        AudioChild.CallbackTest { // Compilation error on this line
            Log.i(TAG, "onCall:() called")
        }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        mContext = applicationContext
    }
}
</code>```

When I use AudioChild.CallbackTest I get below compilation error:

Unresolved reference: CallbackTest

Can someone please help me understand why this error is coming?

答:
I'm not an expert in kotlin but I know java and googled a bit:

Kotlin: How can I create a "static" inheritable function?

Static methods (and it appears class/interface definitions) are not inherited.

Basically only instance (non-static) members are inherited. Everything statically (class-based) referenced will have to use the class prefix they are defined in.

In this case:

```<code>private val stateCallback =
    AudioBase.CallbackTest {
        Log.i(TAG, "onCall:() called")
</code>```

Body:
Hi I am trying to address an interface "CallbackTest" which is defined in my AudioBase.java using AudioChild.java which inherits the AudioBase.java. But it gives compilation error of Unresolved reference when trying to do so.

Here are my class definitions:

AudioBase.java

package com.testapp.kotlinexample.classes;

public class AudioBase {

    public interface CallbackTest {
        void onCall(int var1);
    }

}

Child Class AudioChild.java

package com.testapp.kotlinexample.classes;

import android.util.Log;

public class AudioChild extends AudioBase{

    private static final String TAG = "AudioChild";

    public void someOtherMethod() {
        Log.i(TAG, "in someOtherMethod()");
    }

}

MainActivity.kt

import android.content.Context
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.testapp.kotlinexample.classes.AudioChild

class MainActivity : AppCompatActivity() {

    private val TAG = "TestApp"
    private var mContext: Context? = null
    private val stateCallback =
        AudioChild.CallbackTest { // Compilation error on this line
            Log.i(TAG, "onCall:() called")
        }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        mContext = applicationContext
    }
}

When I use AudioChild.CallbackTest I get below compilation error:

Unresolved reference: CallbackTest

Can someone please help me understand why this error is coming?

Body:
I'm not an expert in kotlin but I know java and googled a bit:

Kotlin: How can I create a "static" inheritable function?

Static methods (and it appears class/interface definitions) are not inherited.

Basically only instance (non-static) members are inherited. Everything statically (class-based) referenced will have to use the class prefix they are defined in.

In this case:

private val stateCallback =
    AudioBase.CallbackTest {
        Log.i(TAG, "onCall:() called")


问:
ASP.NET Storing global variables - accessible from every page
I am building a large application and I ususally use a simple session to store private  global information however as the application could be rather large I belive this could be a problem due to the amount of memory sessions it could have.

Is there a better way to store such variables?

For example, when the user logs in I want to store data about that user and display it where needed without having to query the database each time.

答: You might use Cache. That has built-in mechanism to free up when memory is running out...</p>

OwnerDisplayName: HenryH

LastEditorDisplayName: Rich B

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Rashack


问:
How do I verify that an Android apk is signed with a release certificate?
How can I check that an Android apk is signed with a release and not debug cert?</p>

答:
Use this command, (go to java < jdk < bin path in cmd prompt)

```<code>$ jarsigner -verify -verbose -certs my_application.apk
</code>```

If you see "CN=Android Debug", this means the .apk was signed with the debug key generated by the Android SDK
(means it is unsigned), otherwise you will find something for CN.
For more details see: http://developer.android.com/guide/publishing/app-signing.html

Body:
Use this command, (go to java < jdk < bin path in cmd prompt)

$ jarsigner -verify -verbose -certs my_application.apk

If you see "CN=Android Debug", this means the .apk was signed with the debug key generated by the Android SDK
(means it is unsigned), otherwise you will find something for CN.
For more details see: http://developer.android.com/guide/publishing/app-signing.html


问:
Default.aspx vs. Index.aspx
I've been using Index.aspx as the 'home' file of my web applications directories for the past 5 years, but have only just recently started using Visual Studio for debugging sites.

The built in web server for Visual Studio has Default.aspx as the 'home' file.

When I click on a link such as /News?id=5, its not picking up on the Index.aspx file, and instead showing a directory listing.

This causes an issue because I'm sometimes passing querystring, which is then lost when going to the directory listing.

Therefore, should I cave in and do what Microsoft tells me, and use Default.aspx?

Is this what all other ASP.NET web developers do?

答:
I think you can set this up in the web.config file.

[CORRECTION]: What I was thinking of is actually the  section, which allows to setup 404 pages. You may use that to redirect to Index, but it might not be "good practice".

Hah, amazingly enough, somebody already asked almost the same question, and even another closely related one, that you probably may use to solve your issue.

You can also write an XML SiteMap file to setup Index.aspx as your toplevel page.

As per convention, as stated in my comment, ASPX.NET convention is to name the pages by the name of their controller's action method, such as Index.aspx, however all examples in the MS70-515 book are based on Default.aspx. My personal opinion therefore would be to use Default.aspx.

Title: Default.aspx vs. Index.aspx


问:
Cannot disable "white-space: nowrap;" on html div
On my website app, I have a logger window. In that window, I have table rows with divs inside.

I was able to crop long sentences for users. What I want is, when one hovers an item, it will show all sentences of that item.

It actually works for the last item. But why it does not work for the first item?

.TGC_LibBootGUIDebug {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.TGC_LibBootGUIDebug:hover {
  overflow: visible;
  white-space: normal;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tbody>
    <tr>
      <td>
        <div class="TGC_LibBootGUIDebug">- Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce vel commodo justo. Aenean vitae tellus vitae libero scelerisque tincidunt eu facilisis tellus. In tincidunt in mi in semper. Vivamus fermentum massa sagittis ullamcorper pulvinar. Ut id volutpat lectus. Nulla eget vulputate orci, id efficitur mauris. Donec lacinia consequat tortor vitae finibus. Phasellus a sem quis arcu iaculis finibus. Quisque tristique, purus ac sollicitudin efficitur, quam libero luctus massa, eget congue urna tellus ut dui.
        </div>
      </td>
    </tr>
    <tr>
      <td>
        <div class="TGC_LibBootGUIDebug">- Ut accumsan mattis eros ac hendrerit. Interdum et malesuada fames ac ante ipsum primis in faucibus. Aenean condimentum massa et vestibulum vestibulum. Aenean ac imperdiet arcu. Duis quis elit nibh. Nam tortor nunc, tristique eget dolor eu, placerat accumsan ligula. Mauris at odio cursus, scelerisque lectus nec, interdum erat. Sed facilisis ex vitae magna mattis dictum. Praesent molestie eros id diam sagittis pharetra. Donec sit amet tellus sem. Nullam iaculis nulla sit amet tellus bibendum, vel congue leo commodo. Cras accumsan imperdiet lorem, quis dictum arcu interdum a. In sollicitudin lacinia libero, sit amet accumsan enim mattis vitae.
        </div>
      </td>
    </tr>
  </tbody>
</table></code>```

答:
you have to set a width on your TGC_LibBootGUIDebug to make running the white-space correctly

- Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce vel commodo justo. Aenean vitae tellus vitae libero scelerisque tincidunt eu facilisis tellus. In tincidunt in mi in semper. Vivamus fermentum massa sagittis ullamcorper pulvinar. Ut id volutpat lectus. Nulla eget vulputate orci, id efficitur mauris. Donec lacinia consequat tortor vitae finibus. Phasellus a sem quis arcu iaculis finibus. Quisque tristique, purus ac sollicitudin efficitur, quam libero luctus massa, eget congue urna tellus ut dui.

- Ut accumsan mattis eros ac hendrerit. Interdum et malesuada fames ac ante ipsum primis in faucibus. Aenean condimentum massa et vestibulum vestibulum. Aenean ac imperdiet arcu. Duis quis elit nibh. Nam tortor nunc, tristique eget dolor eu, placerat accumsan ligula. Mauris at odio cursus, scelerisque lectus nec, interdum erat. Sed facilisis ex vitae magna mattis dictum. Praesent molestie eros id diam sagittis pharetra. Donec sit amet tellus sem. Nullam iaculis nulla sit amet tellus bibendum, vel congue leo commodo. Cras accumsan imperdiet lorem, quis dictum arcu interdum a. In sollicitudin lacinia libero, sit amet accumsan enim mattis vitae.

```

Body:
On my website app, I have a logger window. In that window, I have table rows with divs inside.

I was able to crop long sentences for users. What I want is, when one hovers an item, it will show all sentences of that item.

It actually works for the last item. But why it does not work for the first item?

.TGC_LibBootGUIDebug {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.TGC_LibBootGUIDebug:hover {
  overflow: visible;
  white-space: normal;
}

- Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce vel commodo justo. Aenean vitae tellus vitae libero scelerisque tincidunt eu facilisis tellus. In tincidunt in mi in semper. Vivamus fermentum massa sagittis ullamcorper pulvinar. Ut id volutpat lectus. Nulla eget vulputate orci, id efficitur mauris. Donec lacinia consequat tortor vitae finibus. Phasellus a sem quis arcu iaculis finibus. Quisque tristique, purus ac sollicitudin efficitur, quam libero luctus massa, eget congue urna tellus ut dui.

- Ut accumsan mattis eros ac hendrerit. Interdum et malesuada fames ac ante ipsum primis in faucibus. Aenean condimentum massa et vestibulum vestibulum. Aenean ac imperdiet arcu. Duis quis elit nibh. Nam tortor nunc, tristique eget dolor eu, placerat accumsan ligula. Mauris at odio cursus, scelerisque lectus nec, interdum erat. Sed facilisis ex vitae magna mattis dictum. Praesent molestie eros id diam sagittis pharetra. Donec sit amet tellus sem. Nullam iaculis nulla sit amet tellus bibendum, vel congue leo commodo. Cras accumsan imperdiet lorem, quis dictum arcu interdum a. In sollicitudin lacinia libero, sit amet accumsan enim mattis vitae.

Body:
you have to set a width on your TGC_LibBootGUIDebug to make running the white-space correctly

<style>
.TGC_LibBootGUIDebug {
    width:250px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
.TGC_LibBootGUIDebug:hover {
    overflow: visible;
    white-space: normal;
}
</style><table><tbody>
<tr><td><div class="TGC_LibBootGUIDebug">- Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce vel commodo justo. Aenean vitae tellus vitae libero scelerisque tincidunt eu facilisis tellus. In tincidunt in mi in semper. Vivamus fermentum massa sagittis ullamcorper pulvinar. Ut id volutpat lectus. Nulla eget vulputate orci, id efficitur mauris. Donec lacinia consequat tortor vitae finibus. Phasellus a sem quis arcu iaculis finibus. Quisque tristique, purus ac sollicitudin efficitur, quam libero luctus massa, eget congue urna tellus ut dui.</div></td></tr>
<tr><td><div class="TGC_LibBootGUIDebug">- Ut accumsan mattis eros ac hendrerit. Interdum et malesuada fames ac ante ipsum primis in faucibus. Aenean condimentum massa et vestibulum vestibulum. Aenean ac imperdiet arcu. Duis quis elit nibh. Nam tortor nunc, tristique eget dolor eu, placerat accumsan ligula. Mauris at odio cursus, scelerisque lectus nec, interdum erat. Sed facilisis ex vitae magna mattis dictum. Praesent molestie eros id diam sagittis pharetra. Donec sit amet tellus sem. Nullam iaculis nulla sit amet tellus bibendum, vel congue leo commodo. Cras accumsan imperdiet lorem, quis dictum arcu interdum a. In sollicitudin lacinia libero, sit amet accumsan enim mattis vitae.</div></td></tr>
</tbody></table>


问:
How to cumsum the elements of a vector under certain condition in R?
My objective is to do a cumulative sum of the elements of a vector and assign the result to each element. But when certain condition is reached, then reset the cumulative sum.

For example:

```<code>vector_A <- c(1, 1, -1, -1, -1, 1, -1, -1, 1, -1)
</code>```

Now, suppose that the condition to reset the cumulative sum is that the next element has a different sign.

Then the desired output is:

```<code>vector_B <- c(1, 2, -1, -2, -3, 1, -1, -2, 1, -1)
</code>```

How can I achieve this?

答:
A base R option with Reduce

```<code>> Reduce(function(x, y) ifelse(x * y > 0, x + y, y), vector_A, accumulate = TRUE)
 [1]  1  2 -1 -2 -3  1 -1 -2  1 -1
</code>```

or using ave + cumsum

```<code>> ave(vector_A, cumsum(c(1, diff(sign(vector_A)) != 0)), FUN = cumsum)
 [1]  1  2 -1 -2 -3  1 -1 -2  1 -1
</code>```

Body:
My objective is to do a cumulative sum of the elements of a vector and assign the result to each element. But when certain condition is reached, then reset the cumulative sum.

For example:

vector_A <- c(1, 1, -1, -1, -1, 1, -1, -1, 1, -1)

Now, suppose that the condition to reset the cumulative sum is that the next element has a different sign.

Then the desired output is:

vector_B <- c(1, 2, -1, -2, -3, 1, -1, -2, 1, -1)

How can I achieve this?

Body:
A base R option with Reduce

> Reduce(function(x, y) ifelse(x * y > 0, x + y, y), vector_A, accumulate = TRUE)
 [1]  1  2 -1 -2 -3  1 -1 -2  1 -1

or using ave + cumsum

> ave(vector_A, cumsum(c(1, diff(sign(vector_A)) != 0)), FUN = cumsum)
 [1]  1  2 -1 -2 -3  1 -1 -2  1 -1


问:
Android project build error Duplicate of android class.data binding.Database observed in data binding modules-runtime-7.0.4-runtime
When building a project in Android Studio, Duplicate of android class.data binding.Database observed in data binding modules-runtime-7.0.4-runtime,  an error appears below is an incomplete error code and gradle files of the project:

```<code>Duplicate class androidx.databinding.BaseObservableField found in modules databinding-runtime-7.0.4-runtime (androidx.databinding:databinding-runtime:7.0.4) and jetified-library-3.2.0-alpha11-runtime (androidx.databinding:library:3.2.0-alpha11) Duplicate class androidx.databinding.BaseObservableField$DependencyCallback found in modules databinding-runtime-7.0.4-runtime (androidx.databinding:databinding-runtime:7.0.4) and jetified-library-3.2.0-alpha11-runtime (androidx.databinding:library:3.2.0-alpha11)
</code>```

Duplicate class androidx.databinding.Bindable found in modules databinding-common-7.0.4 (androidx.databinding:databinding-common:7.0.4) and jetified-baseLibrary-3.2.0-alpha11 (androidx.databinding:baseLibrary:3.2.0-alpha11) Duplicate class androidx.databinding.BindingAdapter found in modules databinding-common-7.0.4 (androidx.databinding:databinding-common:7.0.4) and jetified-baseLibrary-3.2.0-alpha11 (androidx.databinding:baseLibrary:3.2.0-alpha11) Duplicate class androidx.databinding.BindingBuildInfo found in modules databinding-common-7.0.4 (androidx.databinding:databinding-common:7.0.4) and jetified-baseLibrary-3.2.0-alpha11 (androidx.databinding:baseLibrary:3.2.0-alpha11) Duplicate class androidx.databinding.BindingConversion found in modules databinding-common-7.0.4 (androidx.databinding:databinding-common:7.0.4) and jetified-baseLibrary-3.2.0-alpha11 (androidx.databinding:baseLibrary:3.2.0-alpha11) Duplicate class androidx.databinding.BindingMethod found in modules databinding-common-7.0.4 (androidx.databinding:databinding-common:7.0.4) and jetified-baseLibrary-3.2.0-alpha11 (androidx.databinding:baseLibrary:3.2.0-alpha11) Duplicate class androidx.databinding.BindingMethods found in modules databinding-common-7.0.4 (androidx.databinding:databinding-common:7.0.4) and jetified-baseLibrary-3.2.0-alpha11 (androidx.databinding:baseLibrary:3.2.0-alpha11) Duplicate class androidx.databinding.CallbackRegistry found in modules databinding-common-7.0.4 (androidx.databinding:databinding-common:7.0.4) and jetified-baseLibrary-3.2.0-alpha11 (androidx.databinding:baseLibrary:3.2.0-alpha11) Duplicate class androidx.databinding.CallbackRegistry$NotifierCallback found in modules databinding-common-7.0.4 (androidx.databinding:databinding-common:7.0.4) and jetified-baseLibrary-3.2.0-alpha11 (androidx.databinding:baseLibrary:3.2.0-alpha11) Duplicate class androidx.databinding.DataBinderMapper found in modules databinding-runtime-7.0.4-runtime (androidx.databinding:databinding-runtime:7.0.4) and jetified-library-3.2.0-alpha11-runtime (androidx.databinding:library:3.2.0-alpha11) Duplicate class androidx.databinding.DataBindingUtil found in modules databinding-runtime-7.0.4-runtime (androidx.databinding:databinding-runtime:7.0.4) and jetified-library-3.2.0-alpha11-runtime (androidx.databinding:library:3.2.0-alpha11) Duplicate class androidx.databinding.InverseBindingAdapter found in modules databinding-common-7.0.4 (androidx.databinding:databinding-common:7.0.4) and jetified-baseLibrary-3.2.0-alpha11 (androidx.databinding:baseLibrary:3.2.0-alpha11) Duplicate class androidx.databinding.InverseBindingListener found in modules databinding-common-7.0.4 (androidx.databinding:databinding-common:7.0.4) and jetified-baseLibrary-3.2.0-alpha11 (androidx.databinding:baseLibrary:3.2.0-alpha11) Duplicate class androidx.databinding.InverseBindingMethod found in modules databinding-common-7.0.4 (androidx.databinding:databinding-common:7.0.4) and jetified-baseLibrary-3.2.0-alpha11 (androidx.databinding:baseLibrary:3.2.0-alpha11) Duplicate class androidx.databinding.InverseBindingMethods found in modules databinding-common-7.0.4 (androidx.databinding:databinding-common:7.0.4) and jetified-baseLibrary-3.2.0-alpha11 (androidx.databinding:baseLibrary:3.2.0-alpha11)....

```<code>Go to the documentation to learn how to Fix dependency resolution errors.
</code>```

Here is the Cradle(module) file:

```<code>plugins {
    id 'com.android.application'
    id 'kotlin-android'
}

android {
compileSdk 31

defaultConfig {
     applicationId "com.example.singupactivity"
     minSdk 24
     targetSdk 31
     versionCode 1
     versionName "1.0"

     testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
 }

  buildTypes {
        release {
          minifyEnabled false
           proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'),
           'proguard-rules.pro'
    }
  }
  compileOptions {
      sourceCompatibility JavaVersion.VERSION_1_8
      targetCompatibility JavaVersion.VERSION_1_8
  }
  kotlinOptions {
     jvmTarget = '1.8'
  }
   buildFeatures {
     //noinspection DataBindingWithoutKapt
     dataBinding true
  }
}

apply plugin: 'kotlin-kapt'

dependencies {

  implementation "com.github.moxy-community:moxy:2.2.2"
  kapt "com.github.moxy-community:moxy-compiler:2.2.2"

  implementation "androidx.recyclerview:recyclerview:1.3.0-alpha01"
  implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.0'
  implementation 'androidx.navigation:navigation-fragment-ktx:2.4.0-rc01'
  implementation 'androidx.navigation:navigation-ui-ktx:2.4.0-rc01'
  implementation 'com.makeramen:roundedimageview:2.3.0'
  implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
  implementation 'com.squareup.retrofit2:retrofit:2.3.0'
  implementation 'com.squareup.retrofit2:retrofit:2.3.0'
  implementation 'androidx.core:core-ktx:1.7.0'
  implementation 'androidx.appcompat:appcompat:1.4.1'
  implementation 'com.google.android.material:material:1.5.0'
  implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
  implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.4.0'
  implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.0'
  implementation 'androidx.legacy:legacy-support-v4:1.0.0'
  implementation 'androidx.test:core-ktx:1.4.0'
  implementation 'androidx.databinding:library:3.2.0-alpha11'
  testImplementation 'junit:junit:'
  androidTestImplementation 'androidx.test.ext:junit:1.1.3'
  androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

}
</code>```

Here is the Cradle(project) file:

```<code>     // Top-level build file where you can add configuration options common to all sub-
 projects/modules.
buildscript {
  repositories {
      google()
      mavenCentral()
 }
dependencies {
classpath "com.android.tools.build:gradle:7.0.4"
classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.6.10'

// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}

task clean(type: Delete) {
delete rootProject.buildDir
 }
</code>```

答:
first step --go to gradle.properties and check whether android.enableJetifier is false and implement the code in build.gradle(Module)

implementation 'com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava'

Body:
When building a project in Android Studio, Duplicate of android class.data binding.Database observed in data binding modules-runtime-7.0.4-runtime,  an error appears below is an incomplete error code and gradle files of the project:

Duplicate class androidx.databinding.BaseObservableField found in modules databinding-runtime-7.0.4-runtime (androidx.databinding:databinding-runtime:7.0.4) and jetified-library-3.2.0-alpha11-runtime (androidx.databinding:library:3.2.0-alpha11) Duplicate class androidx.databinding.BaseObservableField$DependencyCallback found in modules databinding-runtime-7.0.4-runtime (androidx.databinding:databinding-runtime:7.0.4) and jetified-library-3.2.0-alpha11-runtime (androidx.databinding:library:3.2.0-alpha11)

Duplicate class androidx.databinding.Bindable found in modules databinding-common-7.0.4 (androidx.databinding:databinding-common:7.0.4) and jetified-baseLibrary-3.2.0-alpha11 (androidx.databinding:baseLibrary:3.2.0-alpha11) Duplicate class androidx.databinding.BindingAdapter found in modules databinding-common-7.0.4 (androidx.databinding:databinding-common:7.0.4) and jetified-baseLibrary-3.2.0-alpha11 (androidx.databinding:baseLibrary:3.2.0-alpha11) Duplicate class androidx.databinding.BindingBuildInfo found in modules databinding-common-7.0.4 (androidx.databinding:databinding-common:7.0.4) and jetified-baseLibrary-3.2.0-alpha11 (androidx.databinding:baseLibrary:3.2.0-alpha11) Duplicate class androidx.databinding.BindingConversion found in modules databinding-common-7.0.4 (androidx.databinding:databinding-common:7.0.4) and jetified-baseLibrary-3.2.0-alpha11 (androidx.databinding:baseLibrary:3.2.0-alpha11) Duplicate class androidx.databinding.BindingMethod found in modules databinding-common-7.0.4 (androidx.databinding:databinding-common:7.0.4) and jetified-baseLibrary-3.2.0-alpha11 (androidx.databinding:baseLibrary:3.2.0-alpha11) Duplicate class androidx.databinding.BindingMethods found in modules databinding-common-7.0.4 (androidx.databinding:databinding-common:7.0.4) and jetified-baseLibrary-3.2.0-alpha11 (androidx.databinding:baseLibrary:3.2.0-alpha11) Duplicate class androidx.databinding.CallbackRegistry found in modules databinding-common-7.0.4 (androidx.databinding:databinding-common:7.0.4) and jetified-baseLibrary-3.2.0-alpha11 (androidx.databinding:baseLibrary:3.2.0-alpha11) Duplicate class androidx.databinding.CallbackRegistry$NotifierCallback found in modules databinding-common-7.0.4 (androidx.databinding:databinding-common:7.0.4) and jetified-baseLibrary-3.2.0-alpha11 (androidx.databinding:baseLibrary:3.2.0-alpha11) Duplicate class androidx.databinding.DataBinderMapper found in modules databinding-runtime-7.0.4-runtime (androidx.databinding:databinding-runtime:7.0.4) and jetified-library-3.2.0-alpha11-runtime (androidx.databinding:library:3.2.0-alpha11) Duplicate class androidx.databinding.DataBindingUtil found in modules databinding-runtime-7.0.4-runtime (androidx.databinding:databinding-runtime:7.0.4) and jetified-library-3.2.0-alpha11-runtime (androidx.databinding:library:3.2.0-alpha11) Duplicate class androidx.databinding.InverseBindingAdapter found in modules databinding-common-7.0.4 (androidx.databinding:databinding-common:7.0.4) and jetified-baseLibrary-3.2.0-alpha11 (androidx.databinding:baseLibrary:3.2.0-alpha11) Duplicate class androidx.databinding.InverseBindingListener found in modules databinding-common-7.0.4 (androidx.databinding:databinding-common:7.0.4) and jetified-baseLibrary-3.2.0-alpha11 (androidx.databinding:baseLibrary:3.2.0-alpha11) Duplicate class androidx.databinding.InverseBindingMethod found in modules databinding-common-7.0.4 (androidx.databinding:databinding-common:7.0.4) and jetified-baseLibrary-3.2.0-alpha11 (androidx.databinding:baseLibrary:3.2.0-alpha11) Duplicate class androidx.databinding.InverseBindingMethods found in modules databinding-common-7.0.4 (androidx.databinding:databinding-common:7.0.4) and jetified-baseLibrary-3.2.0-alpha11 (androidx.databinding:baseLibrary:3.2.0-alpha11)....

Go to the documentation to learn how to Fix dependency resolution errors.

Here is the Cradle(module) file:

plugins {
    id 'com.android.application'
    id 'kotlin-android'
}

android {
compileSdk 31

defaultConfig {
     applicationId "com.example.singupactivity"
     minSdk 24
     targetSdk 31
     versionCode 1
     versionName "1.0"

     testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
 }

  buildTypes {
        release {
          minifyEnabled false
           proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'),
           'proguard-rules.pro'
    }
  }
  compileOptions {
      sourceCompatibility JavaVersion.VERSION_1_8
      targetCompatibility JavaVersion.VERSION_1_8
  }
  kotlinOptions {
     jvmTarget = '1.8'
  }
   buildFeatures {
     //noinspection DataBindingWithoutKapt
     dataBinding true
  }
}

apply plugin: 'kotlin-kapt'

dependencies {

  implementation "com.github.moxy-community:moxy:2.2.2"
  kapt "com.github.moxy-community:moxy-compiler:2.2.2"

  implementation "androidx.recyclerview:recyclerview:1.3.0-alpha01"
  implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.0'
  implementation 'androidx.navigation:navigation-fragment-ktx:2.4.0-rc01'
  implementation 'androidx.navigation:navigation-ui-ktx:2.4.0-rc01'
  implementation 'com.makeramen:roundedimageview:2.3.0'
  implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
  implementation 'com.squareup.retrofit2:retrofit:2.3.0'
  implementation 'com.squareup.retrofit2:retrofit:2.3.0'
  implementation 'androidx.core:core-ktx:1.7.0'
  implementation 'androidx.appcompat:appcompat:1.4.1'
  implementation 'com.google.android.material:material:1.5.0'
  implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
  implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.4.0'
  implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.0'
  implementation 'androidx.legacy:legacy-support-v4:1.0.0'
  implementation 'androidx.test:core-ktx:1.4.0'
  implementation 'androidx.databinding:library:3.2.0-alpha11'
  testImplementation 'junit:junit:'
  androidTestImplementation 'androidx.test.ext:junit:1.1.3'
  androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

}

Here is the Cradle(project) file:

     // Top-level build file where you can add configuration options common to all sub-
 projects/modules.
buildscript {
  repositories {
      google()
      mavenCentral()
 }
dependencies {
classpath "com.android.tools.build:gradle:7.0.4"
classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.6.10'

// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}

task clean(type: Delete) {
delete rootProject.buildDir
 }


问:
Why "\n" is true doesn't compare?
Look at the sceene here , please:
http://social.microsoft.com/Forums/getfile/3600/
why it's not matching?</p>

答:
EDIT: Okay, now we know it's XmlReader.Value, which does return a string, that's definitely not the problem. I'll leave the previous answer below for future reference.

My guess is that there are some "odd" Unicode characters which don't show up in the debugger... or that the watch window is behaving strangely. Putting a watch on xml.Value.ToCharArray() would help to show that.

(As an aside, giving a Dictionary<,> parameter the name list is very confusing...)

EDIT: Additionally, using bracing and indentation would also make your code easier to follow...

We can't tell for sure at the moment, but my guess is that the Value property is of type object, not string. That means that == and != perform reference comparisons (operators are overloaded, not overridden, remember). You want the polymorphic behaviour of:

```<code>if (xml.Value.Equals("\n"))
</code>```

or if xml.Value can legitimately be null:

```<code>if ("\n".Equals(xml.Value))
</code>```

Title: Why "\n" is true doesn't compare?

Body:
EDIT: Okay, now we know it's XmlReader.Value, which does return a string, that's definitely not the problem. I'll leave the previous answer below for future reference.

My guess is that there are some "odd" Unicode characters which don't show up in the debugger... or that the watch window is behaving strangely. Putting a watch on xml.Value.ToCharArray() would help to show that.

(As an aside, giving a Dictionary<,> parameter the name list is very confusing...)

EDIT: Additionally, using bracing and indentation would also make your code easier to follow...

We can't tell for sure at the moment, but my guess is that the Value property is of type object, not string. That means that == and != perform reference comparisons (operators are overloaded, not overridden, remember). You want the polymorphic behaviour of:

if (xml.Value.Equals("\n"))

or if xml.Value can legitimately be null:

if ("\n".Equals(xml.Value))


问:
else statement only works when I add a return or break
My else statement only works when I add a break or return, and I have been trying to fix this for 3 hours and I have no clue what I am doing. I don't need you to rewrite the code just please tell me what to do.</p>
```<code>    while (pHealth > 0 || pHappiness > 0 && !restarted)
    {
        Console.Clear();

        UpdateHud();

        // Get user input

        Console.Write("╚═ENTER CHOICE: ");
        choice = Console.ReadLine();

        // Add your Codes here!

        if (choice == "A" || choice == "a")
        {
            if (pHappiness > 0)
            {
                pHealth = pHealth + 10;
                pHappiness = Math.Clamp(pHappiness - 25, 0, 100);
            }
        }
        else if (choice == "B" || choice == "b")
        {
            if (pHealth > 0)
            {
                pHealth = Math.Clamp(pHealth - 25, 0, 100);
                pHappiness = pHappiness + 15;
            }
        }
        else if (choice == "C" || choice == "c")
        {
            if (pHappiness > 0)
            {
                pHealth = pHealth + 20;
                pHappiness = Math.Clamp(pHappiness - 40, 0, 100);
            }
        }
        else
        {
            Console.Clear();
            UpdateHud();
            Console.WriteLine("Invalid!!!");
            break;
        }
    }
</code>```

答: Remove 2nd while outside of 1st while loop. Your game over logs are written ih happiness or health are equal to zero, but parent loop is executed while they are greater than zero. Maybe that solve problem. And reconsider refactoring to use switch instead so many if else.</p>

Body:
My else statement only works when I add a break or return, and I have been trying to fix this for 3 hours and I have no clue what I am doing. I don't need you to rewrite the code just please tell me what to do.

    while (pHealth > 0 || pHappiness > 0 && !restarted)
    {
        Console.Clear();

        UpdateHud();

        // Get user input

        Console.Write("╚═ENTER CHOICE: ");
        choice = Console.ReadLine();

        // Add your Codes here!

        if (choice == "A" || choice == "a")
        {
            if (pHappiness > 0)
            {
                pHealth = pHealth + 10;
                pHappiness = Math.Clamp(pHappiness - 25, 0, 100);
            }
        }
        else if (choice == "B" || choice == "b")
        {
            if (pHealth > 0)
            {
                pHealth = Math.Clamp(pHealth - 25, 0, 100);
                pHappiness = pHappiness + 15;
            }
        }
        else if (choice == "C" || choice == "c")
        {
            if (pHappiness > 0)
            {
                pHealth = pHealth + 20;
                pHappiness = Math.Clamp(pHappiness - 40, 0, 100);
            }
        }
        else
        {
            Console.Clear();
            UpdateHud();
            Console.WriteLine("Invalid!!!");
            break;
        }
    }


问:
Not able to test an event of Stencil app with Jest
I'm trying to test a click event originated from an icon () in a Stencil component. The thing is I am able to debug the test and I see that the test triggers the correct method on the component, but Jest is not able to detect\register the event and the toHaveBeenCalled() method fails.

input.spec.jsx

```<code>  it("dispatches icon click event", async () => {
    const page = await newSpecPage({
      components: [Input], //just the component name
      template: () => (<input-fields value="some input value"></input-fields>),
    });

    const eventSpy = jest.fn();
    page.win.addEventListener('input-field-search-event', eventSpy);

    await page.root.shadowRoot.querySelector('.icon-container').click();
    await page.waitForChanges();
    expect(eventSpy).toHaveBeenCalled();
  });
</code>```

input.tsx

```<code>  private dispatchSearchEvent(e){
    //i can stop ay this point with a break point and the data passed by the test is correct
    this.tipInputEnterEvent.emit({type: "input-field-search-event", event: e, data: this.value});
  }
</code>```

the error

```<code>  ● Input tests › dispatches icon click event

    expect(jest.fn()).toHaveBeenCalled()

    Expected number of calls: >= 1
    Received number of calls:    0

      334 |     await page.root.shadowRoot.querySelector('.icon-container').click();
      335 |     await page.waitForChanges();
    > 336 |     expect(eventSpy).toHaveBeenCalled();
          |                      ^
      337 |   });
      338 |
      339 | });
</code>```

答:
By default the name of custom events is the property name, in your case tipInputEnterEvent. So the listener should instead be:

page.win.addEventListener('tipInputEnterEvent', eventSpy);
```
<p>You can also change the event name if you want:</p>
```@Event({ eventName: 'input-field-search-event' }) tipInputEnterEvent: EventEmitter;
```

Body:
I'm trying to test a click event originated from an icon () in a Stencil component. The thing is I am able to debug the test and I see that the test triggers the correct method on the component, but Jest is not able to detect\register the event and the toHaveBeenCalled() method fails.

input.spec.jsx

  it("dispatches icon click event", async () => {
    const page = await newSpecPage({
      components: [Input], //just the component name
      template: () => (<input-fields value="some input value"></input-fields>),
    });

    const eventSpy = jest.fn();
    page.win.addEventListener('input-field-search-event', eventSpy);

    await page.root.shadowRoot.querySelector('.icon-container').click();
    await page.waitForChanges();
    expect(eventSpy).toHaveBeenCalled();
  });

input.tsx

  private dispatchSearchEvent(e){
    //i can stop ay this point with a break point and the data passed by the test is correct
    this.tipInputEnterEvent.emit({type: "input-field-search-event", event: e, data: this.value});
  }

the error

  ● Input tests › dispatches icon click event

    expect(jest.fn()).toHaveBeenCalled()

    Expected number of calls: >= 1
    Received number of calls:    0

      334 |     await page.root.shadowRoot.querySelector('.icon-container').click();
      335 |     await page.waitForChanges();
    > 336 |     expect(eventSpy).toHaveBeenCalled();
          |                      ^
      337 |   });
      338 |
      339 | });

Body:
By default the name of custom events is the property name, in your case tipInputEnterEvent. So the listener should instead be:

page.win.addEventListener('tipInputEnterEvent', eventSpy);

You can also change the event name if you want:

@Event({ eventName: 'input-field-search-event' }) tipInputEnterEvent: EventEmitter;


问:
Can React-hook-form create payload with dot in the object key
When I register register("data.name") the response payload will be something like this

```<code>{
   data: {
     name: "some value"
   }
}
</code>```

Is it possible to get payload something like with with inbuilt method

```<code>{
  data.name: "some value"
}
</code>```

答: RHF doesn't have functionality, you may have to build this at your app level.</p>

Body:
When I register register("data.name") the response payload will be something like this

{
   data: {
     name: "some value"
   }
}

Is it possible to get payload something like with with inbuilt method

{
  data.name: "some value"
}