问:
Clubbing both complex objects does not work: Javascript
I have an source object that has the following structure

```<code>var obj1 = {
          type: "type1",
          nested: {
                level1: [
                  { field: "field1", value: "val1"},
                  { field: "field2", value: "val2"},
                  {
                     level2: [
                                  {
                                    field: "abc",
                                    value: "11",
                                  },
                                  {
                                    field: "abc",
                                    value: "12",
                                  }
                             ]
                  }
                ]
          },
          in: 0,
          out: 20
};

</code>```

Also there is an input object, based on which merging should happen

```<code>var obj2 = {
          type: "type1",
          nested: {
                level1: [
                  { field: "field1", value: "val1"},
                  { field: "field3", value: "val5" }
                ]
          },
          in: 0,
          out: 20
};

</code>```

Based on the new object I need to merge and resultant should hold only the unique one's. In my case the object can go deep upto level 2. The only thing I need is a manipulation on "nested" object. If same keys are present then update the value, else just append it. Also content within "nested" of obj2 will always be there in obj1's "nested". If something of obj2's "nested" is not present in obj1's "nested" then delete that object. Test cases file attached inside sandbox

Output should look like:

```<code>result = {
              type: "type1",
              nested: {
                      level1: [
                                { field: "field1", value: "val1"},
                                { field: "field2", value: "val2"},
                                { field: "field3", value: "val5" },
                                {
                                 level2:
                                     [
                                         {
                                           field: "abc",
                                           value: "11",
                                         },
                                         {
                                           field: "abc",
                                           value: "12",
                                         }
                                      ]
                                    }
                                  ]
                             },
                            in: 0,
                            out: 20
    };

</code>```

Method that I have tried:

```<code>const merged = [...new Set([...obj1.nested.level1, ...obj2.nested.level1])]

</code>```

Sandbox: https://codesandbox.io/s/angry-liskov-e5m1m

答:
Just google "deep merge javascript" or "merge nested objects". Here is one example of what i found:

// Merge a `source` object to a `target` recursively
const merge = (target, source) => {
  // Iterate through `source` properties and if an `Object` set property to merge of `target` and `source` properties
  for (const key of Object.keys(source)) {
    if (source[key] instanceof Object) Object.assign(source[key], merge(target[key], source[key]))
  }

  // Join `target` and modified `source`
  Object.assign(target || {}, source)
  return target
}

console.log(merge(obj1, obj2));
```

Body:
I have an source object that has the following structure

var obj1 = {
          type: "type1",
          nested: {
                level1: [
                  { field: "field1", value: "val1"},
                  { field: "field2", value: "val2"},
                  {
                     level2: [
                                  {
                                    field: "abc",
                                    value: "11",
                                  },
                                  {
                                    field: "abc",
                                    value: "12",
                                  }
                             ]
                  }
                ]
          },
          in: 0,
          out: 20
};

Also there is an input object, based on which merging should happen

var obj2 = {
          type: "type1",
          nested: {
                level1: [
                  { field: "field1", value: "val1"},
                  { field: "field3", value: "val5" }
                ]
          },
          in: 0,
          out: 20
};

Based on the new object I need to merge and resultant should hold only the unique one's. In my case the object can go deep upto level 2. The only thing I need is a manipulation on "nested" object. If same keys are present then update the value, else just append it. Also content within "nested" of obj2 will always be there in obj1's "nested". If something of obj2's "nested" is not present in obj1's "nested" then delete that object. Test cases file attached inside sandbox

Output should look like:

result = {
              type: "type1",
              nested: {
                      level1: [
                                { field: "field1", value: "val1"},
                                { field: "field2", value: "val2"},
                                { field: "field3", value: "val5" },
                                {
                                 level2:
                                     [
                                         {
                                           field: "abc",
                                           value: "11",
                                         },
                                         {
                                           field: "abc",
                                           value: "12",
                                         }
                                      ]
                                    }
                                  ]
                             },
                            in: 0,
                            out: 20
    };

Method that I have tried:

const merged = [...new Set([...obj1.nested.level1, ...obj2.nested.level1])]

Sandbox: https://codesandbox.io/s/angry-liskov-e5m1m


来源: stackexchange

问:
Can we connect the gateway only once in hypeledger fabric using node SDK
I need to help with my query which related to hyperledger fabric gateway connection to client though node sdk. I wrote some API's which is connected to the fabric network using below code.

```<code>const ccpPath = path.resolve(__dirname, '..', 'config', 'connection.json');

const gateway = new Gateway();

await gateway.connect(ccpPath, {
    wallet,
    identity: Username,
    discovery: {
        enabled: true,
        asLocalhost: false
    }

});
</code>```

Now I have to use the above code to connect each and every time controller which call API's, however, I want to use it onetime so Once the connection made to the network I don't need to connect again and again.
Is there is some way to implement it? if possible suggest to me so I can implement it in my API's.
Please let me know if there is anything more information need?

Thanks in Advance

答:
Yes sure.

inglobe in a connect function and declare the gateway as external to the function.

```<code>let gateway;
function connect() {
  const ccpPath = path.resolve(__dirname, '..', 'config', 'connection.json');

  gateway = new Gateway();

  await gateway.connect(ccpPath, {
    wallet,
    identity: Username,
    discovery: {
        enabled: true,
        asLocalhost: false
    }

  });
}
</code>```

Next from app.js or starting point of your app, call the function and you are connected.
You don't need to connect each time, you can connect once.

ContentLicense: CC BY-SA 4.0

Body:
I need to help with my query which related to hyperledger fabric gateway connection to client though node sdk. I wrote some API's which is connected to the fabric network using below code.

const ccpPath = path.resolve(__dirname, '..', 'config', 'connection.json');

const gateway = new Gateway();

await gateway.connect(ccpPath, {
    wallet,
    identity: Username,
    discovery: {
        enabled: true,
        asLocalhost: false
    }

});

Now I have to use the above code to connect each and every time controller which call API's, however, I want to use it onetime so Once the connection made to the network I don't need to connect again and again.
Is there is some way to implement it? if possible suggest to me so I can implement it in my API's.
Please let me know if there is anything more information need?

Thanks in Advance

Body:
Yes sure.

inglobe in a connect function and declare the gateway as external to the function.

let gateway;
function connect() {
  const ccpPath = path.resolve(__dirname, '..', 'config', 'connection.json');

  gateway = new Gateway();

  await gateway.connect(ccpPath, {
    wallet,
    identity: Username,
    discovery: {
        enabled: true,
        asLocalhost: false
    }

  });
}

Next from app.js or starting point of your app, call the function and you are connected.
You don't need to connect each time, you can connect once.


问:
Creating a live checkers-like web app with PHP, JS, CSS and HTML?
I want to create a live, checkers-like app, which will work like this: There will be multiple icons/avatars displayed on this checkerboard like surface. I want to have a command prompt beneath this board, or some other sort of interface, that will allow them to control a certain avatar, and get it to preform actions. Multiple users will be using it at one time, and I will all be able to view the other user's changes/actions to the checkerboard.

What I'm wondering is: what's the best way to do this? I've got my HTML, CSS, and JS approach down, but not my data storage method. I know that, using PHP, I've got the choices to use either: file-based storage, MYSQL, or some other method. I need to know which is better, because I don't want to have server-lag, poor-response time, or some other issue, especially in this case since actions will be preformed every other second 2 or so, by these multiple users.

I've done similar stuff before, but I'm wanting to hear how others would handle it (advice, etc.) from more experienced programmers.

答:
Sounds like a great project for node.js!

To clarify, node.js is a server-side implementation of javascript. What you'll want is a comet based application (a web-based client application that receives server side pushes instead of the client constantly polling the server), which is exactly what node.js is good at.

Traditional ajax calls for your clients to poll the server for data. This creates enormous overhead for both the client and the server. Allowing the server to push requests directly to the client without the client repeatedly asking solves the overhead issue and creates a more responsive interface. This is accomplished by holding asynchronous client connections on the server and only returning when the server has something to respond with. Once the server responds with data, another connection is immediately created and held by the server again until data is ready to be sent.

You may be able to accomplish the same thing with PHP, but I'm not that familiar with PHP and Comet type applications.

Number of users and hosting costs will play into your file vs DB options. If you're planning on more than a couple of users, I'd stick to the database. There are some NoSQL options available out there, but in my experience MySQL is much faster and more reliable than those options.

Good luck with your project!

http://en.wikipedia.org/wiki/Comet_%28programming%29

http://www.nodejs.org/

http://zenmachine.wordpress.com/2010/01/31/node-js-and-comet/

http://socket.io/ - abstracts away the communication layer with your clients based on their capability (LongPolling, WebSockets, etc.)

ContentLicense: CC BY-SA 3.0


问:
Shared memory between NDK and SDK below API Level 26
Library written in c++ produces continuous stream of data and same has to be ported on different platforms. Now integrating the lib to android application, I am trying to create shared memory between NDK and SDK.

Below is working snippet,

Native code:

```<code>#include <jni.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <linux/ashmem.h>
#include <android/log.h>
#include <string>

char  *buffer;
constexpr size_t BufferSize=100;
extern "C" JNIEXPORT jobject JNICALL
Java_test_com_myapplication_MainActivity_getSharedBufferJNI(
        JNIEnv* env,
        jobject /* this */) {

    int fd = open("/dev/ashmem", O_RDWR);

    ioctl(fd, ASHMEM_SET_NAME, "shared_memory");
    ioctl(fd, ASHMEM_SET_SIZE, BufferSize);

    buffer = (char*) mmap(NULL, BufferSize, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);

    return (env->NewDirectByteBuffer(buffer, BufferSize));
}

extern "C" JNIEXPORT void JNICALL
Java_test_com_myapplication_MainActivity_TestBufferCopy(
        JNIEnv* env,
        jobject /* this */) {

   for(size_t i=0;i<BufferSize;i = i+2) {
       __android_log_print(ANDROID_LOG_INFO, "native_log", "Count %d value:%d", i,buffer[i]);
   }

   //pass `buffer` to dynamically loaded library to update share memory
   //

}
</code>```

SDK code:

```<code>//MainActivity.java
public class MainActivity extends AppCompatActivity {

    // Used to load the 'native-lib' library on application startup.

    static {
        System.loadLibrary("native-lib");
    }

    final int BufferSize = 100;
    @RequiresApi(api = Build.VERSION_CODES.Q)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ByteBuffer byteBuffer = getSharedBufferJNI();

        //update the command to shared memory here
        //byteBuffer updated with commands
        //Call JNI to inform update and get the response
        TestBufferCopy();
    }

    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     */
    public native ByteBuffer getSharedBufferJNI();
    public native int TestBufferCopy();
}
</code>```

Question:

Accessing primitive arrays from Java to native is reference only if garbage collector supports pinning. Is it true for other way around ?

Is it guaranteed by android platform that ALWAYS reference is shared from NDK to SDK without redundant copy?

Is it the right way to share memory?

答:
Let me summarize my findings,

Accessing primitive arrays from Java to native is reference only if garbage collector supports pinning. Is it true for other way around ?

The contents of a direct buffer can, potentially, reside in native memory outside of the ordinary garbage-collected heap. And hence garbage collector can't claim the memory.

Is it guaranteed by android platform that ALWAYS reference is shared from NDK to SDK without redundant copy?

Yes, As per documentation of NewDirectByteBuffer.

```<code>jobject NewDirectByteBuffer(JNIEnv* env, void* address, jlong capacity);
</code>```

Allocates and returns a direct java.nio.ByteBuffer referring to the block of memory starting at the memory address address and extending capacity bytes.

Body:
Library written in c++ produces continuous stream of data and same has to be ported on different platforms. Now integrating the lib to android application, I am trying to create shared memory between NDK and SDK.

Below is working snippet,

Native code:

#include <jni.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <linux/ashmem.h>
#include <android/log.h>
#include <string>

char  *buffer;
constexpr size_t BufferSize=100;
extern "C" JNIEXPORT jobject JNICALL
Java_test_com_myapplication_MainActivity_getSharedBufferJNI(
        JNIEnv* env,
        jobject /* this */) {

    int fd = open("/dev/ashmem", O_RDWR);

    ioctl(fd, ASHMEM_SET_NAME, "shared_memory");
    ioctl(fd, ASHMEM_SET_SIZE, BufferSize);

    buffer = (char*) mmap(NULL, BufferSize, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);

    return (env->NewDirectByteBuffer(buffer, BufferSize));
}

extern "C" JNIEXPORT void JNICALL
Java_test_com_myapplication_MainActivity_TestBufferCopy(
        JNIEnv* env,
        jobject /* this */) {

   for(size_t i=0;i<BufferSize;i = i+2) {
       __android_log_print(ANDROID_LOG_INFO, "native_log", "Count %d value:%d", i,buffer[i]);
   }

   //pass `buffer` to dynamically loaded library to update share memory
   //

}

SDK code:

//MainActivity.java
public class MainActivity extends AppCompatActivity {

    // Used to load the 'native-lib' library on application startup.

    static {
        System.loadLibrary("native-lib");
    }

    final int BufferSize = 100;
    @RequiresApi(api = Build.VERSION_CODES.Q)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ByteBuffer byteBuffer = getSharedBufferJNI();

        //update the command to shared memory here
        //byteBuffer updated with commands
        //Call JNI to inform update and get the response
        TestBufferCopy();
    }

    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     */
    public native ByteBuffer getSharedBufferJNI();
    public native int TestBufferCopy();
}

Question:

Accessing primitive arrays from Java to native is reference only if garbage collector supports pinning. Is it true for other way around ?

Is it guaranteed by android platform that ALWAYS reference is shared from NDK to SDK without redundant copy?

Is it the right way to share memory?

Body:
Let me summarize my findings,

Accessing primitive arrays from Java to native is reference only if garbage collector supports pinning. Is it true for other way around ?

The contents of a direct buffer can, potentially, reside in native memory outside of the ordinary garbage-collected heap. And hence garbage collector can't claim the memory.

Is it guaranteed by android platform that ALWAYS reference is shared from NDK to SDK without redundant copy?

Yes, As per documentation of NewDirectByteBuffer.

jobject NewDirectByteBuffer(JNIEnv* env, void* address, jlong capacity);

Allocates and returns a direct java.nio.ByteBuffer referring to the block of memory starting at the memory address address and extending capacity bytes.


问:
Implementing OAuth2.0 to secure microservice architecture
I have been looking for several weeks to find a way to secure my application using microservice architecture using OAuth2 and I couldn't find any helpful material.

I would appreciate if anyone of you could help me.

答:
here you can find a complete example implementing microservices architecture,
this could help you :) </p>


问:
Simple XQuery FLWOR to return text without numbers
How do I return non-numeric text?

```<code>for $foo  in db:open("foo")
return $foo//text()
</code>```

Assuming that every address or phone number cell from the original spreadsheet has numerals, I'm looking to return any string without numerals.

context, per Michael Kay's note:

Each cell of the spreadsheet has a String.  There's only one column of what can easily be CSV data.  Seemingly, only the names lack numerals.  On that assumption, looking to break the data into "chunks" to differentiate each individual.  There's no real pattern to the data.

答:
I'm looking to return any string without numerals.

Regex could do that:

```<code>for $foo in db:open("foo")
return $foo//text()[not(matches(., '[0-9]'))]
</code>```

Body:
How do I return non-numeric text?

for $foo  in db:open("foo")
return $foo//text()

Assuming that every address or phone number cell from the original spreadsheet has numerals, I'm looking to return any string without numerals.

context, per Michael Kay's note:

Each cell of the spreadsheet has a String.  There's only one column of what can easily be CSV data.  Seemingly, only the names lack numerals.  On that assumption, looking to break the data into "chunks" to differentiate each individual.  There's no real pattern to the data.

Body:
I'm looking to return any string without numerals.

Regex could do that:

for $foo in db:open("foo")
return $foo//text()[not(matches(., '[0-9]'))]


问:
How can I call a Python module inside a Jinja for loop?
I have this function in Flask where I do a search on spotify:

```<code>@app.route('/search', methods=['GET','POST'])
def search():
    data = sp.search(request.form['code'])
    api_url = data['tracks']['href']
    items = data['tracks']['items']
    for item in items:
        artist = sp.artist(item['artists'][0]['uri'])
        image_url = artist['images'][2]['url']
    html = render_template('search.html',
                            artist_name=request.form['code'],
                            results=items,
                            api_url=api_url,
                            image_url=image_url)
    return html
</code>```

This is the Jinja template in my html page:

```<code>{% for artist in results %}
        <tr>
          <td>
            <img src="{{image_url}}" alt="{{image_url}}" class="bobby img-thumbnail img-circle">
            <a href="{{ url_for('artist', id=artist.id) }}">
              {{ artist.name }}
            </a>
          </td>
          <td>
            {{ artist.artists.0.name }}
          </td>
        </tr>
      {% endfor %}
</code>```

I correctly recieve the artist and song. But I have a problem with the part where I try to recieve the picture for every artist:

```<code>for item in items:
  artist = sp.artist(item['artists'][0]['uri'])
  image_url = artist['images'][2]['url']
</code>```

I get the same picture for all the artists. Should that for loop with the spotipy module be inside the Jinja template? And how can I do that?

答:
Update search function first:

```<code>@app.route('/search', methods=['GET','POST'])
def search():
    data = sp.search(request.form['code'])
    api_url = data['tracks']['href']
    items = data['tracks']['items']
    for item in items:
        artist = sp.artist(item['artists'][0]['uri'])
        item['image_url'] = artist['images'][2]['url'] # <-- change this line
    html = render_template('search.html',
                            artist_name=request.form['code'],
                            results=items,
                            api_url=api_url,
                            image_url=image_url)
    return html
</code>```

Then you need to update your template

```<code><img src="{{artist.image_url}}" alt="{{artist.image_url}}" class="bobby img-thumbnail img-circle">
</code>```

Body:
I have this function in Flask where I do a search on spotify:

@app.route('/search', methods=['GET','POST'])
def search():
    data = sp.search(request.form['code'])
    api_url = data['tracks']['href']
    items = data['tracks']['items']
    for item in items:
        artist = sp.artist(item['artists'][0]['uri'])
        image_url = artist['images'][2]['url']
    html = render_template('search.html',
                            artist_name=request.form['code'],
                            results=items,
                            api_url=api_url,
                            image_url=image_url)
    return html

This is the Jinja template in my html page:

{% for artist in results %}

              {{ artist.name }}

            {{ artist.artists.0.name }}

      {% endfor %}

I correctly recieve the artist and song. But I have a problem with the part where I try to recieve the picture for every artist:

for item in items:
  artist = sp.artist(item['artists'][0]['uri'])
  image_url = artist['images'][2]['url']

I get the same picture for all the artists. Should that for loop with the spotipy module be inside the Jinja template? And how can I do that?

Body:
Update search function first:

@app.route('/search', methods=['GET','POST'])
def search():
    data = sp.search(request.form['code'])
    api_url = data['tracks']['href']
    items = data['tracks']['items']
    for item in items:
        artist = sp.artist(item['artists'][0]['uri'])
        item['image_url'] = artist['images'][2]['url'] # <-- change this line
    html = render_template('search.html',
                            artist_name=request.form['code'],
                            results=items,
                            api_url=api_url,
                            image_url=image_url)
    return html

Then you need to update your template

<img src="{{artist.image_url}}" alt="{{artist.image_url}}" class="bobby img-thumbnail img-circle">


问:
How do I make a selected radio button change one piece of state based upon another radio button changing another piece of state?
I have a couple of components I am building and have run into a bit of a stumbling block.

The components start with a piano keyboard on which I can overlay different musical entities, like notes, intervals, chords, scales, etc...by passing the note names via a notes={[]} array prop into the Keyboard component. In this particular instance of the component I am then importing it into a Scales component in which I have added scale and note buttons, so I can overlay entire scales in this instance on top of the keyboard, which is all basically working. have a list of note names that I can click on and then overlay that scale on top of the keyboard, like so:

The gif shows the current behavior of the Scales component, which is not quite correct yet...

In the gif you can see that the major and minor scale buttons change the state of the scale, which is then used by the note name buttons to change the state of the keyboard beneath it. But what I also want it to do is switch the currently selected scale when the major or minor button is clicked, but currently the note name buttons don't automatically react to the change in state in the major and minor buttons, but have to be clicked again to make the change occur.

What I want is to be able to just click the major and minor buttons and which ever note is selected will simply change from major to minor without having to re-click the selected scale note again, which is the current behavior.

So, in my Scales component I am using custom radio buttons like so, first to control the major and minor buttons:

```<code><MajorInput
  type="radio"
  name="scale"
  id="major"
  label="major"
  value="major"
  checked={scale === 'major'}
  onChange={handleChange}
  onClick={() => setScale('major')}
/>
<MajorLabel
  whileHover={{ scale: 1 }}
  whileTap={{ scale: 0.9 }}
  htmlFor="major"
>
  Major
</MajorLabel>
</code>```

...then to control the note buttons, like so:

```<code><NoteInput
  id="c"
  scale={scale}
  type="radio"
  name="notes"
  label="c"
  value="c"
  onClick={
    () => setNotes(
      scale === 'major' ? ['c1p', 'd1ma', 'e1ma', 'f1p', 'g1p', 'a1ma', 'b1ma'] :
      scale === 'minor' ? ['c1p', 'd1ma', 'eb1mi', 'f1p', 'g1p', 'ab1mi', 'bb1mi'] :
      ''
    )
  }
/>
<NoteLabel
  whileHover={{ scale: 1 }}
  whileTap={{ scale: 0.9 }}
  scale={scale}
  htmlFor="c"
>
{
  scale === 'major' ? 'C' :
  scale === 'minor' ? 'C' :
  'C'
}
</NoteLabel>
</code>```

...and the state is established via two useState hooks, like so:

```<code>const [ scale, setScale] = useState('')

const [ notes, setNotes] = useState([])
</code>```

...then ultimately the imported Keyboard component receives it's notes={notes} prop from the notes buttons, like so:

```<code><Keyboard octaves={'2'} notes={notes}/>
</code>```

...so i don't really know how I could make the note buttons be aware or know about the scale buttons being clicked and then translate that information to the keyboards notes prop, which is where i am stuck now...

Here is a code sandbox of the the component:

https://codesandbox.io/s/scales-981uk

Thank you for your help :-)

答:
I looked through your code.

The problem you have right now is that your note components are not rerendered and restyled when the major button is clicked. In React, you can use the change in props to trigger a rerender which will also restyle your notes.

I would suggest to put all your note inputs into a sub component. :

// ./Scales.js

import NoteButtonBox from ./NoteButtonBox.js

//...

// important: pass scale as props.
// Everytime scale changes, the note buttons are rerendered and restyled
sub component
  return (
    <Container>
      <ScaleButtonBox>
        {/* ... */}
      <ScaleButtonBox>
      <NoteButtonBox scale={scale} />
      {/* ... */}
```

<pre class="lang-js prettyprint-override"><code>// ./NoteButtonBox.js

const NoteButtonBox = ({scale}) => {
   // Don't forget to also move 'const [notes, setNotes] = useState([]);' into the
  const [notes, setNotes] = useState([]);
  return {
    /* return your styled notes based on props scale */
  }
}
</code>```

EDIT

For situations where you need to access state across multiple sub components, you can use React Context. Alternatively, you can use React Redux which accomplishes the same thing. I would suggest Comtext because it is a native part of React.

Breaking up your app into sub components might seem like unnecessary work but it is good practice to create many small components in React. React encourages composition like I suggest.

Create a NotesStateContext class.

You define the where it is needed NotesStateContext.Provider:

      <NotesStateContext.Provider value="dark">
        <NoteButtonBox />
        </* All other components that need to access the state of your notes */>
      </NotesStateContext.Provider>
```

Get and update your state from the provider

Body:
I have a couple of components I am building and have run into a bit of a stumbling block.

The components start with a piano keyboard on which I can overlay different musical entities, like notes, intervals, chords, scales, etc...by passing the note names via a notes={[]} array prop into the Keyboard component. In this particular instance of the component I am then importing it into a Scales component in which I have added scale and note buttons, so I can overlay entire scales in this instance on top of the keyboard, which is all basically working. have a list of note names that I can click on and then overlay that scale on top of the keyboard, like so:

The gif shows the current behavior of the Scales component, which is not quite correct yet...

In the gif you can see that the major and minor scale buttons change the state of the scale, which is then used by the note name buttons to change the state of the keyboard beneath it. But what I also want it to do is switch the currently selected scale when the major or minor button is clicked, but currently the note name buttons don't automatically react to the change in state in the major and minor buttons, but have to be clicked again to make the change occur.

What I want is to be able to just click the major and minor buttons and which ever note is selected will simply change from major to minor without having to re-click the selected scale note again, which is the current behavior.

So, in my Scales component I am using custom radio buttons like so, first to control the major and minor buttons:

<MajorInput
  type="radio"
  name="scale"
  id="major"
  label="major"
  value="major"
  checked={scale === 'major'}
  onChange={handleChange}
  onClick={() => setScale('major')}
/>
<MajorLabel
  whileHover={{ scale: 1 }}
  whileTap={{ scale: 0.9 }}
  htmlFor="major"
>
  Major
</MajorLabel>

...then to control the note buttons, like so:

<NoteInput
  id="c"
  scale={scale}
  type="radio"
  name="notes"
  label="c"
  value="c"
  onClick={
    () => setNotes(
      scale === 'major' ? ['c1p', 'd1ma', 'e1ma', 'f1p', 'g1p', 'a1ma', 'b1ma'] :
      scale === 'minor' ? ['c1p', 'd1ma', 'eb1mi', 'f1p', 'g1p', 'ab1mi', 'bb1mi'] :
      ''
    )
  }
/>
<NoteLabel
  whileHover={{ scale: 1 }}
  whileTap={{ scale: 0.9 }}
  scale={scale}
  htmlFor="c"
>
{
  scale === 'major' ? 'C' :
  scale === 'minor' ? 'C' :
  'C'
}
</NoteLabel>

...and the state is established via two useState hooks, like so:

const [ scale, setScale] = useState('')

const [ notes, setNotes] = useState([])

...then ultimately the imported Keyboard component receives it's notes={notes} prop from the notes buttons, like so:

<Keyboard octaves={'2'} notes={notes}/>

...so i don't really know how I could make the note buttons be aware or know about the scale buttons being clicked and then translate that information to the keyboards notes prop, which is where i am stuck now...

Here is a code sandbox of the the component:

https://codesandbox.io/s/scales-981uk

Thank you for your help :-)

Body:
I looked through your code.

The problem you have right now is that your note components are not rerendered and restyled when the major button is clicked. In React, you can use the change in props to trigger a rerender which will also restyle your notes.

I would suggest to put all your note inputs into a sub component. :

// ./Scales.js

import NoteButtonBox from ./NoteButtonBox.js

//...

// important: pass scale as props.
// Everytime scale changes, the note buttons are rerendered and restyled
sub component
  return (
    <Container>
      <ScaleButtonBox>
        {/* ... */}
      <ScaleButtonBox>
      <NoteButtonBox scale={scale} />
      {/* ... */}

// ./NoteButtonBox.js

const NoteButtonBox = ({scale}) => {
   // Don't forget to also move 'const [notes, setNotes] = useState([]);' into the
  const [notes, setNotes] = useState([]);
  return {
    /* return your styled notes based on props scale */
  }
}

EDIT

For situations where you need to access state across multiple sub components, you can use React Context. Alternatively, you can use React Redux which accomplishes the same thing. I would suggest Comtext because it is a native part of React.

Breaking up your app into sub components might seem like unnecessary work but it is good practice to create many small components in React. React encourages composition like I suggest.

Create a NotesStateContext class.

You define the where it is needed NotesStateContext.Provider:

      <NotesStateContext.Provider value="dark">
        <NoteButtonBox />
        </* All other components that need to access the state of your notes */>
      </NotesStateContext.Provider>

Get and update your state from the provider


问:
DataStudio: How to filter greater than '>' without 'ADD A FILTER'
Got a salary column in big query.

Trying to figure out a way to filter the salary with logical operators without specifying a custom filter(ADD A FILTER) in DataStudio.

I would like to perform the following operation:
salary > 5000000000000000 for example.

Is this possible?

答:
One way is to use a Filter Control, with the Dimension set to Salary, and the Filter Control set to the Search All view, so that comparison operators (>, >=, <, <=, =) can be used to filter Metrics quickly.

Created a Google Data Studio Report (Google Sheets Embedded) as well as a GIF showing the process.


问:
How do I grab an element with jQuery without a way to reference it via class, ID, etc
I have a table like so:

```<code><table>
<thead>
    <tr>
        <th>Hostname</th>
        <th>Action</th>
    </tr>
</thead>
<tbody>
    <tr>
        <td>127.0.0.1</td>
        <td><a name="delete" onclick="remove_host('127.0.0.1')">Remove</a></td>
    </tr>
    <tr>
        <td>127.0.0.2</td>
        <td><a name="delete" onclick="remove_host('127.0.0.2')">Remove</a></td>
    </tr>
    <tr>
        <td>127.0.0.3</td>
        <td><a name="delete" onclick="remove_host('127.0.0.3')">Remove</a></td>
    </tr>
</tbody>
</code>```

What I'm trying to do is, when a user clicks on Remove, that the link is replaced with one of those loading images so the user can't repeatedly hit the link.

How do I get the a element, so to speak, so I can set the HTML accordingly with jQuery?

On other parts of the site, I'm able to attach a rel="host-1" (or similar) to the link, so I can easily reference it to change out the HTML.

答:
You could pass this in the call to remove_host, like this:

```<code>remove_host('127.0.0.1', this);
</code>```

This will give you a reference to the DOM element, which you can wrap in jQuery.

Body:
I have a table like so:

        Hostname
        Action

        127.0.0.1
        Remove

        127.0.0.2
        Remove

        127.0.0.3
        Remove

What I'm trying to do is, when a user clicks on Remove, that the link is replaced with one of those loading images so the user can't repeatedly hit the link.

How do I get the a element, so to speak, so I can set the HTML accordingly with jQuery?

On other parts of the site, I'm able to attach a rel="host-1" (or similar) to the link, so I can easily reference it to change out the HTML.

Body:
You could pass this in the call to remove_host, like this:

remove_host('127.0.0.1', this);

This will give you a reference to the DOM element, which you can wrap in jQuery.


问:
Is there a way to "Cancel" a stream after the delay operator
I am using a polling scheme in my Angular application using NgRx.

To simplify things, I have something like the following:

```<code>    public stopPolling$ = createEffect(() => this.actions$.pipe(
        ofType(actions.stopPolling),
        tap(_ => this.isPollingActive = false),
        map(_ => actions.stopPolling())
      ), { dispatch: false });

     public continuePolling$ = createEffect(() => this.actions$.pipe(
        ofType(actions.getData),
        tap(_ => this.logger.debug('continue polling')),
        delay(8000),
        switchMap(_ => this.pollData())
      ), { dispatch: false });

    private pollData() {
       if (!this.isPollingActive)
         return;
    }
</code>```

In my "StopPolling" I set a flag, but if it is restarted (ie isPollingActive is et back to true) while I am in the delay(8000), the delay will exit and I will end up with the getData being called multiple times.

So, my question is, is there a way to step the switchMap(_ => this.pollData()) being called after the delay - ie is there someway to "force the delay to exit" before the timeout period?

Almost (if you know C#/.net). like a manualResetEvent.WaitOne(8000) which can be cancelled by calling Set() on the manualResetEvent object.

答:
You can create an observable that emits after a delay using timer and unsubscribe with takeUntil to exit early:

```<code>this.actions$.pipe(
  ofType(actions.getData),
  tap(_ => this.logger.debug('continue polling')),
  switchMap(_ =>
    timer(8000).pipe(
      takeUntil(this.actions$.pipe(ofType(actions.stopPolling))),
      concatMap(() => this.pollData())
    )
)
</code>```

This might also allow you to remove the side-effect this.isPollingActive = false and ensure that the control flow remains within the observable.

Body:
I am using a polling scheme in my Angular application using NgRx.

To simplify things, I have something like the following:

    public stopPolling$ = createEffect(() => this.actions$.pipe(
        ofType(actions.stopPolling),
        tap(_ => this.isPollingActive = false),
        map(_ => actions.stopPolling())
      ), { dispatch: false });

     public continuePolling$ = createEffect(() => this.actions$.pipe(
        ofType(actions.getData),
        tap(_ => this.logger.debug('continue polling')),
        delay(8000),
        switchMap(_ => this.pollData())
      ), { dispatch: false });

    private pollData() {
       if (!this.isPollingActive)
         return;
    }

In my "StopPolling" I set a flag, but if it is restarted (ie isPollingActive is et back to true) while I am in the delay(8000), the delay will exit and I will end up with the getData being called multiple times.

So, my question is, is there a way to step the switchMap(_ => this.pollData()) being called after the delay - ie is there someway to "force the delay to exit" before the timeout period?

Almost (if you know C#/.net). like a manualResetEvent.WaitOne(8000) which can be cancelled by calling Set() on the manualResetEvent object.

Body:
You can create an observable that emits after a delay using timer and unsubscribe with takeUntil to exit early:

this.actions$.pipe(
  ofType(actions.getData),
  tap(_ => this.logger.debug('continue polling')),
  switchMap(_ =>
    timer(8000).pipe(
      takeUntil(this.actions$.pipe(ofType(actions.stopPolling))),
      concatMap(() => this.pollData())
    )
)

This might also allow you to remove the side-effect this.isPollingActive = false and ensure that the control flow remains within the observable.


问:
Julia create multiple slightly modified versions of a function
I have a function that looks like

```<code>function eom!(du, u, p)
    @views a, b = u[:,1], u[:,2];
    @views da, db = du[:,1], du[:,2];

    y = # some stuff involving p and a;
    da .= f(a, b, y);
    db .= g(b, a);
end
</code>```

I now want to create a second a function that is the exact same, except the last line reads

```<code>db .= g(b, y);
</code>```

How can I do this most cleanly? Of course, I could just copy and paste and give the functions slightly different names, but this seems unideal, especially if, as is plausible, I later want more functions where the second argument of g could be something else. Is there perhaps a way that I could pass into the function eom! an expression (via the argument p) that would specify the second argument of g? Or is there a way I could make some function eom_generator which can output all of the functions that I want? Perhaps macros are the central tool in doing this, but I am not sure.

答:
You could produce a closure:

```<code>function eom_generator(g)
    return function eom!(du, u, p)
        @views a, b = u[:,1], u[:,2]
        @views da, db = du[:,1], du[:,2]

        y = nothing # some stuff involving p and a;
        da .= f(a, b, y)
        db .= g(a, b, y)
    end
end

const eom1! = eom_generator((a, b, y) -> g(b, a))
const eom2! = eom_generator((a, b, y) -> g(b, y))
</code>```

But since this is at the core of a differential equation, be sure to test whether you don't have any performance issues that way.

If you decide that you really need metaprogramming, you can use @eval in a loop:

```<code>for (i, expr) in enumerate((:(g(b, a)), :(g(b, y))))
    @eval function $(Symbol("eom", i, "!"))(du, u, p)
            @views a, b = u[:,1], u[:,2]
            @views da, db = du[:,1], du[:,2]

            y = nothing # some stuff involving p and a;
            da .= f(a, b, y)
            db .= $expr
        end
    end
end
</code>```

Body:
I have a function that looks like

function eom!(du, u, p)
    @views a, b = u[:,1], u[:,2];
    @views da, db = du[:,1], du[:,2];

    y = # some stuff involving p and a;
    da .= f(a, b, y);
    db .= g(b, a);
end

I now want to create a second a function that is the exact same, except the last line reads

db .= g(b, y);

How can I do this most cleanly? Of course, I could just copy and paste and give the functions slightly different names, but this seems unideal, especially if, as is plausible, I later want more functions where the second argument of g could be something else. Is there perhaps a way that I could pass into the function eom! an expression (via the argument p) that would specify the second argument of g? Or is there a way I could make some function eom_generator which can output all of the functions that I want? Perhaps macros are the central tool in doing this, but I am not sure.

Body:
You could produce a closure:

function eom_generator(g)
    return function eom!(du, u, p)
        @views a, b = u[:,1], u[:,2]
        @views da, db = du[:,1], du[:,2]

        y = nothing # some stuff involving p and a;
        da .= f(a, b, y)
        db .= g(a, b, y)
    end
end

const eom1! = eom_generator((a, b, y) -> g(b, a))
const eom2! = eom_generator((a, b, y) -> g(b, y))

But since this is at the core of a differential equation, be sure to test whether you don't have any performance issues that way.

If you decide that you really need metaprogramming, you can use @eval in a loop:

for (i, expr) in enumerate((:(g(b, a)), :(g(b, y))))
    @eval function $(Symbol("eom", i, "!"))(du, u, p)
            @views a, b = u[:,1], u[:,2]
            @views da, db = du[:,1], du[:,2]

            y = nothing # some stuff involving p and a;
            da .= f(a, b, y)
            db .= $expr
        end
    end
end


问:
How to keep camera rotation pointed at origin while moving its position in three.js?
So I want to move my cameras position around in three.js, but as I move it, I want the cameras rotation to automatically update to point at the origin.

So if i have the camera set as:

```<code> camera.position.set(25,25,25)
</code>```

I would like the camera.rotation to be updated so that it is facing the world origin.

答:
You can set the camera to look at or target a specific position in your scene but using the lookAt() method - https://threejs.org/docs/#api/en/core/Object3D.lookAt

In this case, setting camera.lookAt(0,0,0) will point to the centre of the 'world'.

Body:
So I want to move my cameras position around in three.js, but as I move it, I want the cameras rotation to automatically update to point at the origin.

So if i have the camera set as:

 camera.position.set(25,25,25)

I would like the camera.rotation to be updated so that it is facing the world origin.


问:
WPF GridView sorting when clicking column header
I am implementing a GridView which sorts by clicking on the column headers. I was finding one of the standard solutions, but it did not work for me.

I have a header "P" while both the content of the cells and the header should centered (alignment). The header has a different label "P" than the binding "Photo".

```<code><GridViewColumn Width="30" Header="P">

    <GridViewColumn.HeaderContainerStyle>
        <Style TargetType="{x:Type GridViewColumnHeader}">
            <Setter Property="HorizontalContentAlignment" Value="Center"/>
        </Style>
    </GridViewColumn.HeaderContainerStyle>

        <GridViewColumn.CellTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Photo}" HorizontalAlignment="Center"/>
        </DataTemplate>
    </GridViewColumn.CellTemplate>

</GridViewColumn>
</code>```

The code that handels the column click is as follows below (from the Mircosoft site).

It assumes that there is a DisplayMemberBinding

var columnBinding = headerClicked.Column.DisplayMemberBinding as Binding;
```

<p>Which I do not have, otherwise the column header and content is not centered. </p>

<p>Otherwise it takes the label of the column as property for sorting.</p>

<pre class="lang-cs prettyprint-override"><code>var sortBy = columnBinding?.Path.Path ?? headerClicked.Column.Header as string;
</code>```

This does not work either because my label is "P" and the property is "Photo".

Any other idea?

```<code>internal void HandleOverviewColumnHeaderClicked(GridViewColumnHeader headerClicked)
{
    ListSortDirection direction;

    if (headerClicked != null)
    {
        if (headerClicked.Role != GridViewColumnHeaderRole.Padding)
        {
            if (headerClicked != _lastHeaderClicked)
            {
                direction = ListSortDirection.Ascending;
            }
            else
            {
                if (_lastDirection == ListSortDirection.Ascending)
                {
                    direction = ListSortDirection.Descending;
                }
                else
                {
                    direction = ListSortDirection.Ascending;
                }
            }

            var columnBinding = headerClicked.Column.DisplayMemberBinding as Binding;
            var sortBy = columnBinding?.Path.Path ?? headerClicked.Column.Header as string;

            Sort(sortBy, direction);

            if (direction == ListSortDirection.Ascending)
            {
                headerClicked.Column.HeaderTemplate = _window.Resources["HeaderTemplateArrowUp"] as DataTemplate;
            }
            else
            {
                headerClicked.Column.HeaderTemplate = _window.Resources["HeaderTemplateArrowDown"] as DataTemplate;
            }

            // Remove arrow from previously sorted header
            if (_lastHeaderClicked != null && _lastHeaderClicked != headerClicked)
            {
                _lastHeaderClicked.Column.HeaderTemplate = null;
            }

            _lastHeaderClicked = headerClicked;
            _lastDirection = direction;
        }
    }
}
</code>```

答:
```<code><GridViewColumn DisplayMemberBinding="{Binding MyData}">
      <GridViewColumnHeader Content="MyHeader" Click="GridViewColumnHeader_Click" />
</GridViewColumn>
</code>```

and

```<code>        GridViewColumnHeader _lastHeaderClicked = null;
        ListSortDirection _lastDirection = ListSortDirection.Ascending;

        private void GridViewColumnHeader_Click(object sender, RoutedEventArgs e)
        {
            var headerClicked = e.OriginalSource as GridViewColumnHeader;
            ListSortDirection direction;

            if (headerClicked != null)
            {
                if (headerClicked.Role != GridViewColumnHeaderRole.Padding)
                {
                    if (headerClicked != _lastHeaderClicked)
                    {
                        direction = ListSortDirection.Ascending;
                    }
                    else
                    {
                        if (_lastDirection == ListSortDirection.Ascending)
                        {
                            direction = ListSortDirection.Descending;
                        }
                        else
                        {
                            direction = ListSortDirection.Ascending;
                        }
                    }

                    var columnBinding = headerClicked.Column.DisplayMemberBinding as Binding;
                    var sortBy = columnBinding?.Path.Path ?? headerClicked.Column.Header as string;

                    Sort(sortBy, direction);

                    if (direction == ListSortDirection.Ascending)
                    {
                        headerClicked.Column.HeaderTemplate =
                          Resources["HeaderTemplateArrowUp"] as DataTemplate;
                    }
                    else
                    {
                        headerClicked.Column.HeaderTemplate =
                          Resources["HeaderTemplateArrowDown"] as DataTemplate;
                    }

                    // Remove arrow from previously sorted header
                    if (_lastHeaderClicked != null && _lastHeaderClicked != headerClicked)
                    {
                        _lastHeaderClicked.Column.HeaderTemplate = null;
                    }

                    _lastHeaderClicked = headerClicked;
                    _lastDirection = direction;
                }
            }
        }

        private void Sort(string sortBy, ListSortDirection direction)
        {
            ICollectionView dataView =
              CollectionViewSource.GetDefaultView(lv.ItemsSource);

            dataView.SortDescriptions.Clear();
            SortDescription sd = new SortDescription(sortBy, direction);
            dataView.SortDescriptions.Add(sd);
            dataView.Refresh();
        }
</code>```

Body:
I am implementing a GridView which sorts by clicking on the column headers. I was finding one of the standard solutions, but it did not work for me.

I have a header "P" while both the content of the cells and the header should centered (alignment). The header has a different label "P" than the binding "Photo".

<GridViewColumn Width="30" Header="P">

    <GridViewColumn.HeaderContainerStyle>

    </GridViewColumn.HeaderContainerStyle>

        <GridViewColumn.CellTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Photo}" HorizontalAlignment="Center"/>
        </DataTemplate>
    </GridViewColumn.CellTemplate>

</GridViewColumn>

The code that handels the column click is as follows below (from the Mircosoft site).

It assumes that there is a DisplayMemberBinding

var columnBinding = headerClicked.Column.DisplayMemberBinding as Binding;

Which I do not have, otherwise the column header and content is not centered.

Otherwise it takes the label of the column as property for sorting.

var sortBy = columnBinding?.Path.Path ?? headerClicked.Column.Header as string;

This does not work either because my label is "P" and the property is "Photo".

Any other idea?

internal void HandleOverviewColumnHeaderClicked(GridViewColumnHeader headerClicked)
{
    ListSortDirection direction;

    if (headerClicked != null)
    {
        if (headerClicked.Role != GridViewColumnHeaderRole.Padding)
        {
            if (headerClicked != _lastHeaderClicked)
            {
                direction = ListSortDirection.Ascending;
            }
            else
            {
                if (_lastDirection == ListSortDirection.Ascending)
                {
                    direction = ListSortDirection.Descending;
                }
                else
                {
                    direction = ListSortDirection.Ascending;
                }
            }

            var columnBinding = headerClicked.Column.DisplayMemberBinding as Binding;
            var sortBy = columnBinding?.Path.Path ?? headerClicked.Column.Header as string;

            Sort(sortBy, direction);

            if (direction == ListSortDirection.Ascending)
            {
                headerClicked.Column.HeaderTemplate = _window.Resources["HeaderTemplateArrowUp"] as DataTemplate;
            }
            else
            {
                headerClicked.Column.HeaderTemplate = _window.Resources["HeaderTemplateArrowDown"] as DataTemplate;
            }

            // Remove arrow from previously sorted header
            if (_lastHeaderClicked != null && _lastHeaderClicked != headerClicked)
            {
                _lastHeaderClicked.Column.HeaderTemplate = null;
            }

            _lastHeaderClicked = headerClicked;
            _lastDirection = direction;
        }
    }
}

Body:
<GridViewColumn DisplayMemberBinding="{Binding MyData}">
      <GridViewColumnHeader Content="MyHeader" Click="GridViewColumnHeader_Click" />
</GridViewColumn>

and

        GridViewColumnHeader _lastHeaderClicked = null;
        ListSortDirection _lastDirection = ListSortDirection.Ascending;

        private void GridViewColumnHeader_Click(object sender, RoutedEventArgs e)
        {
            var headerClicked = e.OriginalSource as GridViewColumnHeader;
            ListSortDirection direction;

            if (headerClicked != null)
            {
                if (headerClicked.Role != GridViewColumnHeaderRole.Padding)
                {
                    if (headerClicked != _lastHeaderClicked)
                    {
                        direction = ListSortDirection.Ascending;
                    }
                    else
                    {
                        if (_lastDirection == ListSortDirection.Ascending)
                        {
                            direction = ListSortDirection.Descending;
                        }
                        else
                        {
                            direction = ListSortDirection.Ascending;
                        }
                    }

                    var columnBinding = headerClicked.Column.DisplayMemberBinding as Binding;
                    var sortBy = columnBinding?.Path.Path ?? headerClicked.Column.Header as string;

                    Sort(sortBy, direction);

                    if (direction == ListSortDirection.Ascending)
                    {
                        headerClicked.Column.HeaderTemplate =
                          Resources["HeaderTemplateArrowUp"] as DataTemplate;
                    }
                    else
                    {
                        headerClicked.Column.HeaderTemplate =
                          Resources["HeaderTemplateArrowDown"] as DataTemplate;
                    }

                    // Remove arrow from previously sorted header
                    if (_lastHeaderClicked != null && _lastHeaderClicked != headerClicked)
                    {
                        _lastHeaderClicked.Column.HeaderTemplate = null;
                    }

                    _lastHeaderClicked = headerClicked;
                    _lastDirection = direction;
                }
            }
        }

        private void Sort(string sortBy, ListSortDirection direction)
        {
            ICollectionView dataView =
              CollectionViewSource.GetDefaultView(lv.ItemsSource);

            dataView.SortDescriptions.Clear();
            SortDescription sd = new SortDescription(sortBy, direction);
            dataView.SortDescriptions.Add(sd);
            dataView.Refresh();
        }


问:
syntax error 'EOL while scanning string literal (<unknown>, line 9)'

import os

async def cmdrun(client, message, prefix):
    cmd = message.content.split(' ')[0].split(prefix)[1]
    args = message.content.split(cmd)[1][1:].split(' ')
    for filename in os.listdir('./commands'):
        if filename.endswith('.py'):
            imported = filename.split('.py')[0]
            strin = f"from commands.{imported} import name, aliases, run\nx = name()\ny = aliases()\nawait message.channel.send(x + y)\nif x == {cmd} or {cmd} in y:\n    await run(client, message, args)"
            exec(strin)
```

I am making a discord bot with discord.py.
What is the error

答:
That error is definitely always associated with a missing double-inverted/single-inverted comma. Here's my suggestions:

Try running the prepared lines of code you're attempting to use as is.

I couldn't find anything in the new documentation, but the old
documentation suggest that ...in the current implementation, multi-line compound statements must end with a newline: exec "for v in seq:\n\tprint v\n" works, but exec "for v in seq:\n\tprint v" fails with SyntaxError. Perhaps try adding a new line character at the end?

Try using triple inverted commas.

Hope this solves the issue!

Body:
import os

async def cmdrun(client, message, prefix):
    cmd = message.content.split(' ')[0].split(prefix)[1]
    args = message.content.split(cmd)[1][1:].split(' ')
    for filename in os.listdir('./commands'):
        if filename.endswith('.py'):
            imported = filename.split('.py')[0]
            strin = f"from commands.{imported} import name, aliases, run\nx = name()\ny = aliases()\nawait message.channel.send(x + y)\nif x == {cmd} or {cmd} in y:\n    await run(client, message, args)"
            exec(strin)

I am making a discord bot with discord.py.
What is the error


问:
Always failed to close channel (netty) from server-side when the client has been physically killed
It's a web-socket application based on netty. However, when the client is physically killed without sending a CloseWebSocketFrame, server needs to know the channel has been closed and do some cleaning work. IdleStateHandler is used to monitor whether the channel is idle.

Here is the channel handler pipeline.

```<code>public void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();
    SSLEngine sslEngine = new SSLServiceBase().getSSLContext().createSSLEngine();
    sslEngine.setUseClientMode(false);
    sslEngine.setNeedClientAuth(true);
    ... // business process
    pipeline.addLast(new IdleStateHandler(30, 10, 0, TimeUnit.SECONDS));
    pipeline.addLast(new HeartbeatHandler());
}
</code>```

This is the userEventTriggered method of HeartbeatHandler which is used to do some cleaning work when channel is closed from the client abnormally.

```<code>public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    if (evt instanceof IdleStateEvent) {
        IdleStateEvent event = (IdleStateEvent) evt;
        if (IdleState.WRITER_IDLE.equals(event.state())) {
            ctx.writeAndFlush(new PingWebSocketFrame()).addListener(future -> {
                if (!future.isSuccess()) {
                    ChannelFuture closeFuture = ctx.channel().close();
                    if (closeFuture.isSuccess()) {
                        System.out.println("ping faild, channel close successfully");
                    } else {
                        System.out.println("ping failed, channel close failed");
                    }
                } else {
                    System.out.println("Ping succeed, keep the channel.");
                }
            });
        }
    } else {
        super.userEventTriggered(ctx, evt);
    }
}
</code>```

Actually, I'm continuously getting 'close failed', and the channel is still alive from the server view. Could anyone let me know why the channel can't be closed or how to close?  Thanks a lot.

答:
I suspect the close was not done yet (remember it is an async operation). Change the code to:

```<code>public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    if (evt instanceof IdleStateEvent) {
        IdleStateEvent event = (IdleStateEvent) evt;
        if (IdleState.WRITER_IDLE.equals(event.state())) {
            ctx.writeAndFlush(new PingWebSocketFrame()).addListener(future -> {
                if (!future.isSuccess()) {
                    ctx.close().addListener(closeFuture -> {
                        If (closeFuture.isSuccess()) {
                            System.out.println("ping faild, channel close successfully");
                        } else {
                            System.out.println("ping failed, channel close failed");
                            // TODO: You may also want to log the reason why the close operation failed.
                            //       closeFuture.cause() will contain why.
                        }
                    });
                } else {
                    System.out.println("Ping succeed, keep the channel.");
                }
        });
    }
} else {
    super.userEventTriggered(ctx, evt);
}
</code>```

}

Body:
It's a web-socket application based on netty. However, when the client is physically killed without sending a CloseWebSocketFrame, server needs to know the channel has been closed and do some cleaning work. IdleStateHandler is used to monitor whether the channel is idle.

Here is the channel handler pipeline.

public void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();
    SSLEngine sslEngine = new SSLServiceBase().getSSLContext().createSSLEngine();
    sslEngine.setUseClientMode(false);
    sslEngine.setNeedClientAuth(true);
    ... // business process
    pipeline.addLast(new IdleStateHandler(30, 10, 0, TimeUnit.SECONDS));
    pipeline.addLast(new HeartbeatHandler());
}

This is the userEventTriggered method of HeartbeatHandler which is used to do some cleaning work when channel is closed from the client abnormally.

public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    if (evt instanceof IdleStateEvent) {
        IdleStateEvent event = (IdleStateEvent) evt;
        if (IdleState.WRITER_IDLE.equals(event.state())) {
            ctx.writeAndFlush(new PingWebSocketFrame()).addListener(future -> {
                if (!future.isSuccess()) {
                    ChannelFuture closeFuture = ctx.channel().close();
                    if (closeFuture.isSuccess()) {
                        System.out.println("ping faild, channel close successfully");
                    } else {
                        System.out.println("ping failed, channel close failed");
                    }
                } else {
                    System.out.println("Ping succeed, keep the channel.");
                }
            });
        }
    } else {
        super.userEventTriggered(ctx, evt);
    }
}

Actually, I'm continuously getting 'close failed', and the channel is still alive from the server view. Could anyone let me know why the channel can't be closed or how to close?  Thanks a lot.

Body:
I suspect the close was not done yet (remember it is an async operation). Change the code to:

public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    if (evt instanceof IdleStateEvent) {
        IdleStateEvent event = (IdleStateEvent) evt;
        if (IdleState.WRITER_IDLE.equals(event.state())) {
            ctx.writeAndFlush(new PingWebSocketFrame()).addListener(future -> {
                if (!future.isSuccess()) {
                    ctx.close().addListener(closeFuture -> {
                        If (closeFuture.isSuccess()) {
                            System.out.println("ping faild, channel close successfully");
                        } else {
                            System.out.println("ping failed, channel close failed");
                            // TODO: You may also want to log the reason why the close operation failed.
                            //       closeFuture.cause() will contain why.
                        }
                    });
                } else {
                    System.out.println("Ping succeed, keep the channel.");
                }
        });
    }
} else {
    super.userEventTriggered(ctx, evt);
}

}


问:
Convert object of objects to array
I work on a Angular Project and I have a little issue with an object..

I have an object with objects inside :

```<code>P3E051V:{
    lot: "P3E051V"
    quantite: 5400
},
P3E052V:{
    lot: "P3E052V"
    quantite: 5400
},
P3E054V:{
    lot: "P3E054V"
    quantite: 10800
}
</code>```

What I would like to do is to display a table like this :
image of the table

But I can't loop on an object with *ngFor.
I tried to use Object.entries(myObject) but it doesn't work.

Anyone have an idea to solve this ?

Thanks

答:
const objs = {P3E051V:{
    lot: "P3E051V",
    quantite: 5400
},
P3E052V:{
    lot: "P3E052V",
    quantite: 5400
},
P3E054V:{
    lot: "P3E054V",
    quantite: 10800
}}

console.log('the key + the object', Object.entries(objs));
console.log('just the internal object', Object.entries(objs).map(o => o[1]));```

Here's what objectt.entries does

Title: Convert object of objects to array

Body:
I work on a Angular Project and I have a little issue with an object..

I have an object with objects inside :

P3E051V:{
    lot: "P3E051V"
    quantite: 5400
},
P3E052V:{
    lot: "P3E052V"
    quantite: 5400
},
P3E054V:{
    lot: "P3E054V"
    quantite: 10800
}

What I would like to do is to display a table like this :
image of the table

But I can't loop on an object with *ngFor.
I tried to use Object.entries(myObject) but it doesn't work.

Anyone have an idea to solve this ?

Thanks

Body:
const objs = {P3E051V:{
    lot: "P3E051V",
    quantite: 5400
},
P3E052V:{
    lot: "P3E052V",
    quantite: 5400
},
P3E054V:{
    lot: "P3E054V",
    quantite: 10800
}}

console.log('the key + the object', Object.entries(objs));
console.log('just the internal object', Object.entries(objs).map(o => o[1]));

Here's what objectt.entries does


问:
How do I rewrite this code for V8 from Rhino?
I used to a script on GAS.
Because I do manage attendance by Chat and Google spread sheet with GAS.
Chat tool is Chat work.
It works on Gas(Rhino).
But It doesn't work V8.

I tried to rewrite line19 for each (var obj in json){ to for (var obj in json){

Please tell me what is bad...
Which should I rewrite it?

```<code>function recordTime(){
  /*Sheet setting*/
  var wsData = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("data"); //DataSheetSetting
  var wsStaff = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("coworkers"); //CoworkersMasterSetting
  /*ChatworkURLrequest*/
  var params = {
    headers : {"X-ChatWorkToken" : 'anynumber'},
    method : "get"
  };
  var roomID = anynumber; //ROOMID
  var url = "https://api.chatwork.com/v2/rooms/" + roomID + "/messages?force=0"; //GetMessageFromGroupchat
  try{
    var respons = UrlFetchApp.fetch(url, params); //GetResponseFromChatworkAPIendpoint
    var json = JSON.parse(respons.getContentText()); //Returnjson
    for each(var obj in json){　//I understand that I should rewrite "for (var obj in json){
      /*Get YMDhm and ID*/
      var date = new Date(obj.send_time*1000);
      var date_D = new Date(date.getFullYear(),date.getMonth(),date.getDate(),0,0,0);
      var date_T = new Date(date.getFullYear(),date.getMonth(),date.getDate(),date.getHours(),date.getMinutes(),0);
      var date_TH = new Date(0,0,0,date.getHours(),date.getMinutes(),0);
      /*dateToSn Setting*/
      var MILLIS_DIFFERENCE = 9 * 60 * 60 * 1000;
      var COEFFICIENT = 24 * 60 * 60 * 1000;
      var DATES_OFFSET = 70 * 365 + 17 + 1 + 1;
      function dateToSn(date){ //Date→Serial
        return convertUt2Sn(date.getTime());
      }
      function convertUt2Sn(unixTimeMillis){ //UNIX→Serial
        return (unixTimeMillis + MILLIS_DIFFERENCE) / COEFFICIENT + DATES_OFFSET;
      }
      /*findRow*/
      function findRow(sheet,val,col){
        var dat = sheet.getDataRange().getValues();
        for(var i=1;i<dat.length;i++){
          if(dat[i][col-1] === val){
            return i+1;
          }
        }
        return 0;
      }
      /*StaffID*/
      var staffID = wsStaff.getRange(findRow(wsStaff,obj.account.account_id,1),2).getValue();
      var dataRow=findRow(wsData,dateToSn(date_D)+staffID.toString(),1);
      if(obj.body.match(/出勤/)){
        if(!dataRow){
          wsData.appendRow(
            ["=INDIRECT(\"RC[1]\",FALSE) & INDIRECT(\"RC[2]\",FALSE)",date_D,
             "=VLOOKUP(" + obj.account.account_id + ",'coworkers'!A:B,2,FALSE)","=VLOOKUP(" + obj.account.account_id + ",'coworkers'!A:E,4,FALSE)","出勤",date_T
            ]);
        }
      }else if(obj.body.match(/外出/) || obj.body.match(/直行/)){
        if(dataRow){
          var rng = wsData.getRange(dataRow,8);
          if(!rng.getValue()){
            rng.setValue(date_T);
          }
        }
      }else if(obj.body.match(/帰社/) || obj.body.match(/直帰/)){
        if(dataRow){
          var rng = wsData.getRange(dataRow,9);
          if(!rng.getValue()){
            rng.setValue(date_T);
          }
        }
      }else if (obj.body.match(/中抜け/)){
        if(dataRow){
          var rng = wsData.getRange(dataRow,10);
          if(!rng.getValue()){
            rng.setValue(date_T);
          }
        }
      }else if (obj.body.match(/戻り/)){
        if(dataRow){
          var rng = wsData.getRange(dataRow,11);
          if(!rng.getValue()){
            rng.setValue(date_T);
          }
        }
      }else if(obj.body.match(/退勤/)){
        if(dataRow){
          var rng = wsData.getRange(dataRow,7);
          if(!rng.getValue()){
            rng.setValue(date_T);
          }
        }
      }
    }
  }catch(e){
    Logger.log('Error');
    Logger.log(e.message);
  }
}
</code>```

答:
See the official documention here: https://developers.google.com/apps-script/guides/v8-runtime/migration#avoid_for_eachvariable_in_object

In short:

```<code>for each (var obj in json) {
  do_something_with(obj);
}
</code>```

becomes

```<code>for (var obj of json) {
  do_something_with(obj);
}
</code>```

Note that in changed to of, which makes the for-loop iterate over values rather than keys. Accordingly, you can also use a traditional for-in loop, and manually use the key to get the value:

```<code>for (var obj_key in json) {
  var obj = json[obj_key];
  do_something_with(obj);
}
</code>```

You can also use let instead of var to get block-scoped variables, which are generally more intuitive to use, but that's an unrelated change and is not required if you just want things to work.

Body:
I used to a script on GAS.
Because I do manage attendance by Chat and Google spread sheet with GAS.
Chat tool is Chat work.
It works on Gas(Rhino).
But It doesn't work V8.

I tried to rewrite line19 for each (var obj in json){ to for (var obj in json){

Please tell me what is bad...
Which should I rewrite it?

function recordTime(){
  /*Sheet setting*/
  var wsData = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("data"); //DataSheetSetting
  var wsStaff = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("coworkers"); //CoworkersMasterSetting
  /*ChatworkURLrequest*/
  var params = {
    headers : {"X-ChatWorkToken" : 'anynumber'},
    method : "get"
  };
  var roomID = anynumber; //ROOMID
  var url = "https://api.chatwork.com/v2/rooms/" + roomID + "/messages?force=0"; //GetMessageFromGroupchat
  try{
    var respons = UrlFetchApp.fetch(url, params); //GetResponseFromChatworkAPIendpoint
    var json = JSON.parse(respons.getContentText()); //Returnjson
    for each(var obj in json){　//I understand that I should rewrite "for (var obj in json){
      /*Get YMDhm and ID*/
      var date = new Date(obj.send_time*1000);
      var date_D = new Date(date.getFullYear(),date.getMonth(),date.getDate(),0,0,0);
      var date_T = new Date(date.getFullYear(),date.getMonth(),date.getDate(),date.getHours(),date.getMinutes(),0);
      var date_TH = new Date(0,0,0,date.getHours(),date.getMinutes(),0);
      /*dateToSn Setting*/
      var MILLIS_DIFFERENCE = 9 * 60 * 60 * 1000;
      var COEFFICIENT = 24 * 60 * 60 * 1000;
      var DATES_OFFSET = 70 * 365 + 17 + 1 + 1;
      function dateToSn(date){ //Date→Serial
        return convertUt2Sn(date.getTime());
      }
      function convertUt2Sn(unixTimeMillis){ //UNIX→Serial
        return (unixTimeMillis + MILLIS_DIFFERENCE) / COEFFICIENT + DATES_OFFSET;
      }
      /*findRow*/
      function findRow(sheet,val,col){
        var dat = sheet.getDataRange().getValues();
        for(var i=1;i<dat.length;i++){
          if(dat[i][col-1] === val){
            return i+1;
          }
        }
        return 0;
      }
      /*StaffID*/
      var staffID = wsStaff.getRange(findRow(wsStaff,obj.account.account_id,1),2).getValue();
      var dataRow=findRow(wsData,dateToSn(date_D)+staffID.toString(),1);
      if(obj.body.match(/出勤/)){
        if(!dataRow){
          wsData.appendRow(
            ["=INDIRECT(\"RC[1]\",FALSE) & INDIRECT(\"RC[2]\",FALSE)",date_D,
             "=VLOOKUP(" + obj.account.account_id + ",'coworkers'!A:B,2,FALSE)","=VLOOKUP(" + obj.account.account_id + ",'coworkers'!A:E,4,FALSE)","出勤",date_T
            ]);
        }
      }else if(obj.body.match(/外出/) || obj.body.match(/直行/)){
        if(dataRow){
          var rng = wsData.getRange(dataRow,8);
          if(!rng.getValue()){
            rng.setValue(date_T);
          }
        }
      }else if(obj.body.match(/帰社/) || obj.body.match(/直帰/)){
        if(dataRow){
          var rng = wsData.getRange(dataRow,9);
          if(!rng.getValue()){
            rng.setValue(date_T);
          }
        }
      }else if (obj.body.match(/中抜け/)){
        if(dataRow){
          var rng = wsData.getRange(dataRow,10);
          if(!rng.getValue()){
            rng.setValue(date_T);
          }
        }
      }else if (obj.body.match(/戻り/)){
        if(dataRow){
          var rng = wsData.getRange(dataRow,11);
          if(!rng.getValue()){
            rng.setValue(date_T);
          }
        }
      }else if(obj.body.match(/退勤/)){
        if(dataRow){
          var rng = wsData.getRange(dataRow,7);
          if(!rng.getValue()){
            rng.setValue(date_T);
          }
        }
      }
    }
  }catch(e){
    Logger.log('Error');
    Logger.log(e.message);
  }
}

Body:
See the official documention here: https://developers.google.com/apps-script/guides/v8-runtime/migration#avoid_for_eachvariable_in_object

In short:

for each (var obj in json) {
  do_something_with(obj);
}

becomes

for (var obj of json) {
  do_something_with(obj);
}

Note that in changed to of, which makes the for-loop iterate over values rather than keys. Accordingly, you can also use a traditional for-in loop, and manually use the key to get the value:

for (var obj_key in json) {
  var obj = json[obj_key];
  do_something_with(obj);
}

You can also use let instead of var to get block-scoped variables, which are generally more intuitive to use, but that's an unrelated change and is not required if you just want things to work.


问:
Merge similar properties in a object into one property
I am new to python. I have a query to make.

```<code>b = [{a:"1",b:"6"},{a:"1",b:"89"},{a:"2",b:"16"},{a:"2",b:"99"}]
</code>```

i want to convert this into:

```<code>[{a:"1", b: "6. 89"}, {a:"2", "b": "16. 99"}]
</code>```

Any idea?

答:
You can try this:</p>

```<code>b = [{'a':"1",'b':"6"},{'a':"1",'b':"89"},{'a':"2",'b':"16"},{'a':"2",'b':"99"}]
n = 2
final = [b[i * n:(i + 1) * n] for i in range((len(b) + n - 1) // n )]
finalDict = []
for i in final:
    tempDict = {}
    for j in i:
        for h in j:
            if h not in tempDict.keys():
                tempDict[h] = j[h]
            else:
                if tempDict[h]!=j[h]:
                    tempDict[h]+="."+j[h]
    finalDict.append(tempDict)
print(finalDict)
</code>```

Body:
I am new to python. I have a query to make.

b = [{a:"1",b:"6"},{a:"1",b:"89"},{a:"2",b:"16"},{a:"2",b:"99"}]

i want to convert this into:

[{a:"1", b: "6. 89"}, {a:"2", "b": "16. 99"}]

Any idea?

Body:
You can try this:

b = [{'a':"1",'b':"6"},{'a':"1",'b':"89"},{'a':"2",'b':"16"},{'a':"2",'b':"99"}]
n = 2
final = [b[i * n:(i + 1) * n] for i in range((len(b) + n - 1) // n )]
finalDict = []
for i in final:
    tempDict = {}
    for j in i:
        for h in j:
            if h not in tempDict.keys():
                tempDict[h] = j[h]
            else:
                if tempDict[h]!=j[h]:
                    tempDict[h]+="."+j[h]
    finalDict.append(tempDict)
print(finalDict)


问:
How to import local json file data to my JavaScript variable?
I have data inside employees.json how can I get this data and assign it to the variable inside main.js?</p>

答:
This might help,Using the Fetch API:</p>

```<code>fetch("employees.json")
     .then(response => response.json())
      .then(json => data = (json));
</code>```

Body:
This might help,Using the Fetch API:

fetch("employees.json")
     .then(response => response.json())
      .then(json => data = (json));


问:
Patch Request using Spring Boot Java
I have a problem with my Patch Request with OpenShift Api.
This is my actual code :

```<code>
public static  HttpStatus PatchHTTPRequestCustomHeaders(String url, String data) {

        String Bearer = "ayJhbGciOiJSUzI1NiIs...";

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer "+Bearer);
        headers.set("X-HTTP-Method-Override",  "PATCH");
        headers.set("Content-Type", "application/json-patch+json");
        headers.set("Accept", "application/json");
        final HttpEntity<String> entity = new HttpEntity<String>(data, headers);
        RestTemplate restTemplate = new RestTemplate();

            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class, 1);
            if(response.getStatusCode() == HttpStatus.OK) {
                return HttpStatus.OK;
            }else {
                return null;
            }
    }
</code>```

The data contains a op replace or add or remove ...

Error on PostMan : 500 Internal Server Error

On Spring :

```<code>2020-02-14 10:12:28.918 ERROR 14944 --- [nio-8169-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.web.client.HttpClientErrorException$MethodNotAllowed: 405 Method Not Allowed: [{"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":"the server does not allow this method on the requested resource","reason":"MethodNotAllowed","details":{},"code":405}
]] with root cause

org.springframework.web.client.HttpClientErrorException$MethodNotAllowed: 405 Method Not Allowed: [{"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":"the server does not allow this method on the requested resource","reason":"MethodNotAllowed","details":{},"code":405}
]
</code>```

I don't have any problem with my Patch in Php...

I hope someone know the reason of what is happening.

EDIT :

```<code>public static void disableSSLCertificateChecking() {
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            @Override
            public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                // Not implemented
            }

            @Override
            public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                // Not implemented
            }
        } };

        try {
            SSLContext sc = SSLContext.getInstance("TLS");

            sc.init(null, trustAllCerts, new java.security.SecureRandom());

            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }
</code>```

答:
I got same problem when sending a Patch request.
Here is the solution for this:</p>

```<code>restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory())
</code>```

Title: Patch Request using Spring Boot Java

Body:
I have a problem with my Patch Request with OpenShift Api.
This is my actual code :

public static  HttpStatus PatchHTTPRequestCustomHeaders(String url, String data) {

        String Bearer = "ayJhbGciOiJSUzI1NiIs...";

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer "+Bearer);
        headers.set("X-HTTP-Method-Override",  "PATCH");
        headers.set("Content-Type", "application/json-patch+json");
        headers.set("Accept", "application/json");
        final HttpEntity<String> entity = new HttpEntity<String>(data, headers);
        RestTemplate restTemplate = new RestTemplate();

            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class, 1);
            if(response.getStatusCode() == HttpStatus.OK) {
                return HttpStatus.OK;
            }else {
                return null;
            }
    }

The data contains a op replace or add or remove ...

Error on PostMan : 500 Internal Server Error

On Spring :

2020-02-14 10:12:28.918 ERROR 14944 --- [nio-8169-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.web.client.HttpClientErrorException$MethodNotAllowed: 405 Method Not Allowed: [{"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":"the server does not allow this method on the requested resource","reason":"MethodNotAllowed","details":{},"code":405}
]] with root cause

org.springframework.web.client.HttpClientErrorException$MethodNotAllowed: 405 Method Not Allowed: [{"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":"the server does not allow this method on the requested resource","reason":"MethodNotAllowed","details":{},"code":405}
]

I don't have any problem with my Patch in Php...

I hope someone know the reason of what is happening.

EDIT :

public static void disableSSLCertificateChecking() {
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            @Override
            public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                // Not implemented
            }

            @Override
            public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                // Not implemented
            }
        } };

        try {
            SSLContext sc = SSLContext.getInstance("TLS");

            sc.init(null, trustAllCerts, new java.security.SecureRandom());

            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

Body:
I got same problem when sending a Patch request.
Here is the solution for this:

restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory())


问:
C#: How to transform String "[['x','x'],['x','x']]" into an Array without Split()ing?
The string looks like a 2-D array:

```<code>[['a;b;c','d','e'],['a;b;c;d','h','k'], ... ]
</code>```

But how do i evaluate it and transform it into 2D array in C# without using Split()?

答: It looks to me like a JSON string. If it is, then use the DataContractJsonSerializer to deserialize the string into a string[][]

Body:
The string looks like a 2-D array:

[['a;b;c','d','e'],['a;b;c;d','h','k'], ... ]

But how do i evaluate it and transform it into 2D array in C# without using Split()?


问:
jdk.serialFilter is not working for restricting depth of TreeMap in Java (prevent DoS attack through Java)
How to prevent DoS attack through Java TreeMap?

My code has an API which accepts a Map object. Now I want to prevent client to send Map objects of certain length.

Now maxarray in jdk.serialFilter is able to prevent the client sending a HashMap object of size > maxarray.

I want to do the same for TreeMap too. But maxarray field is not working for TreeMap. It is unable to reject that request.

I set maxdepth size too. But nothing is working.

Can anyone please help me with this?

答:
Searching the OpenJDK for getJavaObjectInputStreamAccess().checkArray turns up maxarray checking in these classes.

java.util.ArrayDeque

java.util.ArrayList

java.util.Collection

java.util.HashMap

java.util.HashSet

java.util.Hashtable

java.util.IdentityHashMap

java.util.ImmutableCollections

java.util.PriorityBlockingQueue

java.util.PriorityQueue

java.util.Properties

java.util.concurrent.CopyOnArrayList

javax.management.openmbean.TabularDataSupport

And java.io.ObjectInputStream uses it, of course.

What is maxarray attempting to defend against? Presumably malicious streams causing allocation of extremely disproportionate amount of memory. But this isn't cumulative, so would appear to be entirely ineffective against anything new.

TreeMap doesn't use arrays, so maxarray couldn't apply. If we wanted to limit the size of a TreeMap as part of efforts to reduce the maximum size of deserialised objects, then maxrefs and maxbytes are appropriate as with any other serialisable object.


问:
React javascript check if string contains specific word and add something like link react router / styles to specific word
is there any solution how to check strings(ex:Google) and add Link react router into specific word(ex:Google)?

example like this photo

before

after

this is my very simple code

```<code>import React, { Component } from "react";
import { Link } from "react-router-dom";

class App extends Component {
  state = {
    text: "Google is my Friend, Google is Search Engine, Thanks to google"
    website: "Google Friend"
  };

  render() {
    let text = null;
    if (this.state.text.includes(this.state.website)) {
      return (text = (
        <div>
          <Link to={"/example"}>Google </Link> then state text
        </div>
      ));
    }
    return <div>{text}</div>;
  }
}

export default App;
</code>```

it would be more helpful if you can show me how to add style inside specific word(ex: Google) like changing color, or adding bold/italic or anything

thanks

答:
You can do it like this:</p>

```<code>{this.state.text.split(" ").map(text => {
   return text === "Google" ? <Link to="/google">Google</Link> : text;
})}
</code>```

Body:
is there any solution how to check strings(ex:Google) and add Link react router into specific word(ex:Google)?

example like this photo

before

after

this is my very simple code

import React, { Component } from "react";
import { Link } from "react-router-dom";

class App extends Component {
  state = {
    text: "Google is my Friend, Google is Search Engine, Thanks to google"
    website: "Google Friend"
  };

  render() {
    let text = null;
    if (this.state.text.includes(this.state.website)) {
      return (text = (

          <Link to={"/example"}>Google </Link> then state text

      ));
    }
    return
{text}
;
  }
}

export default App;

it would be more helpful if you can show me how to add style inside specific word(ex: Google) like changing color, or adding bold/italic or anything

thanks

Body:
You can do it like this:

{this.state.text.split(" ").map(text => {
   return text === "Google" ? <Link to="/google">Google</Link> : text;
})}


问:
Connect javaEE to SQL Server?
I used to work in all my projects with MySQL.

But now I should develop a web application using JEE and SQL Server? Can we do it? If yes, what should I change in this connection part:

```<code>public class gestion extends HttpServlet {
    private static final long serialVersionUID = 1L;
     String urlPilote="com.mysql.cj.jdbc.Driver";//chemin pr xarger le pilote
        String urlBaseDonnees="jdbc:mysql://localhost/lydec?serverTimezone=UTC";//chemin de connexion a la bd
        Connection con=null;

    public gestion() {
        super();        // TODO Auto-generated constructor stub
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out =response.getWriter();
        try {
            Class.forName(urlPilote);
            con=DriverManager.getConnection(urlBaseDonnees, "root", "");
            String sql="select * from poste ";
            PreparedStatement ps=con.prepareStatement(sql);
            ResultSet rs=ps.executeQuery();

    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
</code>```

答:
It's better idea to configure application server to open connection for you. Application server will manage the connection pool, lifecycle etc.

for jboss: How can we configure database connection from JBOSS?

Title: Connect javaEE to SQL Server?

Body:
I used to work in all my projects with MySQL.

But now I should develop a web application using JEE and SQL Server? Can we do it? If yes, what should I change in this connection part:

public class gestion extends HttpServlet {
    private static final long serialVersionUID = 1L;
     String urlPilote="com.mysql.cj.jdbc.Driver";//chemin pr xarger le pilote
        String urlBaseDonnees="jdbc:mysql://localhost/lydec?serverTimezone=UTC";//chemin de connexion a la bd
        Connection con=null;

    public gestion() {
        super();        // TODO Auto-generated constructor stub
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out =response.getWriter();
        try {
            Class.forName(urlPilote);
            con=DriverManager.getConnection(urlBaseDonnees, "root", "");
            String sql="select * from poste ";
            PreparedStatement ps=con.prepareStatement(sql);
            ResultSet rs=ps.executeQuery();

    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


问:
oracle pl-sql find the 3rd wednesday of a given date
Currently I have a process which takes a date variable EG: '01-MAR-2026', it then iterates over this date checking if the day is wednesday. If so then increment a counter else add 1 day and check again.
This exits when the wednesday count is = 3.

```<code>IF (to_char(v_Date,'dy') = 'wed') THEN
        v_NumWed := v_NumWed + 1;
END IF;

WHILE (v_NumWed != 3) LOOP
    v_Date := v_Date + interval '1' day;
    IF (to_char(v_Date, 'dy') = 'wed') THEN
        v_NumWed := v_NumWed + 1;
    END IF;
END LOOP;
</code>```

However I have a feeling there is a simpler way to achieve this maybe via a query or something not using a loop EG: use an input date and query to find the first wednesday then + 14 days?

Any suggestions would be great, thanks in advance :)

EDIT: I have something like this which appears to work, also considers if the first day is a wednesday itself.

```<code>select next_day(trunc(v_date, 'MM') - 1, 'WED'), next_day(trunc(v_date, 'MM') - 1, 'WED') + 14 into v_first, v_third from dual;
</code>```

SOLVED: thanks for the help folks, got a few possible solutions now in the comments!

答:
How about this? Find the first Wednesday (using NEXT_DAY) that follows some date, and add 14 days (i.e. 2 weeks) to find the 3rd Wednesday.

```<code>SQL> alter session set nls_date_format = 'dd.mm.yyyy';

Session altered.

SQL> alter session set nls_date_language = 'english';

Session altered.

SQL> WITH test (col)
  2       AS (SELECT DATE '2020-01-27' FROM DUAL
  3           UNION ALL
  4           SELECT DATE '2020-02-06' FROM DUAL
  5           UNION ALL
  6           SELECT DATE '2020-02-12' FROM DUAL)
  7  SELECT col, NEXT_DAY (col, 'wed') + 14 next_3
  8    FROM test;

COL        NEXT_3
---------- ----------
27.01.2020 12.02.2020
06.02.2020 26.02.2020
12.02.2020 04.03.2020

SQL>
</code>```

[EDIT]

If comment you posted means that - for any date - you want to find 3rd Wednesday in that month, then truncate date to month (which returns 1st day in that month) and find the 3rd Wednesday, taking care about whether the 1st day of the month is (or is not) Wednesday.

```<code>SQL> WITH test (col)
  2       AS (SELECT DATE '2020-01-27' FROM DUAL
  3           UNION ALL
  4           SELECT DATE '2020-02-06' FROM DUAL
  5           UNION ALL
  6           SELECT DATE '2020-03-18' FROM DUAL)
  7  SELECT col,
  8           NEXT_DAY (TRUNC (col, 'mm'), 'wed')
  9         + CASE
 10              WHEN TO_CHAR (TRUNC (col, 'mm'), 'dy') = 'wed' THEN 7
 11              ELSE 14
 12           END
 13            next_3
 14    FROM test;

COL        NEXT_3
---------- ----------
27.01.2020 15.01.2020
06.02.2020 19.02.2020
18.03.2020 18.03.2020

SQL>
</code>```

Body:
Currently I have a process which takes a date variable EG: '01-MAR-2026', it then iterates over this date checking if the day is wednesday. If so then increment a counter else add 1 day and check again.
This exits when the wednesday count is = 3.

IF (to_char(v_Date,'dy') = 'wed') THEN
        v_NumWed := v_NumWed + 1;
END IF;

WHILE (v_NumWed != 3) LOOP
    v_Date := v_Date + interval '1' day;
    IF (to_char(v_Date, 'dy') = 'wed') THEN
        v_NumWed := v_NumWed + 1;
    END IF;
END LOOP;

However I have a feeling there is a simpler way to achieve this maybe via a query or something not using a loop EG: use an input date and query to find the first wednesday then + 14 days?

Any suggestions would be great, thanks in advance :)

EDIT: I have something like this which appears to work, also considers if the first day is a wednesday itself.

select next_day(trunc(v_date, 'MM') - 1, 'WED'), next_day(trunc(v_date, 'MM') - 1, 'WED') + 14 into v_first, v_third from dual;

SOLVED: thanks for the help folks, got a few possible solutions now in the comments!

Body:
How about this? Find the first Wednesday (using NEXT_DAY) that follows some date, and add 14 days (i.e. 2 weeks) to find the 3rd Wednesday.

SQL> alter session set nls_date_format = 'dd.mm.yyyy';

Session altered.

SQL> alter session set nls_date_language = 'english';

Session altered.

SQL> WITH test (col)
  2       AS (SELECT DATE '2020-01-27' FROM DUAL
  3           UNION ALL
  4           SELECT DATE '2020-02-06' FROM DUAL
  5           UNION ALL
  6           SELECT DATE '2020-02-12' FROM DUAL)
  7  SELECT col, NEXT_DAY (col, 'wed') + 14 next_3
  8    FROM test;

COL        NEXT_3
---------- ----------
27.01.2020 12.02.2020
06.02.2020 26.02.2020
12.02.2020 04.03.2020

SQL>

[EDIT]

If comment you posted means that - for any date - you want to find 3rd Wednesday in that month, then truncate date to month (which returns 1st day in that month) and find the 3rd Wednesday, taking care about whether the 1st day of the month is (or is not) Wednesday.

SQL> WITH test (col)
  2       AS (SELECT DATE '2020-01-27' FROM DUAL
  3           UNION ALL
  4           SELECT DATE '2020-02-06' FROM DUAL
  5           UNION ALL
  6           SELECT DATE '2020-03-18' FROM DUAL)
  7  SELECT col,
  8           NEXT_DAY (TRUNC (col, 'mm'), 'wed')
  9         + CASE
 10              WHEN TO_CHAR (TRUNC (col, 'mm'), 'dy') = 'wed' THEN 7
 11              ELSE 14
 12           END
 13            next_3
 14    FROM test;

COL        NEXT_3
---------- ----------
27.01.2020 15.01.2020
06.02.2020 19.02.2020
18.03.2020 18.03.2020

SQL>


问:
VS 2005 doesn't detect changes in header files of C++ project
Very often, actually most of the times, Visual Studio2005 doesn't detect
that some header included in some CPP file C++ project was changed.
As the consequence, it doesn't recompile the project if only header is changed.

It doesn't depend on the "precompiled headers" settings.
It doesn't happen in VS 2006 but in every version of VS 2005 and VS 2008 it does.
It happens for all the projects, not for some specific one.

It doesn't happen if header file is a  part of the project,
i.e. if it appears in the vcproj file

The only way to resolve the issue is to perform a clean build.

Any advise is strongly appreciated.

答:
For those of us still having this issue with vs 2015, 2017 and 2019 (probably some more versions) and have tried turning off precompiled headers, creating a brand new solution/project (not copying anything over), disabling minimal rebuild and so on. And just want a solution that works and doesn't mean running clean or rebuild manually before every test run.

You can fix by brute force:

Go to project properties

"custom build step"

"execute before" and set to "Clean"

I wonder how many things I and others have unlearned by not knowing VS was actually just running the broken old version of the code without the changes that actually did fix the code?

ContentLicense: CC BY-SA 2.5