问:
I want to go to another page when I click on the image in Flutter
I'm a newbie in Flutter and I'm trying to design a page to let the user choose the user type.
And I'm trying to use onTap method so that when I click on the picture I go to the selected user type page but when I used the onTap method the user type image disappears.
I don't know if I'm using the right method or if I'm using it in a wrong way.
But here is what my code looks like you maybe able to help me :)
thank you</p>
```<code>import 'package:flutter/material.dart';

class ChooseUser extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new Scaffold(
        body: new Container(
          padding: const EdgeInsets.fromLTRB(0, 250, 0, 0),
          child: new Column(
            children: [
              new Container(
                alignment: Alignment(0.4, 0.2),
                child: new Text(
                  "فضلًا أختر نوع المستخدم",
                  style: TextStyle(
                      fontSize: 30,
                      fontFamily: 'Cairo',
                      color: Color(0xFF403E3E),
                      shadows: [
                        Shadow(
                            color: Color(0xFF403E3E),
                            offset: Offset(1, 1),
                            blurRadius: 1)
                      ]),
                ),
              ),
              new Container(
                  height: 300.0,
                  width: 300.0,
                  padding: const EdgeInsets.fromLTRB(15, 120, 0, 0),
                  child: new Row(children: [
                    new Column(
                      children: [
                        new Container(
                          margin: const EdgeInsets.only(right: 40.0),
                          height: 100.0,
                          width: 100.0,
                          decoration: new BoxDecoration(
                            image: DecorationImage(
                                image: new AssetImage(
                                    'assets/images/elderly-icon.png'),
                                fit: BoxFit.fill),
                          ),
                        ),
                        new Container(
                            margin: const EdgeInsets.only(right: 40.0, top: 10),
                            child: new Text(
                              "كبير سن",
                              style: TextStyle(
                                  fontSize: 20,
                                  fontFamily: 'Cairo',
                                  color: Color(0xFF403E3E),
                                  shadows: [
                                    Shadow(
                                        color: Color(0xFF403E3E),
                                        offset: Offset(1, 1),
                                        blurRadius: 1)
                                  ]),
                            )),
                      ],
                    ),
                    new Column(children: [
                      GestureDetector(
                        onTap: () {
                          Navigator.of(context).pushNamed('medical-choose');
                          new Container(
                            margin: const EdgeInsets.only(left: 20.0),
                            height: 100.0,
                            width: 100.0,
                            decoration: new BoxDecoration(
                              image: DecorationImage(
                                  image: new AssetImage(
                                      'assets/images/staff-icon.png'),
                                  fit: BoxFit.fill),
                            ),
                          );
                          new Container(
                            margin: const EdgeInsets.only(left: 10.0, top: 10),
                            child: new Text(
                              "طاقم طبي",
                              style: TextStyle(
                                  fontSize: 20,
                                  fontFamily: 'Cairo',
                                  color: Color(0xFF403E3E),
                                  shadows: [
                                    Shadow(
                                        color: Color(0xFF403E3E),
                                        offset: Offset(1, 1),
                                        blurRadius: 1)
                                  ]),
                            ),
                          );
                        },
                      ),
                    ]),
                  ])),
            ],
          ),
        ),
      ),
    );
  }
}
</code>```

答:
On the onTap() method, usually nothing is rendered in the function.

The GestureDetector should have the image as a child and the onTap() would just have the Navigator.pushNamed

Something like this:

```<code>    GestureDetector(
      child: Container(
          decoration: BoxDecoration(
              image: DecorationImage(
                  image: AssetImage(
                          'assets/images/staff-icon.png'
                      ),
                      fit: BoxFit.fill
                  )
              )
          )
      ),
      onTap: (){
        Navigator.of(context).pushNamed('medical-choose');
      },
    );
</code>```

Body:
I'm a newbie in Flutter and I'm trying to design a page to let the user choose the user type.
And I'm trying to use onTap method so that when I click on the picture I go to the selected user type page but when I used the onTap method the user type image disappears.
I don't know if I'm using the right method or if I'm using it in a wrong way.
But here is what my code looks like you maybe able to help me :)
thank you

import 'package:flutter/material.dart';

class ChooseUser extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new Scaffold(
        body: new Container(
          padding: const EdgeInsets.fromLTRB(0, 250, 0, 0),
          child: new Column(
            children: [
              new Container(
                alignment: Alignment(0.4, 0.2),
                child: new Text(
                  "فضلًا أختر نوع المستخدم",
                  style: TextStyle(
                      fontSize: 30,
                      fontFamily: 'Cairo',
                      color: Color(0xFF403E3E),
                      shadows: [
                        Shadow(
                            color: Color(0xFF403E3E),
                            offset: Offset(1, 1),
                            blurRadius: 1)
                      ]),
                ),
              ),
              new Container(
                  height: 300.0,
                  width: 300.0,
                  padding: const EdgeInsets.fromLTRB(15, 120, 0, 0),
                  child: new Row(children: [
                    new Column(
                      children: [
                        new Container(
                          margin: const EdgeInsets.only(right: 40.0),
                          height: 100.0,
                          width: 100.0,
                          decoration: new BoxDecoration(
                            image: DecorationImage(
                                image: new AssetImage(
                                    'assets/images/elderly-icon.png'),
                                fit: BoxFit.fill),
                          ),
                        ),
                        new Container(
                            margin: const EdgeInsets.only(right: 40.0, top: 10),
                            child: new Text(
                              "كبير سن",
                              style: TextStyle(
                                  fontSize: 20,
                                  fontFamily: 'Cairo',
                                  color: Color(0xFF403E3E),
                                  shadows: [
                                    Shadow(
                                        color: Color(0xFF403E3E),
                                        offset: Offset(1, 1),
                                        blurRadius: 1)
                                  ]),
                            )),
                      ],
                    ),
                    new Column(children: [
                      GestureDetector(
                        onTap: () {
                          Navigator.of(context).pushNamed('medical-choose');
                          new Container(
                            margin: const EdgeInsets.only(left: 20.0),
                            height: 100.0,
                            width: 100.0,
                            decoration: new BoxDecoration(
                              image: DecorationImage(
                                  image: new AssetImage(
                                      'assets/images/staff-icon.png'),
                                  fit: BoxFit.fill),
                            ),
                          );
                          new Container(
                            margin: const EdgeInsets.only(left: 10.0, top: 10),
                            child: new Text(
                              "طاقم طبي",
                              style: TextStyle(
                                  fontSize: 20,
                                  fontFamily: 'Cairo',
                                  color: Color(0xFF403E3E),
                                  shadows: [
                                    Shadow(
                                        color: Color(0xFF403E3E),
                                        offset: Offset(1, 1),
                                        blurRadius: 1)
                                  ]),
                            ),
                          );
                        },
                      ),
                    ]),
                  ])),
            ],
          ),
        ),
      ),
    );
  }
}

Body:
On the onTap() method, usually nothing is rendered in the function.

The GestureDetector should have the image as a child and the onTap() would just have the Navigator.pushNamed

Something like this:

    GestureDetector(
      child: Container(
          decoration: BoxDecoration(
              image: DecorationImage(
                  image: AssetImage(
                          'assets/images/staff-icon.png'
                      ),
                      fit: BoxFit.fill
                  )
              )
          )
      ),
      onTap: (){
        Navigator.of(context).pushNamed('medical-choose');
      },
    );


来源: stackexchange

问:
Getting an error on json POST request with Cakephp
I'm relatively new to Cakephp and unfortunately have to work with it for this project.  The problem that I am having is my POST request is returning an error even though I am echoing a json string properly.

Here is my html and embedded javascript

```<code> <div class="submit">
   <input type="submit" onclick="results();" id="submit"></submit>
</div>
<script type="text/javascript">
function results() {
    var data = $('#ListingResultsForm').serialize();

    $.ajax({
        type: 'post',
        url: '/listings/results',
        data: data,
        dataType: 'json',
        success: function(data, textStatus, jqXHR) {
            console.log(textStatus);
            console.log(jqXHR);
            console.log(data);
        },
        error: function(textStatus, errorThrown, jqXHR) {
            console.log(textStatus);
            console.log(jqXHR);
            console.log(errorThrown);
        }
    });
    return false;
}
</code>```

And here is my controller

```<code>function results() {
    $this->layout = 'ajax';
    $this->autoLayout = false;
    $this->autoRender = false;
    $conditions = array();
    if (!empty($this->data)) {
        ($this->data['Listing']['listing_countyid'] !== '') ?   $conditions['listing_countyid'] = $this->data['Listing']['listing_countyid'] : '';
        ($this->data['Listing']['listing_area'] !== '') ? $conditions['listing_area'] = $this->data['Listing']['listing_area'] : '';
        ($this->data['Listing']['listing_neighborhood'] !== '') ? $conditions['listing_neighborhood'] = $this->data['Listing']['listing_neighborhood'] : '';
        ($this->data['Listing']['min_price'] !== '') ? $conditions['listing_listprice >='] = $this->data['Listing']['min_price'] : '';
        ($this->data['Listing']['max_price'] !== '') ? $conditions['listing_listprice <='] = $this->data['Listing']['max_price'] : '';
        ($this->data['Listing']['min_listing_sqfttotal'] !== '') ? $conditions['listing_sqfttotal >='] = $this->data['Listing']['min_listing_sqfttotal'] : '';
        ($this->data['Listing']['max_listing_sqfttotal'] !== '') ? $conditions['listing_sqfttotal <='] = $this->data['Listing']['max_listing_sqfttotal'] : '';
        ($this->data['Listing']['min_stories'] !== '') ? $conditions['listing_stories >='] = $this->data['Listing']['min_stories'] : '';
        ($this->data['Listing']['listing_yearbuilt'] !== '') ? $conditions['listing_yearbuilt >='] = $this->data['Listing']['listing_yearbuilt'] : '';
        ($this->data['Listing']['min_bathrooms'] !== '') ?  $conditions['listing_bathstotal >='] = $this->data['Listing']['min_bathrooms'] : '';
        ($this->data['Listing']['max_bathrooms'] !== '') ?  $conditions['listing_bathstotal <='] = $this->data['Listing']['max_bathrooms'] : '';
        ($this->data['Listing']['min_bedrooms'] !== '') ? $conditions['listing_bedrooms >='] = $this->data['Listing']['min_bedrooms'] : '';
        ($this->data['Listing']['max_bedrooms'] !== '') ? $conditions['listing_bedrooms <='] = $this->data['Listing']['max_bedrooms'] : '';
        ($this->data['Listing']['level1_mstr'] !== '') ? $conditions['listing_roommasterbrlevel'] = $this->data['Listing']['level1_mstr'] : '';
        ($this->data['Listing']['level1_laundry'] !== '') ? $conditions['listing_roomlaundrylevel'] = $this->data['Listing']['level1_laundry'] : '';
        ($this->data['Listing']['heat_type'] !== '') ? $conditions['listing_heatsystem'] = $this->data['Listing']['heat_type'] : '';
        ($this->data['Listing']['cool_type'] !== '') ? $conditions['listing_coolsystem'] = $this->data['Listing']['cool_type'] : '';
        ($this->data['Listing']['irrigation_system'] !== '') ? $conditions['listing_irrigationsrc'] = $this->data['Listing']['irrigation_system'] : '';
        ($this->data['Listing']['fireplace'] !== '') ? $conditions['listing_fireplaces'] = $this->data['Listing']['fireplace'] : '';
        ($this->data['Listing']['handicap'] !== '') ? $conditions['listing_handicap'] = $this->data['Listing']['handicap'] : '';
        ($this->data['Listing']['fence'] !== '') ? $conditions['listing_fence'] = $this->data['Listing']['fence'] : '';
        $items = $this->Idx->find('all', array('conditions'=> $conditions));
        $this->header('Content-Type: application/json');
        echo json_encode($items);
        return;
    }
}
</code>```

Any help is greatly appreciated.

答:
It will be good if you moved the json part to view something like

In view

```<code>//in listings/results.ctp
header('Content-Type: application/json');
echo json_encode($items);
</code>```

In controller (skipped some code)

```<code>    function results() {
        $this->layout = 'ajax';
        $this->autoLayout = false;
        $conditions = array();
        Configure::write('debug',0);
        $items = array();
        if (!empty($this->data)) {
            ($this->data['Listing']['listing_countyid'] !== '') ?   $conditions['listing_countyid'] = $this->data['Listing']['listing_countyid'] : '';
        ..........
        ...........
            $items = $this->Idx->find('all', array('conditions'=> $conditions));
        }
        $this->set(compact('items'));
    }
</code>```

Make sure you added line no. 5

ContentLicense: CC BY-SA 3.0

Body:
I'm relatively new to Cakephp and unfortunately have to work with it for this project.  The problem that I am having is my POST request is returning an error even though I am echoing a json string properly.

Here is my html and embedded javascript

   <input type="submit" onclick="results();" id="submit"></submit>

Body:
It will be good if you moved the json part to view something like

In view

//in listings/results.ctp
header('Content-Type: application/json');
echo json_encode($items);

In controller (skipped some code)

    function results() {
        $this->layout = 'ajax';
        $this->autoLayout = false;
        $conditions = array();
        Configure::write('debug',0);
        $items = array();
        if (!empty($this->data)) {
            ($this->data['Listing']['listing_countyid'] !== '') ?   $conditions['listing_countyid'] = $this->data['Listing']['listing_countyid'] : '';
        ..........
        ...........
            $items = $this->Idx->find('all', array('conditions'=> $conditions));
        }
        $this->set(compact('items'));
    }

Make sure you added line no. 5


问:
Stream File Download in Safari and Firefox
Currently, as a requirement, if a user wishes to download a large zip file, the download is a streamed.

This is done by fetching an endpoint, then using Streamsaver.js to stream the download to their browser as shown below.

```<code>function download(id, fileName) {
  const endpoint = `.../extract/downloads/zip_download/?id=${id}`;
  return fetch(endpoint, requestOptions.get()).then(res => {
    const downloadSize = res.headers.get("content-length");
    const fileStream = createWriteStream(fileName, { size: downloadSize });
    const writer = fileStream.getWriter();
    if (res.body.pipeTo) {
      writer.releaseLock();
      return res.body.pipeTo(fileStream);
    }

    const reader = res.body.getReader();
    const pump = () =>
      reader
        .read()
        .then(({ value, done }) =>
          done ? writer.close() : writer.write(value).then(pump)
        );

    return pump();
  });
}
</code>```

This works fine in Chrome, however I'm running into issues with Firefox and Safari. The issue I get is:

```<code>TypeError: undefined is not a constructor (evaluating 'new streamSaver.WritableStream')
</code>```

What other methods are there of approaching this? Surely there must be a universal way to stream a download of a large that I'm missing?

ContentLicense: CC BY-SA 4.0

Body:
Currently, as a requirement, if a user wishes to download a large zip file, the download is a streamed.

This is done by fetching an endpoint, then using Streamsaver.js to stream the download to their browser as shown below.

function download(id, fileName) {
  const endpoint = `.../extract/downloads/zip_download/?id=${id}`;
  return fetch(endpoint, requestOptions.get()).then(res => {
    const downloadSize = res.headers.get("content-length");
    const fileStream = createWriteStream(fileName, { size: downloadSize });
    const writer = fileStream.getWriter();
    if (res.body.pipeTo) {
      writer.releaseLock();
      return res.body.pipeTo(fileStream);
    }

    const reader = res.body.getReader();
    const pump = () =>
      reader
        .read()
        .then(({ value, done }) =>
          done ? writer.close() : writer.write(value).then(pump)
        );

    return pump();
  });
}

This works fine in Chrome, however I'm running into issues with Firefox and Safari. The issue I get is:

TypeError: undefined is not a constructor (evaluating 'new streamSaver.WritableStream')

What other methods are there of approaching this? Surely there must be a universal way to stream a download of a large that I'm missing?

Body:
I ran into the same issue and included the web-streams-polyfill package in my project to fix it. Currently, some non-chromium browsers appear to not support WritableStream.

For myself, I simply included this script tag in my index.html

<script src="https://unpkg.com/web-streams-polyfill/dist/polyfill.min.js"></script>


问:
How to install homebrew on M1 mac
I just got a new Mac, the M1 Macbook pro and I am trying to install homebrew, but every time I finish installing it, it tells me that it was not written to the path, and then when I try the advised whatever to add to the path, nothing happens and the terminal or whatever does not recognize the command at all, as if it isn't installed.

This worked perfectly fine on my old Intel mac, and there is some step or whatever - I don't know anything, and I am tired and I don't understand how to install this at all, but hte path is supposed to be different for Apple silicon macs but nothing i read helps at all.

答:
If you are getting the intel chip error

```<code>xcrun: error: unable to load libxcrun (dlopen(/Library/Developer/CommandLineTools/usr/lib/libxcrun.dylib, 0x0005): tried: '/Library/Developer/CommandLineTools/usr/lib/libxcrun.dylib' (mach-o file, but is an incompatible architecture (have 'x86_64', need 'arm64e')), '/usr/lib/libxcrun.dylib' (no such file)).
</code>```

then you have to fix your command line tools (CLT). What I did is the following (solution from here):

What I suggest is to uninstall the command line tools (CLT) and re-install them the official way (source).

So do (source):

```<code>sudo rm -rf /Library/Developer/CommandLineTools
</code>```

check it uninstalled, you should get an output as follows:

```<code>xcode-select -p
</code>```

output

```<code>xcode-select: error: unable to get active developer directory, use `sudo xcode-select --switch path/to/Xcode.app` to set one (or see `man xcode-select`)
</code>```

then install the command line tools (CLT) again:

```<code>xcode-select --install
</code>```

then agree to it and it should download after a couple of minutes. The download should take some time. For me ~13mins.

After that your issues with PyCharm, git, brew and likely other tools will be resolved.

After you have that resolved -- which was causing me issue when trying to install brew -- do what the top answer here recommends: https://stackoverflow.com/a/67271753/1601580 which in a summary is run the bash install of brew and make sure it is in your PATH env variable properly.

Title: How to install homebrew on M1 mac

Body:
If you are getting the intel chip error

xcrun: error: unable to load libxcrun (dlopen(/Library/Developer/CommandLineTools/usr/lib/libxcrun.dylib, 0x0005): tried: '/Library/Developer/CommandLineTools/usr/lib/libxcrun.dylib' (mach-o file, but is an incompatible architecture (have 'x86_64', need 'arm64e')), '/usr/lib/libxcrun.dylib' (no such file)).

then you have to fix your command line tools (CLT). What I did is the following (solution from here):

What I suggest is to uninstall the command line tools (CLT) and re-install them the official way (source).

So do (source):

sudo rm -rf /Library/Developer/CommandLineTools

check it uninstalled, you should get an output as follows:

xcode-select -p

output

xcode-select: error: unable to get active developer directory, use `sudo xcode-select --switch path/to/Xcode.app` to set one (or see `man xcode-select`)

then install the command line tools (CLT) again:

xcode-select --install

then agree to it and it should download after a couple of minutes. The download should take some time. For me ~13mins.

After that your issues with PyCharm, git, brew and likely other tools will be resolved.

After you have that resolved -- which was causing me issue when trying to install brew -- do what the top answer here recommends: https://stackoverflow.com/a/67271753/1601580 which in a summary is run the bash install of brew and make sure it is in your PATH env variable properly.


问:
How to keep viewModel state when fragment is destroyed?
I have an issue with keeping the state of data in a viewModel. The viewModel that I have is initialised inside of the onViewCreated method like this:

```<code>val viewModel: PlayerViewModelImpl by viewModels {
            ViewModelFactory(
              PlayerRepositoryImpl(MockContentProviderImpl()),
              ClipsAudioPlayerImpl.getInstance(requireActivity()),
              storage
            )
          }
</code>```

and whenever i go back, and then open the fragment again I lose all the data that was processed inside of the viewModel. Does anyone have an idea on how can I retain the data and state of the viewModel for this scenario?
Also here is my ViewModelFactory class:

```<code>/**
 * Factory for view models.
 */
class ViewModelFactory(
  private val repository: PlayerRepository,
  private val player: ClipsAudioPlayer<ClipsModel>,
  private val storage: PreferencesStorage): ViewModelProvider.NewInstanceFactory() {

  override fun <T : ViewModel> create(modelClass: Class<T>, extras: CreationExtras): T = PlayerViewModelImpl(repository,storage,player) as T
}
</code>```

Any help will be very much appreciated! Thanks

答:
You can use SharedViewModel concept to resolve this problem. You can keep the ViewModel alive if it attached to activity.

From its name, SharedViewModel can share data between fragments, or activities.

What you are going to do is to:

Use activityViewModel delegate

Follow the official documentation you will find a proper example that solve your problem.

Body:
I have an issue with keeping the state of data in a viewModel. The viewModel that I have is initialised inside of the onViewCreated method like this:

val viewModel: PlayerViewModelImpl by viewModels {
            ViewModelFactory(
              PlayerRepositoryImpl(MockContentProviderImpl()),
              ClipsAudioPlayerImpl.getInstance(requireActivity()),
              storage
            )
          }

and whenever i go back, and then open the fragment again I lose all the data that was processed inside of the viewModel. Does anyone have an idea on how can I retain the data and state of the viewModel for this scenario?
Also here is my ViewModelFactory class:

/**
 * Factory for view models.
 */
class ViewModelFactory(
  private val repository: PlayerRepository,
  private val player: ClipsAudioPlayer<ClipsModel>,
  private val storage: PreferencesStorage): ViewModelProvider.NewInstanceFactory() {

  override fun <T : ViewModel> create(modelClass: Class<T>, extras: CreationExtras): T = PlayerViewModelImpl(repository,storage,player) as T
}

Any help will be very much appreciated! Thanks


问:
DOCUMENT_TEXT_DETECTION language hints
I am using Google Cloud Vision's API DOCUMENT_TEXT_DETECTION to extract text of multiple languages. I am trying to use the ImageContext feature to provide language hints as given here. Can anyone tell me how to make use of it?
Thank you!</p>

答: You can provide a language hint string by specifying one of the languageHints codes from this page: https://cloud.google.com/vision/docs/languages</p>

Title: DOCUMENT_TEXT_DETECTION language hints


问:
Replace a set of html br elements with another in jQuery -- parsing HTML with jQuery
So here's my problem. I have a little third-party service on my site that generates a bunch of HTML from an RSS feed and sticks it in my webpage when the page is loaded. However, when it generates the HTML, it inserts a bunch of totally unnecessary break tags. Unfortunately, the source file that generates this code is on the third party's server and not mine, so I can't tweak it.

Thus, I'm trying to tweak the HTML right before the page is loaded by using a little jQuery inside the onLoad="" property in the body tag. However, I can't simply use something like $('br').remove(); because then there aren't ANY break tags, and I need one per each spot where there are currently three.

So ultimately, what I need to do is come up with a jQuery statement that replaces

```<code><br><br clear=all><br>
</code>```

with

```<code><br />
</code>```

I'm rather new to jQuery, but I couldn't seem to find anything that would help me do this. Any ideas?

Thanks in advance for any help!

答:
Assuming they are in the exact format you gave, you can do this:</p>

```<code>var br = $('br[clear="all"]');
br.attr('clear', '');
br.prev('br').remove();
br.next('br').remove();
</code>```

Body:
So here's my problem. I have a little third-party service on my site that generates a bunch of HTML from an RSS feed and sticks it in my webpage when the page is loaded. However, when it generates the HTML, it inserts a bunch of totally unnecessary break tags. Unfortunately, the source file that generates this code is on the third party's server and not mine, so I can't tweak it.

Thus, I'm trying to tweak the HTML right before the page is loaded by using a little jQuery inside the onLoad="" property in the body tag. However, I can't simply use something like $('br').remove(); because then there aren't ANY break tags, and I need one per each spot where there are currently three.

So ultimately, what I need to do is come up with a jQuery statement that replaces

with

I'm rather new to jQuery, but I couldn't seem to find anything that would help me do this. Any ideas?

Thanks in advance for any help!

Body:
Assuming they are in the exact format you gave, you can do this:

var br = $('br[clear="all"]');
br.attr('clear', '');
br.prev('br').remove();
br.next('br').remove();


问:
Filtering an array of JSON objects with strange characters
I have an array of objects given in the format below as an input, with odd double backslashes that stop me from parsing each input into JSON. I only want to save some document types, so I'm filtering out these records using Array.prototype.filter().  The problem I'm facing is parsing each record with those backslashes.  One is escaping the other and it's keeping one backslash. Any help would be appreciated.

```<code>const records = [
  {
    messageId: '1',
    body: '{"Message" : "{\\"detail\\": {\\"documentType\\": \\"pm1"\\", \\"documentDate\\": \\"2018-08-27 04:00:00\\"}}"}',
  },
  {
    messageId: '2',
    body: '{"Message" : "{\\"detail\\": {\\"documentType\\": \\"pm3\\", \\"documentDate\\": \\"2018-08-27 04:00:00\\"}}"}',
  },
  {
    messageId: '3',
    body: '{"Message" : "{\\"detail\\": {\\"documentType\\": \\"pm8\\", \\"documentDate\\": \\"2018-08-27 04:00:00\\"}}"}',
  },
];

let output = [];
let message = [];
try {
    output = event.Records.filter((resource) => {
    console.log('resource:', resource);
    const body = resource.body ? JSON.stringify(resource.body) : '';
    message = body.Message ? JSON.stringify(resource.body.Message) : '';
    console.log('message:', message);
    const documentType = message.detail?.documentType?.toLowerCase() || '';
    console.log('decoumentType:', documentType);
    const acceptedDocTypes = ['pm1', 'pm2', 'pm3', 'pm4', 'pm5'];
    return acceptedDocTypes.includes(documentType);
});
</code>```

UPDATED SNIPPET:

```<code>  try {
output = event.Records.filter((resource) => {
  let body = '';
  if (resource.body) {
    resource.body.replace(/(\\+")/gmi, '"');
    resource.body.replace(/\s*"\s*\{/gmi, '{').replace(/\s*\}\s*"/gmi, '}');
    body = JSON.parse(resource.body);
  }
  message = body.Message ? JSON.parse(JSON.stringify(body.Message)) : '';
  console.log(message);
  const { documentType } = body.message.detail;
  console.log('decoumentType:', documentType);
  const acceptedDocTypes = ['pm1', 'pm2', 'pm3', 'pm4', 'pm5'];
  return acceptedDocTypes.includes(documentType);
});
</code>```

答:
If your backslashes are consistent, you can try removing them using a regex:

const records = [
  {
    messageId: '2',
    body: '{"Message" : "{\\"detail\\": {\\"documentType\\": \\"pm3\\", \\"documentDate\\": \\"2018-08-27 04:00:00\\"}}"}',
  },
  {
    messageId: '3',
    body: '{"Message" : "{\\"detail\\": {\\"documentType\\": \\"pm8\\", \\"documentDate\\": \\"2018-08-27 04:00:00\\"}}"}',
  },
]

records.forEach(record => record.body = record.body.replace(/(\\+")/gmi, '"'))

records.forEach(record => record.body = record.body.replace(/\s*"\s*\{/gmi, '{').replace(/\s*\}\s*"/gmi, '}'))

records.forEach(record => record.body = JSON.parse(record.body))

console.log(records)```

In this way, you first clean the input, then you can apply JSON.parse. This doesn't work with your first example since there's an extra unescaped quote, but I suppose it was a typo in your writing.

Body:
I have an array of objects given in the format below as an input, with odd double backslashes that stop me from parsing each input into JSON. I only want to save some document types, so I'm filtering out these records using Array.prototype.filter().  The problem I'm facing is parsing each record with those backslashes.  One is escaping the other and it's keeping one backslash. Any help would be appreciated.

const records = [
  {
    messageId: '1',
    body: '{"Message" : "{\\"detail\\": {\\"documentType\\": \\"pm1"\\", \\"documentDate\\": \\"2018-08-27 04:00:00\\"}}"}',
  },
  {
    messageId: '2',
    body: '{"Message" : "{\\"detail\\": {\\"documentType\\": \\"pm3\\", \\"documentDate\\": \\"2018-08-27 04:00:00\\"}}"}',
  },
  {
    messageId: '3',
    body: '{"Message" : "{\\"detail\\": {\\"documentType\\": \\"pm8\\", \\"documentDate\\": \\"2018-08-27 04:00:00\\"}}"}',
  },
];

let output = [];
let message = [];
try {
    output = event.Records.filter((resource) => {
    console.log('resource:', resource);
    const body = resource.body ? JSON.stringify(resource.body) : '';
    message = body.Message ? JSON.stringify(resource.body.Message) : '';
    console.log('message:', message);
    const documentType = message.detail?.documentType?.toLowerCase() || '';
    console.log('decoumentType:', documentType);
    const acceptedDocTypes = ['pm1', 'pm2', 'pm3', 'pm4', 'pm5'];
    return acceptedDocTypes.includes(documentType);
});

UPDATED SNIPPET:

  try {
output = event.Records.filter((resource) => {
  let body = '';
  if (resource.body) {
    resource.body.replace(/(\\+")/gmi, '"');
    resource.body.replace(/\s*"\s*\{/gmi, '{').replace(/\s*\}\s*"/gmi, '}');
    body = JSON.parse(resource.body);
  }
  message = body.Message ? JSON.parse(JSON.stringify(body.Message)) : '';
  console.log(message);
  const { documentType } = body.message.detail;
  console.log('decoumentType:', documentType);
  const acceptedDocTypes = ['pm1', 'pm2', 'pm3', 'pm4', 'pm5'];
  return acceptedDocTypes.includes(documentType);
});

Body:
If your backslashes are consistent, you can try removing them using a regex:

const records = [
  {
    messageId: '2',
    body: '{"Message" : "{\\"detail\\": {\\"documentType\\": \\"pm3\\", \\"documentDate\\": \\"2018-08-27 04:00:00\\"}}"}',
  },
  {
    messageId: '3',
    body: '{"Message" : "{\\"detail\\": {\\"documentType\\": \\"pm8\\", \\"documentDate\\": \\"2018-08-27 04:00:00\\"}}"}',
  },
]

records.forEach(record => record.body = record.body.replace(/(\\+")/gmi, '"'))

records.forEach(record => record.body = record.body.replace(/\s*"\s*\{/gmi, '{').replace(/\s*\}\s*"/gmi, '}'))

records.forEach(record => record.body = JSON.parse(record.body))

console.log(records)

In this way, you first clean the input, then you can apply JSON.parse. This doesn't work with your first example since there's an extra unescaped quote, but I suppose it was a typo in your writing.


问:
Dart Main File (and other essential files) Not Created In New Project
I am learning dart/flutter using InetlliJ, and when I go to create a new dart project, it only creates a few useless files. No main.dart. I have all the most recent versions of flutter and dart installed.
enter image description here</p>

答:
How did you generate your new project?

You can install the Flutter plugin on your editor, and you can create a Flutter Project using this guide


问:
SQL Return All Possible Combinations on Multiple Columns With Multiple WHERE Clauses
I am using a local MAMP connection and creating databases in phpMyadmin. I have a Fantasy Football Database that I want to return all combinations of a submitted lineup where the salary of the NFL players in the contest are less than or equal to a combined 50,000 AND the Fantasy Points Scored is greater than or equal to 200. So a valid lineup consists of a QB, RB1, RB2, WR1, WR2, WR3, TE, FLEX, and DST. A valid lineup can be only submitted if the combined cost of the 9 players in the lineup is less than or equal to 50,000 (for example, the QB costs 10,000, RB1 costs 5,000, RB2 costs 6,000 etc for all 9 slots which must be less than or equal to 50,000). Also, each lineup slot must have a unique player even though there are multiple Running Back and Wide Receiver slots. The FLEX slot can be either a RB, WR, or TE but again, it can't be any of the players in any of the other slots. I am trying to get the results of a contest and return a data set of all possible valid lineups that scored over 200. My database is NOT normalized. I do know how to normalize it and I can if it will make the results better/faster. But for now, I'm just trying to test the query. Here is a link to a sample data set https://docs.google.com/spreadsheets/d/1ECXtOj3MALgQNVMrr1wOlNso2iipqg2jzP6Ty9DZ0JA/edit?usp=sharing I have tried various SQL SELECT statements but they all freeze up and I can't get a result. I have tried limiting the number of results returned but to no avail. Here is basically the SELECT statement that I want to make:

```<code>SELECT DISTINCT QB, QB.Fpts, RB1, RB1.Fpts, RB2, RB2.Fpts, WR1, WR1.Fpts, WR2, WR2.Fpts, WR3, WR3.Fpts, TE, TE.Fpts, FLEX, FLEX.Fpts, DST, DST.Fpts
FROM QB, RB1, RB2, WR1, WR2, WR3, TE, FLEX, DST
WHERE
(QB.Salary + RB1.Salary + RB2.Salary + WR1.Salary + WR2.Salary + WR3.Salary + TE.Salary + FLEX.Salary + + DST.Salary <= 50000)
AND
(QB.Fpts + RB1.Fpts + RB2.Fpts + WR1.Fpts + WR2.Fpts + WR3.Fpts + TE.Fpts + FLEX.Fpts + DST.Fpts >= 200)
LIMIT 1000;
</code>```

How can I make it where I can return values from this query and is there a way to save the results to a text file?

答:
You need additional conditions requiring that the players not be equal:</p>
```<code>SELECT DISTINCT QB, QB.Fpts, RB1, RB1.Fpts, RB2, RB2.Fpts, WR1, WR1.Fpts, WR2, WR2.Fpts, WR3, WR3.Fpts, TE, TE.Fpts, FLEX, FLEX.Fpts, DST, DST.Fpts
FROM QB, RB1, RB2, WR1, WR2, WR3, TE, FLEX, DST
WHERE
WR1 != WR2 AND WR1 != WR3 AND WR2 != WR 3
AND
RB1 != RB2
AND
FLEX != WR1 AND FLEX != WR2 AND FLEX != WR3 AND FLEX != RB1 AND FLEX != RB2 AND FLEX != TE
AND
(QB.Salary + RB1.Salary + RB2.Salary + WR1.Salary + WR2.Salary + WR3.Salary + TE.Salary + FLEX.Salary + + DST.Salary <= 50000)
AND
(QB.Fpts + RB1.Fpts + RB2.Fpts + WR1.Fpts + WR2.Fpts + WR3.Fpts + TE.Fpts + FLEX.Fpts + DST.Fpts >= 200)
LIMIT 1000;
</code>```

Body:
I am using a local MAMP connection and creating databases in phpMyadmin. I have a Fantasy Football Database that I want to return all combinations of a submitted lineup where the salary of the NFL players in the contest are less than or equal to a combined 50,000 AND the Fantasy Points Scored is greater than or equal to 200. So a valid lineup consists of a QB, RB1, RB2, WR1, WR2, WR3, TE, FLEX, and DST. A valid lineup can be only submitted if the combined cost of the 9 players in the lineup is less than or equal to 50,000 (for example, the QB costs 10,000, RB1 costs 5,000, RB2 costs 6,000 etc for all 9 slots which must be less than or equal to 50,000). Also, each lineup slot must have a unique player even though there are multiple Running Back and Wide Receiver slots. The FLEX slot can be either a RB, WR, or TE but again, it can't be any of the players in any of the other slots. I am trying to get the results of a contest and return a data set of all possible valid lineups that scored over 200. My database is NOT normalized. I do know how to normalize it and I can if it will make the results better/faster. But for now, I'm just trying to test the query. Here is a link to a sample data set https://docs.google.com/spreadsheets/d/1ECXtOj3MALgQNVMrr1wOlNso2iipqg2jzP6Ty9DZ0JA/edit?usp=sharing I have tried various SQL SELECT statements but they all freeze up and I can't get a result. I have tried limiting the number of results returned but to no avail. Here is basically the SELECT statement that I want to make:

SELECT DISTINCT QB, QB.Fpts, RB1, RB1.Fpts, RB2, RB2.Fpts, WR1, WR1.Fpts, WR2, WR2.Fpts, WR3, WR3.Fpts, TE, TE.Fpts, FLEX, FLEX.Fpts, DST, DST.Fpts
FROM QB, RB1, RB2, WR1, WR2, WR3, TE, FLEX, DST
WHERE
(QB.Salary + RB1.Salary + RB2.Salary + WR1.Salary + WR2.Salary + WR3.Salary + TE.Salary + FLEX.Salary + + DST.Salary <= 50000)
AND
(QB.Fpts + RB1.Fpts + RB2.Fpts + WR1.Fpts + WR2.Fpts + WR3.Fpts + TE.Fpts + FLEX.Fpts + DST.Fpts >= 200)
LIMIT 1000;

How can I make it where I can return values from this query and is there a way to save the results to a text file?

Body:
You need additional conditions requiring that the players not be equal:

SELECT DISTINCT QB, QB.Fpts, RB1, RB1.Fpts, RB2, RB2.Fpts, WR1, WR1.Fpts, WR2, WR2.Fpts, WR3, WR3.Fpts, TE, TE.Fpts, FLEX, FLEX.Fpts, DST, DST.Fpts
FROM QB, RB1, RB2, WR1, WR2, WR3, TE, FLEX, DST
WHERE
WR1 != WR2 AND WR1 != WR3 AND WR2 != WR 3
AND
RB1 != RB2
AND
FLEX != WR1 AND FLEX != WR2 AND FLEX != WR3 AND FLEX != RB1 AND FLEX != RB2 AND FLEX != TE
AND
(QB.Salary + RB1.Salary + RB2.Salary + WR1.Salary + WR2.Salary + WR3.Salary + TE.Salary + FLEX.Salary + + DST.Salary <= 50000)
AND
(QB.Fpts + RB1.Fpts + RB2.Fpts + WR1.Fpts + WR2.Fpts + WR3.Fpts + TE.Fpts + FLEX.Fpts + DST.Fpts >= 200)
LIMIT 1000;


问:
How to replace multiple value in a pandas DataFrame
How can I replace multiple values with another different multiple values (stored in an array) in a pandas DataFrame?

In detail: I want to replace the values in every rows of columns called 'Cloud3pm' of the dataframe 'df', in which the value is = -1.
I want to replace this cells values respectively with an array of values with length equal to the number of occurrences of values equal to -1 that I will go to find on the dataframe.

答:
Instead of using replace for this, you should be able to just assign a list directly to the dataframe indexed by a mask.

Let's say you have a dataframe in which a total of 5 values in any columns are -1. So there are five -1 values in the dataframe. If you want to replace them with 1, 2, 3, 4, and 5, respectively, you could do this:

```<code>df[df == -1] = [1, 2, 3, 4, 5]
</code>```

If you wanted to do that only for a particular column, you'd do this:

```<code>df.loc[df['Your Column'] == -1, 'Your Column'] = [1, 2, 3, 4, 5]
</code>```

Note that if the list of items you're trying to assign is actually a numpy array, you'll need to call .tolist() on it first, e.g.

```<code>df[df == -1] = my_array.tolist()
</code>```

Body:
Instead of using replace for this, you should be able to just assign a list directly to the dataframe indexed by a mask.

Let's say you have a dataframe in which a total of 5 values in any columns are -1. So there are five -1 values in the dataframe. If you want to replace them with 1, 2, 3, 4, and 5, respectively, you could do this:

df[df == -1] = [1, 2, 3, 4, 5]

If you wanted to do that only for a particular column, you'd do this:

df.loc[df['Your Column'] == -1, 'Your Column'] = [1, 2, 3, 4, 5]

Note that if the list of items you're trying to assign is actually a numpy array, you'll need to call .tolist() on it first, e.g.

df[df == -1] = my_array.tolist()


问:
Custom Error Handler not working in NodeJs Express
I was studying about error handeling in express and I defined one. It works fine for non async functions. But when it comes to async function the app just breaks.

```<code>app.get("/products/:id", async (req, res, next) => {
  const { id } = req.params;
  const product = await Product.findById(id);
  if (!product) {
    return next(new AppError());
  }
  res.render("products/show", { product });
});
</code>```

I have put the error handler at the bottom of the app like this:

```<code>app.use((err, req, res, next) => {
  const { status = 500, message = "something went wrong" } = err;
  res.status(status).send(message);
});
</code>```

My custom Error Class:

```<code>class AppError extends Error {
  constructor(message, status) {
    super();
    this.message = message;
    this.status = status;
  }
}

module.exports = AppError;
</code>```

答:
I believe your router doesn't know what to do when it the await fails for whatever reason. You can use this catchAsync I made below but you can also do a try catch statement around your code so it catches the error and goes onto the next task.

The try/catch could look something like this

app.get("/products/:id", async (req, res, next) => {
  try{
    const { id } = req.params;
    const product = await Product.findById(id);
    res.render("products/show", { product });

  } catch(err) {
    return next(new AppError());
  }
});
```
<p>This is my catch async function that you can use.</p>
<pre class="lang-js prettyprint-override"><code>module.exports = func => {
    return (req, res, next) => {
        func(req, res, next).catch(next);
    }
}
</code>```

Please let me know if this doesn't solve the problem

Body:
I was studying about error handeling in express and I defined one. It works fine for non async functions. But when it comes to async function the app just breaks.

app.get("/products/:id", async (req, res, next) => {
  const { id } = req.params;
  const product = await Product.findById(id);
  if (!product) {
    return next(new AppError());
  }
  res.render("products/show", { product });
});

I have put the error handler at the bottom of the app like this:

app.use((err, req, res, next) => {
  const { status = 500, message = "something went wrong" } = err;
  res.status(status).send(message);
});

My custom Error Class:

class AppError extends Error {
  constructor(message, status) {
    super();
    this.message = message;
    this.status = status;
  }
}

module.exports = AppError;

Body:
I believe your router doesn't know what to do when it the await fails for whatever reason. You can use this catchAsync I made below but you can also do a try catch statement around your code so it catches the error and goes onto the next task.

The try/catch could look something like this

app.get("/products/:id", async (req, res, next) => {
  try{
    const { id } = req.params;
    const product = await Product.findById(id);
    res.render("products/show", { product });

  } catch(err) {
    return next(new AppError());
  }
});

This is my catch async function that you can use.

module.exports = func => {
    return (req, res, next) => {
        func(req, res, next).catch(next);
    }
}

Please let me know if this doesn't solve the problem


问:
Compare list column to a second list and return item in third list
Have a dataframe with a list column like and two reference lists:

```<code>d = {'col1': [1,2,3,4,5], 'col2':[['a','b'],['a','b'],['a','b','c'],['a','b','d'], ['a','b','e']]}
df = pd.DataFrame(data=d)

ref_a = ['c','d','e','f']
ref_b = ['option1', 'option2', 'option3', 'option4']

    col1    col2
0   1   [a, b]
1   2   [a, b]
2   3   [a, b, c]
3   4   [a, b, d]
4   5   [a, b, e]
</code>```

And I want to create a third column that checks if a value in col2 is in ref_a and return the matched item in ref_b

```<code>col1    col2    check
0   1   [a, b]
1   2   [a, b]
2   3   [a, b, c]   option1
3   4   [a, b, d]   option2
4   5   [a, b, e]   option3
</code>```

I've tried something like this:

```<code>for index, row in df.iterrows():
    for (a, b) in zip(ref_a, ref_b):
        if a in row['col2']:
            df.loc[index, 'check'] = b
            print('true', b)
        else:
            df.loc[index, 'check'] = ''
</code>```

And that prints out what I'm anticipating, but doesn't change the actual value, I don't have a large amount of data to iterate over but also not sure if there is a more elegant approach. There will only be one match in the list column, never multiple options.

答:
Using zip function, you can iterate on each one of the refs in parallel. Then, you can use map to make a list of booleans where each True value indicates a sublist where ref_a was found and False otherwise. After that, you need the positions itself where True value was found, for that reason is used index method.

As you should know, index method return a ValueError when an item was not found.

```<code>def mapping():
  try:
    col2 = df['col2'].to_list() #[ [a, b], [a, b], [a, b, c], ...]
    for a, b in zip(ref_a, ref_b):
      # Here you are going to get a list of boolean where True means ref_a was found in a sub-list
      booleans = list(map(lambda subl: a in subl, col2))
      index = booleans.index(True) # The possition where ref_a was found
      df.loc[index, 'check'] = b
  except ValueError as e:
    print(e)

mapping()
print(df)
</code>```

Output:

col1
col2
check

0
1
[a, b]

1
2
[a, b]

2
3
[a, b, c]
option1

3
4
[a, b, d]
option2

4
5
[a, b, e]
option3

Body:
Have a dataframe with a list column like and two reference lists:

d = {'col1': [1,2,3,4,5], 'col2':[['a','b'],['a','b'],['a','b','c'],['a','b','d'], ['a','b','e']]}
df = pd.DataFrame(data=d)

ref_a = ['c','d','e','f']
ref_b = ['option1', 'option2', 'option3', 'option4']

    col1    col2
0   1   [a, b]
1   2   [a, b]
2   3   [a, b, c]
3   4   [a, b, d]
4   5   [a, b, e]

And I want to create a third column that checks if a value in col2 is in ref_a and return the matched item in ref_b

col1    col2    check
0   1   [a, b]
1   2   [a, b]
2   3   [a, b, c]   option1
3   4   [a, b, d]   option2
4   5   [a, b, e]   option3

I've tried something like this:

for index, row in df.iterrows():
    for (a, b) in zip(ref_a, ref_b):
        if a in row['col2']:
            df.loc[index, 'check'] = b
            print('true', b)
        else:
            df.loc[index, 'check'] = ''

And that prints out what I'm anticipating, but doesn't change the actual value, I don't have a large amount of data to iterate over but also not sure if there is a more elegant approach. There will only be one match in the list column, never multiple options.

Body:
Using zip function, you can iterate on each one of the refs in parallel. Then, you can use map to make a list of booleans where each True value indicates a sublist where ref_a was found and False otherwise. After that, you need the positions itself where True value was found, for that reason is used index method.

As you should know, index method return a ValueError when an item was not found.

def mapping():
  try:
    col2 = df['col2'].to_list() #[ [a, b], [a, b], [a, b, c], ...]
    for a, b in zip(ref_a, ref_b):
      # Here you are going to get a list of boolean where True means ref_a was found in a sub-list
      booleans = list(map(lambda subl: a in subl, col2))
      index = booleans.index(True) # The possition where ref_a was found
      df.loc[index, 'check'] = b
  except ValueError as e:
    print(e)

mapping()
print(df)

Output:

col1
col2
check

0
1
[a, b]

1
2
[a, b]

2
3
[a, b, c]
option1

3
4
[a, b, d]
option2

4
5
[a, b, e]
option3


问:
Match if element of array is a partial match to a string?
I am aware of

```<code>if ( grep(/^$pattern$/, @array) ) {...}
</code>```

which will return true if the entire string is found in an element of the array.
However im trying to figure out how to return true if one of the elements in the array is a partial match to the end of the string.

For example:

```<code>my @array = (".com", ".net", ".org");
my $domain = "www.example.com";   #<--Returns True
   $domain = "www.example.gov";   #<--Returns False
   $domain = "www.computer.gov";  #<--Returns False, .com not at end
</code>```

Is there a more elegant way to do this without creating a foreach() and using a m// match against each element?

答:
How about</p>
```<code>my @array = (".com", ".net", ".org");
my $pattern = join "|", map quotemeta, @array;

if ($domain =~ /(?:$pattern)$/)    # $ matches end of string
</code>```

Body:
I am aware of

if ( grep(/^$pattern$/, @array) ) {...}

which will return true if the entire string is found in an element of the array.
However im trying to figure out how to return true if one of the elements in the array is a partial match to the end of the string.

For example:

my @array = (".com", ".net", ".org");
my $domain = "www.example.com";   #<--Returns True
   $domain = "www.example.gov";   #<--Returns False
   $domain = "www.computer.gov";  #<--Returns False, .com not at end

Is there a more elegant way to do this without creating a foreach() and using a m// match against each element?

Body:
How about

my @array = (".com", ".net", ".org");
my $pattern = join "|", map quotemeta, @array;

if ($domain =~ /(?:$pattern)$/)    # $ matches end of string


问:
How to bulk set custom filed meta value as tags in wordpress?
I have a million articles in my blog and they all have a custom meta-key named fromname_value

and I want to automatically turn this field into the corresponding article tag.

I add some code in function.php

```<code>function my_migration_script()
{
    global $wpdb;

    // Quick and dirty way to get post ids. Normally don't use this method.
    $post_ids = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE post_type = 'post'");

    // Loop through all ids.
    foreach ($post_ids as $post_id) {

        // Grab the location meta value if it exists.
        if ($value = get_post_meta($post_id, 'fromname_value', true)) {

            // Remove any commas since it's used as a delimiter.
            $value = str_replace(',', '', $value);

            // Create a tag based on the `location` custom field value.
            wp_add_post_tags($post_id, $value);
        }
    }

    // Uncomment if you'd rather delete without verifying first.
    // $wpdb->delete( $wpdb->postmeta, array( 'meta_key' => 'location' ) );
}

// Kick off the script.
my_migration_script();
</code>```

But this function will make the whole process super slow and will prompt 502 error.

I also installed plugin: https://en-ca.wordpress.org/plugins/wp-custom-taxonomy-meta/

However, this plugin will not be displayed in the menu bar of the website background management interface, and I cannot enter the settings page at all. I think the reason may be that this plugin does not support the latest version of wordpress I am using.

Is there a more ingenious and efficient way to achieve this?
Thanks a lot.

ps:
All my post is from sql below:

```<code>use wordpress

CREATE TEMPORARY TABLE temptable ( col1 VARCHAR(255) NOT NULL,
                            col2 bigint NOT NULL,
                            col3 longtext NOT NULL,
                            col4 VARCHAR(255) NOT NULL,
                            col5 VARCHAR(255) NOT NULL,
                            col6 VARCHAR(10000) NOT NULL,
                            col7 longtext NOT NULL);
LOAD DATA INFILE '/www/wwwroot/csv/b-lengzhishi.csv'
INTO TABLE temptable
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 LINES;

    `post_author`,
        `post_content`,
        `post_title`,
        `post_excerpt`,
        `post_type`,
        `post_status`,
        `comment_status`,
        `ping_status`,
        `to_ping`,
        `pinged`,
        `post_content_filtered`,
        `post_date`)
SELECT  Postid,
        1,
        '',
        col3,
        '',
        'post',
        'publish',
        'open',
        'open',
        '',
        '',
        '',
        col4
FROM temptable;

INSERT INTO `wp_postmeta`(`Post_id`,`meta_key`,`meta_value`)
SELECT Postid,'fromurl_value',col1
FROM temptable;

INSERT INTO `wp_postmeta`(`Post_id`,`meta_key`,`meta_value`)
SELECT Postid,'views',col2
FROM temptable;

INSERT INTO `wp_postmeta`(`Post_id`,`meta_key`,`meta_value`)
SELECT Postid,'fifu_image_url',col6
FROM temptable;

INSERT INTO `wp_term_relationships` (`object_id`, `term_taxonomy_id`)
SELECT Postid,'7'
FROM temptable;

INSERT INTO `wp_postmeta`(`Post_id`,`meta_key`,`meta_value`)
SELECT Postid,'fromname_value',col7
FROM temptable;
</code>```

Actually tags are in the col5, But I don't know how to write sql statement to import.

答:
I think this plugin can help you:

https://wpsheeteditor.com/

```<code>With this editor you can:

Do all kinds of edits live on WP Admin. You can execute math formulas, remove thousands of duplicates, do advanced replacements, execute regex updates, and more

You can export all the fields easily

You can edit in Excel or Google Sheets
</code>```

I never handled a dataset of millions but this can do things in batches and that would be better for not returning into 502-e

Hope this work for you!

Body:
I have a million articles in my blog and they all have a custom meta-key named fromname_value

and I want to automatically turn this field into the corresponding article tag.

I add some code in function.php

function my_migration_script()
{
    global $wpdb;

    // Quick and dirty way to get post ids. Normally don't use this method.
    $post_ids = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE post_type = 'post'");

    // Loop through all ids.
    foreach ($post_ids as $post_id) {

        // Grab the location meta value if it exists.
        if ($value = get_post_meta($post_id, 'fromname_value', true)) {

            // Remove any commas since it's used as a delimiter.
            $value = str_replace(',', '', $value);

            // Create a tag based on the `location` custom field value.
            wp_add_post_tags($post_id, $value);
        }
    }

    // Uncomment if you'd rather delete without verifying first.
    // $wpdb->delete( $wpdb->postmeta, array( 'meta_key' => 'location' ) );
}

// Kick off the script.
my_migration_script();

But this function will make the whole process super slow and will prompt 502 error.

I also installed plugin: https://en-ca.wordpress.org/plugins/wp-custom-taxonomy-meta/

However, this plugin will not be displayed in the menu bar of the website background management interface, and I cannot enter the settings page at all. I think the reason may be that this plugin does not support the latest version of wordpress I am using.

Is there a more ingenious and efficient way to achieve this?
Thanks a lot.

ps:
All my post is from sql below:

use wordpress

CREATE TEMPORARY TABLE temptable ( col1 VARCHAR(255) NOT NULL,
                            col2 bigint NOT NULL,
                            col3 longtext NOT NULL,
                            col4 VARCHAR(255) NOT NULL,
                            col5 VARCHAR(255) NOT NULL,
                            col6 VARCHAR(10000) NOT NULL,
                            col7 longtext NOT NULL);
LOAD DATA INFILE '/www/wwwroot/csv/b-lengzhishi.csv'
INTO TABLE temptable
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 LINES;

    `post_author`,
        `post_content`,
        `post_title`,
        `post_excerpt`,
        `post_type`,
        `post_status`,
        `comment_status`,
        `ping_status`,
        `to_ping`,
        `pinged`,
        `post_content_filtered`,
        `post_date`)
SELECT  Postid,
        1,
        '',
        col3,
        '',
        'post',
        'publish',
        'open',
        'open',
        '',
        '',
        '',
        col4
FROM temptable;

INSERT INTO `wp_postmeta`(`Post_id`,`meta_key`,`meta_value`)
SELECT Postid,'fromurl_value',col1
FROM temptable;

INSERT INTO `wp_postmeta`(`Post_id`,`meta_key`,`meta_value`)
SELECT Postid,'views',col2
FROM temptable;

INSERT INTO `wp_postmeta`(`Post_id`,`meta_key`,`meta_value`)
SELECT Postid,'fifu_image_url',col6
FROM temptable;

INSERT INTO `wp_term_relationships` (`object_id`, `term_taxonomy_id`)
SELECT Postid,'7'
FROM temptable;

INSERT INTO `wp_postmeta`(`Post_id`,`meta_key`,`meta_value`)
SELECT Postid,'fromname_value',col7
FROM temptable;

Actually tags are in the col5, But I don't know how to write sql statement to import.

Body:
I think this plugin can help you:

https://wpsheeteditor.com/

With this editor you can:

Do all kinds of edits live on WP Admin. You can execute math formulas, remove thousands of duplicates, do advanced replacements, execute regex updates, and more

You can export all the fields easily

You can edit in Excel or Google Sheets

I never handled a dataset of millions but this can do things in batches and that would be better for not returning into 502-e

Hope this work for you!


问:
How to enumerate an enum?
How can you enumerate an enum in C#?

E.g. the following code does not compile:

public enum Suit
{
    Spades,
    Hearts,
    Clubs,
    Diamonds
}

public void EnumerateAllSuitsDemoMethod()
{
    foreach (Suit suit in Suit)
    {
        DoSomething(suit);
    }
}
```

And it gives the following compile-time error:

'Suit' is a 'type' but is used like a 'variable'

It fails on the Suit keyword, the second one.

答: A simple Enum.GetNames(EnumType) should work

Title: How to enumerate an enum?

Body:
How can you enumerate an enum in C#?

E.g. the following code does not compile:

public enum Suit
{
    Spades,
    Hearts,
    Clubs,
    Diamonds
}

public void EnumerateAllSuitsDemoMethod()
{
    foreach (Suit suit in Suit)
    {
        DoSomething(suit);
    }
}

And it gives the following compile-time error:

'Suit' is a 'type' but is used like a 'variable'

It fails on the Suit keyword, the second one.

LastEditorDisplayName: alexandrul


问:
C# comparing 2 lists of objects while ignoring the key field
I am trying to compare 2 lists of objects for equality, but I want to ignore the key field.
How can I do this?

Here is an example:

```<code>public class myProduct
{
    int ID {get; set;}
    int field1 {get; set;}
    int field2 {get; set;}
}

<List>myProduct greenProducts = new <List>myProduct();
<List>myProduct purpleProducts = new <List>myProduct();

greenProducts.Add(new myProduct { ID = 1, field1 = 5, field2 = 8});
greenProducts.Add(new myProduct { ID = 2, field1 = 9, field2 = 12});
greenProducts.Add(new myProduct { ID = 3, field1 = 7, field2 = 7});

purpleProducts.Add(new myProduct { ID = 8, field1 = 5, field2 = 8});
purpleProducts.Add(new myProduct { ID = 9, field1 = 9, field2 = 12});
purpleProducts.Add(new myProduct { ID = 10, field1 = 7, field2 = 7});
</code>```

If you ignore the key field (aka the ID field), these lists are exactly the same.

So I want my code to do something like this:

```<code>if (purpleProducts == greenProducts) //I WANT THE ID FIELD IGNORED FOR THE COMPARISON SO RESULT WITH ABOVE DATA WOULD BE TRUE
{
  //DO ACTION HERE
}
</code>```

答:
you can loop through it. Here is a loop that will make sure the number of duplicates are the same.</p>
```<code>public class myProduct
{
    public int ID { get; set; }
    public int field1 { get; set; }
    public int field2 { get; set; }
}
List<myProduct> greenProducts = new List<myProduct>();
List<myProduct> purpleProducts = new List<myProduct>();

greenProducts.Add(new myProduct { ID = 1, field1 = 5, field2 = 8 });
greenProducts.Add(new myProduct { ID = 2, field1 = 9, field2 = 12 });
greenProducts.Add(new myProduct { ID = 3, field1 = 7, field2 = 7 });

purpleProducts.Add(new myProduct { ID = 8, field1 = 5, field2 = 8 });
purpleProducts.Add(new myProduct { ID = 9, field1 = 9, field2 = 12 });
purpleProducts.Add(new myProduct { ID = 10, field1 = 7, field2 = 7 });

var areEqual = true;

if (greenProducts.Count() != purpleProducts.Count()) areEqual = false;
if (areEqual)
{
    foreach (var item in greenProducts)
    {
        if(greenProducts.Where(g => g.field1 == item.field1 && g.field2 == item.field2).Count() != purpleProducts.Where(p => p.field1 == item.field1 && p.field2 == item.field2).Count())
        {
            areEqual = false;
            break;
        }
    }
}
if (areEqual)
{
    //DO ACTION HERE
}
</code>```

Body:
I am trying to compare 2 lists of objects for equality, but I want to ignore the key field.
How can I do this?

Here is an example:

public class myProduct
{
    int ID {get; set;}
    int field1 {get; set;}
    int field2 {get; set;}
}

<List>myProduct greenProducts = new <List>myProduct();
<List>myProduct purpleProducts = new <List>myProduct();

greenProducts.Add(new myProduct { ID = 1, field1 = 5, field2 = 8});
greenProducts.Add(new myProduct { ID = 2, field1 = 9, field2 = 12});
greenProducts.Add(new myProduct { ID = 3, field1 = 7, field2 = 7});

purpleProducts.Add(new myProduct { ID = 8, field1 = 5, field2 = 8});
purpleProducts.Add(new myProduct { ID = 9, field1 = 9, field2 = 12});
purpleProducts.Add(new myProduct { ID = 10, field1 = 7, field2 = 7});

If you ignore the key field (aka the ID field), these lists are exactly the same.

So I want my code to do something like this:

if (purpleProducts == greenProducts) //I WANT THE ID FIELD IGNORED FOR THE COMPARISON SO RESULT WITH ABOVE DATA WOULD BE TRUE
{
  //DO ACTION HERE
}

Body:
you can loop through it. Here is a loop that will make sure the number of duplicates are the same.

public class myProduct
{
    public int ID { get; set; }
    public int field1 { get; set; }
    public int field2 { get; set; }
}
List<myProduct> greenProducts = new List<myProduct>();
List<myProduct> purpleProducts = new List<myProduct>();

greenProducts.Add(new myProduct { ID = 1, field1 = 5, field2 = 8 });
greenProducts.Add(new myProduct { ID = 2, field1 = 9, field2 = 12 });
greenProducts.Add(new myProduct { ID = 3, field1 = 7, field2 = 7 });

purpleProducts.Add(new myProduct { ID = 8, field1 = 5, field2 = 8 });
purpleProducts.Add(new myProduct { ID = 9, field1 = 9, field2 = 12 });
purpleProducts.Add(new myProduct { ID = 10, field1 = 7, field2 = 7 });

var areEqual = true;

if (greenProducts.Count() != purpleProducts.Count()) areEqual = false;
if (areEqual)
{
    foreach (var item in greenProducts)
    {
        if(greenProducts.Where(g => g.field1 == item.field1 && g.field2 == item.field2).Count() != purpleProducts.Where(p => p.field1 == item.field1 && p.field2 == item.field2).Count())
        {
            areEqual = false;
            break;
        }
    }
}
if (areEqual)
{
    //DO ACTION HERE
}


问:
Create dictionary from values extracted through regex
I have a sparql query (qres1) that fetches strings from concepts of an RDF file (eg. below), on which I am applying regex to get two values. I would like to store these values as key-value pair in dictionary.

eg. (rdflib.term.Literal('skin sarcoma', lang='en'), rdflib.term.URIRef('http://purl.obolibrary.org/obo/DOID_2687'))

```<code>pattern_doid = '.*\/(DOID.*)'
pattern_label = '.*\(\'(.*)\',.*'
doid = []
label = []
dict = {}

for line in qres1:
    doid = re.findall(pattern_doid, str(line[0]), re.MULTILINE)
    label = re.findall(pattern_label, str(line[1]), re.MULTILINE)

   #create dictionary with doid as key and prefLabel as value
    dict[doid[0]] = label[0]

</code>```

This gives me the following error.
IndexError: list index out of range

How can I create such dictionary. Any help is highly appreciated.

答:
You could use zip to pair up the keys and values so that if any of them is missing, you won't get an error:

```<code>myDictionary.update(zip(doid[:1],label))
</code>```

BTW dict is a type name in Python,  you should not use it as a variable name.

You might also want to check the order of the lines (line[0],line[1]) vs the patterns (doid,label) you are searching for.  Seems to me that the 'DOID_' part is at line[1] based on your example data)

Body:
I have a sparql query (qres1) that fetches strings from concepts of an RDF file (eg. below), on which I am applying regex to get two values. I would like to store these values as key-value pair in dictionary.

eg. (rdflib.term.Literal('skin sarcoma', lang='en'), rdflib.term.URIRef('http://purl.obolibrary.org/obo/DOID_2687'))

pattern_doid = '.*\/(DOID.*)'
pattern_label = '.*\(\'(.*)\',.*'
doid = []
label = []
dict = {}

for line in qres1:
    doid = re.findall(pattern_doid, str(line[0]), re.MULTILINE)
    label = re.findall(pattern_label, str(line[1]), re.MULTILINE)

   #create dictionary with doid as key and prefLabel as value
    dict[doid[0]] = label[0]

This gives me the following error.
IndexError: list index out of range

How can I create such dictionary. Any help is highly appreciated.

Body:
You could use zip to pair up the keys and values so that if any of them is missing, you won't get an error:

myDictionary.update(zip(doid[:1],label))

BTW dict is a type name in Python,  you should not use it as a variable name.

You might also want to check the order of the lines (line[0],line[1]) vs the patterns (doid,label) you are searching for.  Seems to me that the 'DOID_' part is at line[1] based on your example data)


问:
problem with the if statement
i m parsing a json file.the logic goes like this, if there is no data in the variable named boy.it got to enter the if loop and if there is data it got to enter the else part.but the problem is even if the variable boy is empty(which shows  empty in the console) the loop still enters the else part..cud u guys help me out..below is the code..

```<code>- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Navigation logic may go here. Create and push another view controller.
NSDictionary *boy=[url objectAtIndex:indexPath.row];
NSLog(@"the boy value:%@",boy);
if (boy == NULL)
{
Secondetailview *detailViewController1 = [[Secondetailview alloc] initWithItem:boy];
[self.navigationController pushViewController:detailViewController1 animated:YES];
[detailViewController1 release];
}else
{
    FirstViewDetail *detailViewController = [[FirstViewDetail alloc] initWithItem:boy];

    [self.navigationController pushViewController:detailViewController animated:YES];
    [detailViewController release];
}
</code>```

}

答:
I would try to use if (boy == nil) but that doesn't seem to work either.

Instead do this:

```<code>NSString *str = [NSString stringWithFormat:@"%@", boy];
if ([str isEqualToString:@""]) {
    //boy is nil do your stuff
}
</code>```

Title: problem with the if statement

Body:
i m parsing a json file.the logic goes like this, if there is no data in the variable named boy.it got to enter the if loop and if there is data it got to enter the else part.but the problem is even if the variable boy is empty(which shows  empty in the console) the loop still enters the else part..cud u guys help me out..below is the code..

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Navigation logic may go here. Create and push another view controller.
NSDictionary *boy=[url objectAtIndex:indexPath.row];
NSLog(@"the boy value:%@",boy);
if (boy == NULL)
{
Secondetailview *detailViewController1 = [[Secondetailview alloc] initWithItem:boy];
[self.navigationController pushViewController:detailViewController1 animated:YES];
[detailViewController1 release];
}else
{
    FirstViewDetail *detailViewController = [[FirstViewDetail alloc] initWithItem:boy];

    [self.navigationController pushViewController:detailViewController animated:YES];
    [detailViewController release];
}

}

Body:
I would try to use if (boy == nil) but that doesn't seem to work either.

Instead do this:

NSString *str = [NSString stringWithFormat:@"%@", boy];
if ([str isEqualToString:@""]) {
    //boy is nil do your stuff
}


问:
How to multiply test data sets in JUnit 5 Parameterized test?
Here is an example of Parameterized test in JUnit 5.

```<code>@ParameterizedTest
@MethodSource("generalDataset")
fun shouldCreateItem(color: String, size: String) {
    val item = Item(color, size)

    assertThat(item.color).isEqualTo(color)
}

@JvmStatic
fun generalDataset() =
    Stream.of(
        arguments("blue", "S"),
        arguments("red", "S"),
        arguments("green", "S"),
        arguments("blue", "L"),
        arguments("red", "L"),
        arguments("green", "L")
    )
</code>```

See that generalDataset is a multiplcation of two sets {"blue", "red", "green"} x {"S", "L"}.

To avoid duplication it would be great to describe it explicitly like this pseudocode

```<code>@ParameterizedTest
@MethodSource("colorDataset"  %MULTIPLY%  "sizeDataset")
fun shouldCreateItem(color: String, size: String) {
    val item = Item(color, size)

    assertThat(item.color).isEqualTo(color)
}

@JvmStatic
fun colorDataset() =
    Stream.of(
        arguments("blue"),
        arguments("red"),
        arguments("green")
    )

@JvmStatic
fun sizeDataset() =
    Stream.of(
        arguments("S"),
        arguments("L")
    )
</code>```

Is it possible to implement something similar (Parameterized test with multiplied sources) in JUnit 5?

答:
If you want to avoid using external library I wrote some code to do Cartesian product, not that much tested, but simple and works

Edit: I have optimized the code to memorize recursive call

```<code>class SomeTestClass {

    @ParameterizedTest
    @MethodSource("SomeTestClassKt#provideSomeData")
    fun someTest(first: String, second: Boolean, third: Int) {
        println("first = $first, second = $second, third = $third")
    }

}

private fun provideSomeData(): Stream<Arguments> {
    return cartesianArguments(
        listOf("Product1", "Product2", "Product3"),
        listOf(true, false),
        listOf(1, 5, 12)
    )
}

inline fun <reified T> cartesianArguments(vararg input: List<T>): Stream<Arguments> {
    return cartesianRecurrence(input.toList())
        .stream()
        .map { Arguments.of(*it.toTypedArray()) }

}

fun <T> cartesianRecurrence(input: List<List<T>>): List<List<T>> {
    if (input.size < 2)
        return input.flatten().map { listOf(it) }

    val result = cartesianRecurrence(input.tail)
    return input.head.flatMap { headElement ->
        result.map { headElement + it }
    }
}

operator fun <T> T.plus(tail: List<T>): List<T> {
    val list = ArrayList<T>(1 + tail.size)

    list.add(this)
    list.addAll(tail)

    return list
}

val <T> List<T>.tail: List<T>
    get() = drop(1)

val <T> List<T>.head: T
    get() = first()
</code>```

This produces result:

```<code>first = Product1, second = true, third = 1
first = Product1, second = true, third = 5
first = Product1, second = true, third = 12
first = Product1, second = false, third = 1
first = Product1, second = false, third = 5
first = Product1, second = false, third = 12
first = Product2, second = true, third = 1
first = Product2, second = true, third = 5
first = Product2, second = true, third = 12
first = Product2, second = false, third = 1
first = Product2, second = false, third = 5
first = Product2, second = false, third = 12
first = Product3, second = true, third = 1
first = Product3, second = true, third = 5
first = Product3, second = true, third = 12
first = Product3, second = false, third = 1
first = Product3, second = false, third = 5
first = Product3, second = false, third = 12
</code>```

Body:
Here is an example of Parameterized test in JUnit 5.

@ParameterizedTest
@MethodSource("generalDataset")
fun shouldCreateItem(color: String, size: String) {
    val item = Item(color, size)

    assertThat(item.color).isEqualTo(color)
}

@JvmStatic
fun generalDataset() =
    Stream.of(
        arguments("blue", "S"),
        arguments("red", "S"),
        arguments("green", "S"),
        arguments("blue", "L"),
        arguments("red", "L"),
        arguments("green", "L")
    )

See that generalDataset is a multiplcation of two sets {"blue", "red", "green"} x {"S", "L"}.

To avoid duplication it would be great to describe it explicitly like this pseudocode

@ParameterizedTest
@MethodSource("colorDataset"  %MULTIPLY%  "sizeDataset")
fun shouldCreateItem(color: String, size: String) {
    val item = Item(color, size)

    assertThat(item.color).isEqualTo(color)
}

@JvmStatic
fun colorDataset() =
    Stream.of(
        arguments("blue"),
        arguments("red"),
        arguments("green")
    )

@JvmStatic
fun sizeDataset() =
    Stream.of(
        arguments("S"),
        arguments("L")
    )

Is it possible to implement something similar (Parameterized test with multiplied sources) in JUnit 5?

Body:
If you want to avoid using external library I wrote some code to do Cartesian product, not that much tested, but simple and works

Edit: I have optimized the code to memorize recursive call

class SomeTestClass {

    @ParameterizedTest
    @MethodSource("SomeTestClassKt#provideSomeData")
    fun someTest(first: String, second: Boolean, third: Int) {
        println("first = $first, second = $second, third = $third")
    }

}

private fun provideSomeData(): Stream<Arguments> {
    return cartesianArguments(
        listOf("Product1", "Product2", "Product3"),
        listOf(true, false),
        listOf(1, 5, 12)
    )
}

inline fun <reified T> cartesianArguments(vararg input: List<T>): Stream<Arguments> {
    return cartesianRecurrence(input.toList())
        .stream()
        .map { Arguments.of(*it.toTypedArray()) }

}

fun <T> cartesianRecurrence(input: List<List<T>>): List<List<T>> {
    if (input.size < 2)
        return input.flatten().map { listOf(it) }

    val result = cartesianRecurrence(input.tail)
    return input.head.flatMap { headElement ->
        result.map { headElement + it }
    }
}

operator fun <T> T.plus(tail: List<T>): List<T> {
    val list = ArrayList<T>(1 + tail.size)

    list.add(this)
    list.addAll(tail)

    return list
}

val <T> List<T>.tail: List<T>
    get() = drop(1)

val <T> List<T>.head: T
    get() = first()

This produces result:

first = Product1, second = true, third = 1
first = Product1, second = true, third = 5
first = Product1, second = true, third = 12
first = Product1, second = false, third = 1
first = Product1, second = false, third = 5
first = Product1, second = false, third = 12
first = Product2, second = true, third = 1
first = Product2, second = true, third = 5
first = Product2, second = true, third = 12
first = Product2, second = false, third = 1
first = Product2, second = false, third = 5
first = Product2, second = false, third = 12
first = Product3, second = true, third = 1
first = Product3, second = true, third = 5
first = Product3, second = true, third = 12
first = Product3, second = false, third = 1
first = Product3, second = false, third = 5
first = Product3, second = false, third = 12


问:
(TBS) TinyButStrong optional sub-blocks
Is there a way to make sub-blocks optional,  there are cases when a sub-block doesn't contain any information and I get errors. Lets say I have a block that contains people's data, like their full name, date of birth, then I have a sub-block for vehicles they own, there might be cases when they don't own one.</p>

答:
You can use parameter bmagnet in order to delete a block when it has no data. It works also for sub-blocks.

Doc on parameter bmagnet

Title: (TBS) TinyButStrong optional sub-blocks


问:
package com.sun.beans.finder does not exist openjdk
When a file is compiled that imports com.sun.beans.finder.ConstructorFinder, this error comes out:

```<code>./src/Demo/FeatConstruction.java:14: error: package com.sun.beans.finder does not exist
</code>```

The system is an Ubuntu 18.04.1 with OpenJDK:

```<code>openjdk version "1.8.0_322"
OpenJDK Runtime Environment (build 1.8.0_322-b06)
</code>```

Where can I find this package?

The compilation process is as follows:

Sources files are located in src

Some jar dependencies are in lib

The output classes are in bin

For ./src/Demo/FeatConstruction.java, I compile it using:

javac -cp "./src:./lib" -d bin ./src/Demo/FeatConstruction.java
```

答:
First of all, you shouldn't be trying to use this class in your code.  It is an internal class.  All classes in com.sun.* are notionally internal, and should not be used directly in your code.

The class exists in the OpenJDK codebase (Java 8, 11 and even 17), and is present in rt.jar in the OpenJDK Java 8 installation on my Ubuntu box.

But even so, my Java 8 javac is still saying that the package does not exist.  So I suspect that javac itself is black-listing the package.

There might be a workaround1 for this, but my advice is DON'T DO IT.  Find another way to implement the functionality rather than relying on some undocumented internal class.  For example, look for a well written2 3rd-party library.

If you do find a way to make your code compile and run on Java 8, be aware that it is liable to stop working on later releases.  1) The class may be renamed or removed without notice.  2) In later versions, they are making it harder and harder to directly use JDK internal classes in your code.

If you persist with this bad practice you are stacking up future problems for yourself ... or the poor mug who has to maintain your code.

1 - ... but I doubt that switching to an Oracle Java 8 distro is going to help.

2 - A library that doesn't do this kind of bad stuff under the covers.

Body:
When a file is compiled that imports com.sun.beans.finder.ConstructorFinder, this error comes out:

./src/Demo/FeatConstruction.java:14: error: package com.sun.beans.finder does not exist

The system is an Ubuntu 18.04.1 with OpenJDK:

openjdk version "1.8.0_322"
OpenJDK Runtime Environment (build 1.8.0_322-b06)

Where can I find this package?

The compilation process is as follows:

Sources files are located in src

Some jar dependencies are in lib

The output classes are in bin

For ./src/Demo/FeatConstruction.java, I compile it using:

javac -cp "./src:./lib" -d bin ./src/Demo/FeatConstruction.java


问:
Reveal animation not working as I'd like. Layout loading for split second then disappearing
So I have a reveal animation in my react app which uses ScrollReveal package and Im struggling to make it work properly.

The animation itself works great however I found that when I navigate through the app and come back to the home page where the layout is supposed to be revealed, the full layout shows up for a split second then disappears to begin the animation. I think its fair to want the animation to start right away and not have that gitter effect at the beggining.
I currently have it in a useEffect cuz I thought that would fix it however it didn't. It also tried useLayoutEffect and it doesn't work.

The code for the home page component that gets revealed:

```<code>import React, { useEffect } from "react";
import ScrollReveal from "scrollreveal";
import {
    Title,
    HomeContainer,
    Subtitle,
    TitleButton,
  Hi,
  Name,
  ButtonContainer
} from "../../styles/Home-styles";

const Home = () => {
  useEffect(() => {
    ScrollReveal().reveal('.title' , {duration: 500, origin:"top", distance: "0.5em", delay: 0 , easing: "ease-in-out"});
    ScrollReveal().reveal('.subtitle', {duration: 500, origin:"top", distance: "1em", delay: 300, easing: "ease-in-out"});
    ScrollReveal().reveal('.button', {duration: 500, delay: 1000, distance: '0px', opacity: 0, easing: "ease-in-out"})

  }, []);

    return (
        <HomeContainer>
            <Title className="title">
                <Hi>Hi, </Hi>
                <Name>I'm Saif.</Name>
            </Title>
            <Subtitle className="subtitle">This is a subtitle</Subtitle>
            <ButtonContainer className="button">
                <TitleButton to="/about">button</TitleButton>
            </ButtonContainer>
        </HomeContainer>
    );
};

export default Home;
</code>```

答: Your animation starts after a layout is rendered, because your useEffect hook is triggered after component is mounted. So first markup is rendered, only after that an animation takes place and force your elements to animate. Set initial CSS styles: hide elements behind the viewport using absolute positioning in CSS, use opacity: 0 and so on</p>

Body:
So I have a reveal animation in my react app which uses ScrollReveal package and Im struggling to make it work properly.

The animation itself works great however I found that when I navigate through the app and come back to the home page where the layout is supposed to be revealed, the full layout shows up for a split second then disappears to begin the animation. I think its fair to want the animation to start right away and not have that gitter effect at the beggining.
I currently have it in a useEffect cuz I thought that would fix it however it didn't. It also tried useLayoutEffect and it doesn't work.

The code for the home page component that gets revealed:

import React, { useEffect } from "react";
import ScrollReveal from "scrollreveal";
import {
    Title,
    HomeContainer,
    Subtitle,
    TitleButton,
  Hi,
  Name,
  ButtonContainer
} from "../../styles/Home-styles";

const Home = () => {
  useEffect(() => {
    ScrollReveal().reveal('.title' , {duration: 500, origin:"top", distance: "0.5em", delay: 0 , easing: "ease-in-out"});
    ScrollReveal().reveal('.subtitle', {duration: 500, origin:"top", distance: "1em", delay: 300, easing: "ease-in-out"});
    ScrollReveal().reveal('.button', {duration: 500, delay: 1000, distance: '0px', opacity: 0, easing: "ease-in-out"})

  }, []);

    return (
        <HomeContainer>
            <Title className="title">
                <Hi>Hi, </Hi>
                <Name>I'm Saif.</Name>
            </Title>
            <Subtitle className="subtitle">This is a subtitle</Subtitle>
            <ButtonContainer className="button">
                <TitleButton to="/about">button</TitleButton>
            </ButtonContainer>
        </HomeContainer>
    );
};

export default Home;


问:
Google Vision - Batch Image Annotation, map result to request images
I'm using Google Vision to detect text in images (on my backend written in kotlin).
I want to do a batch request with multiple images from a web url but the problem I'm facing is how to know what results maps to what image in the request?

Can I rely on Google to return the result in the same order as I put them into the batch request?

Currently I do not get any information in the response that I can use to figure out to what image the annotated text belongs to. And it's important that the text can be mapped to the correct image.

If you need more information please let me know and I'll provide it to you.

答: The responses are in the same order as they are in the request.</p>


问:
How can I Compare 2 Audio Files Programmatically?
I want to compare 2 audio files programmatically.
For example: I have a sound file in my iPhone app, and then I record another one. I want to check if the existing sound matches the recorded sound or not ( - similar to voice recognition).

How can I accomplish this?

答:
Apply bandpass filter to reduce noise

Normalize for amplitude

Calculate the cross-correlation

It can be fairly Mhz intensive.

The DSP details are in the well known text:

Digital Signal Processing by
Alan V. Oppenheim and Ronald W. Schafer


问:
WPF set DataContext to a ViewModel without default constructor
I have a ViewModel that accepts several constructor parameters. As I understand because of this the only way to set View's DataContext is using code behind.

This has its downsides:

Visual Studio will not show ViewModel inteliscence for the view that is being constructed

There is no way to see design time data that is defined in my ViewModel constructor in XAML designer because designer simply breaks

What are my options?

I would like to have a ViewModel that can accept constructor parameters, have design time data and that my Visual Studio inteliscence provide me suggestions about members in my ViewModel so I could have a good design experience.

PS. I'm using MVVM Toolkit / Windows Community Toolkit from Microsoft, but I would appreciate any answer on how to achieve my end goal. Thank you.

答:
The cleanest way to assign a view-model with a paramterised constructor as the data context for a view is using the ViewModelLocator pattern.

```<code>public class ViewModelLocator
{
    public ViewModelLocator()
    {
        // define view-model definitions in IoC container.
    }

    public MainViewModel MainViewModel
    {
        get
        {
            // use the appropriate construct for your choice of IoC container
            var result = IoCContainer.GetInstance<MainViewModel>();
            return result;
        }
    }
}
</code>```

An instance of this class can be created in App.xaml

```<code><Application.Resources>
    <local:ViewModelLocator x:Key="ViewModelLocator">
</Application.Resources>
</code>```

which becomes an application wide resource, that can be referenced in each view.

Now we can fetch an instance of a specific view-model at any time, including in the designer, and assign it as the DataContext of the view.

```<code><Window
    x:Class="MyApplication.MainView"
    ...
    DataContext="{Binding Source={StaticResource ViewModelLocator}, Path=MainViewModel}" />
</code>```

For more details on the usage of this ViewModelLocator pattern, including having design-time data in your ViewModel, check out my blog post.

Body:
The cleanest way to assign a view-model with a paramterised constructor as the data context for a view is using the ViewModelLocator pattern.

public class ViewModelLocator
{
    public ViewModelLocator()
    {
        // define view-model definitions in IoC container.
    }

    public MainViewModel MainViewModel
    {
        get
        {
            // use the appropriate construct for your choice of IoC container
            var result = IoCContainer.GetInstance<MainViewModel>();
            return result;
        }
    }
}

An instance of this class can be created in App.xaml

<Application.Resources>
    <local:ViewModelLocator x:Key="ViewModelLocator">
</Application.Resources>

which becomes an application wide resource, that can be referenced in each view.

Now we can fetch an instance of a specific view-model at any time, including in the designer, and assign it as the DataContext of the view.

<Window
    x:Class="MyApplication.MainView"
    ...
    DataContext="{Binding Source={StaticResource ViewModelLocator}, Path=MainViewModel}" />

For more details on the usage of this ViewModelLocator pattern, including having design-time data in your ViewModel, check out my blog post.


问:
event not fire correctly for the first time
I am using the FileUpload control inside an Ajax updatepanel. I also am using a post-back trigger to force the upload button to postback.
However, when I click on the upload button for the first time, FileUpload.PostedFile = null. Yet, it works fine after the first time .
I don't know what's the error here ? </p>

答: If you are going to use ajax, I highly recommend using the async file uploader in the Ajax Control Toolkit. The update panel and the standard ASP.NET file upload control do not play nicely with one another. The AJAX Control toolkit version of the control should solve most of your problems. However, for your immediate problem, make sure the form tag has multipart specified.</p>


问:
Bootstrap close responsive menu "on click"
On "PRODUCTS" click I slide up a white div (as seen in attached).  When in responsive (mobile and tablet), I would like to automaticly close the responsive navbar and only show the white bar.

I tried:

```<code>$('.btn-navbar').click();
</code>```

also tried:

```<code>$('.nav-collapse').toggle();
</code>```

And it does work. However in desktop size, it is also called and does something funky to the menu where it shrinks for a second.

Any ideas?

答:
For peeps looking for a solution concerning Vue 3 router-link with Bootstrap 5 + data-bs-attributes:

Using data-bs-attributes to toggle the nav directly on a Vue-router-link doesn't seem to work - so instead you need to wrap each of your nav-links in a parent element if not already done (an li would be the obvious choice) and apply the relevant data-bs-attributes on that element.

In short - instead of this:

```<code><li class="nav-item">
  <router-link
    to="/galaxy"
    class="nav-link d-flex"
    data-bs-toggle="collapse"
    data-bs-target="#navbarCollapse.show"
  >
    <v-icon name="gi-galaxy" size="1" class="align-middle" scale="1.5" />
    <span class="flex-fill align-middle text-start ms-3 ms-lg-1">The Galaxy</span>
  </router-link>
</li>
</code>```

Use this:

```<code><li class="nav-item" data-bs-toggle="collapse" data-bs-target="#navbarCollapse.show">
  <router-link to="/galaxy" class="nav-link d-flex">
    <v-icon name="gi-galaxy" class="align-middle" scale="1.5" />
    <span class="flex-fill align-middle text-start ms-3 ms-lg-1">The Galaxy</span>
  </router-link>
</li>
</code>```

Body:
On "PRODUCTS" click I slide up a white div (as seen in attached).  When in responsive (mobile and tablet), I would like to automaticly close the responsive navbar and only show the white bar.

I tried:

$('.btn-navbar').click();

also tried:

$('.nav-collapse').toggle();

And it does work. However in desktop size, it is also called and does something funky to the menu where it shrinks for a second.

Any ideas?

Body:
For peeps looking for a solution concerning Vue 3 router-link with Bootstrap 5 + data-bs-attributes:

Using data-bs-attributes to toggle the nav directly on a Vue-router-link doesn't seem to work - so instead you need to wrap each of your nav-links in a parent element if not already done (an li would be the obvious choice) and apply the relevant data-bs-attributes on that element.

In short - instead of this:

<li class="nav-item">
  <router-link
    to="/galaxy"
    class="nav-link d-flex"
    data-bs-toggle="collapse"
    data-bs-target="#navbarCollapse.show"
  >
    <v-icon name="gi-galaxy" size="1" class="align-middle" scale="1.5" />
    <span class="flex-fill align-middle text-start ms-3 ms-lg-1">The Galaxy</span>
  </router-link>
</li>

Use this:

<li class="nav-item" data-bs-toggle="collapse" data-bs-target="#navbarCollapse.show">
  <router-link to="/galaxy" class="nav-link d-flex">
    <v-icon name="gi-galaxy" class="align-middle" scale="1.5" />
    <span class="flex-fill align-middle text-start ms-3 ms-lg-1">The Galaxy</span>
  </router-link>
</li>


问:
Openpyxl - Merge Empty Column Cells Delimited by String
I've been doing some big data work, and I've been writing a script to automate the formatting of a 15,000+ row .csv into a formatted excel file.  I've been using Openpyxl for most of the formatting work.

I need to merge the server name cells in the Hostname column with the empty cells below it, but can't seem to get it working.  In the table below, I need to merge Dev Server with all of the empty cells below it (to stop at RAS Server).  Then merge RAS Server with the empty cells below that, and Prod Server with the empty cells below that.

The issue I'm having is I can't seem to specify the right for loop that identifies a cell with a string, iterates through each of the cells below it (merging with the empty cells), and then stopping and starting a new merged cell at the next cell containing a string.

Specified parameters/cell numbers cannot work here - the real table is 15,000+ lines long, and the amount of 'installed software' on each server ranges from 25-200+ per server.  To make things better, the real server names also have no consistent naming pattern or scheme.

Is this possible?  Any help or direction would be much appreciated.

Hostname
Installed Software

Dev Server
Microsoft Word

Microsoft Excel

Microsoft Teams

Visual Studio Code

Discord

RAS Server
Microsoft Word

Spotify

Log4j

Prod Server
Adobe Photoshop

Unreal Engine

Adobe PDF Reader

Steam

Adobe Illustrator

Hyper-V

答:
```<code>wb = openpyxl.load_workbook("Test.xlsx")  # Load Workbook
ws = wb["Sheet1"]                         # Load Worksheet

    total_rows = []  # Used to enumerate the total number of rows
                     # in the Worksheet

    for i in range (1,20000):
        if ws["B" + str(i)].value != None:
            total_rows.append(i)  # If the cell has a string, the
                                  # cell row number is appended to
                                  # total_rows.  Indexing the last
                                  # number in total_rows will give
                                  # you the total number of rows

    cells_with_strings = []
    for i in range (1,(total_rows[-1])):
        if ws["A" + str(i)].value != None:
            cells_with_strings.append(int(i))
            # Iterates through each cell in column A, and appends
            # the row numbers of cells containing text to cells_with_strings

    merge_cell_range = len(cells_with_strings) - 1
    for i in range (0, (merge_cell_range)):
        ws.merge_cells("A" + str(cells_with_strings[i]) + ":" + "A" + str((cells_with_strings[(i+1)])-1))
        # Using the values in cell_with_strings, it merges the cells in the rows
        # represented by the values in cells_with_strings.  This works for all
        # merges except for the last merge.

    final_merge = []
    for i in range ((cells_with_strings[-1]), ((cells_with_strings[-1]) + 9999)):
        if ws["B" + str(i)].value != None:
            final_merge.append(int(i))
    ws.merge_cells("A" + str(final_merge[0]) + ":" + "A" + str(final_merge[-1]))
    # The last row merge requires different code to the iteration merge.

wb.save("Test.xlsx")
</code>```