问:
How to use index and get rid of React Warning: Each child in a list should have a unique "key" prop?
Hello I'm facing this error, question is how to propertly pass index in this component?

Error:

```<code>react-jsx-dev-runtime.development.js:117 Warning: Each child in a list should have a unique "key" prop.
</code>```

Here is the component's code fragment:

```<code>                            {calculatorScreenshots.map((imgUrl: any, index) => {
                                return (
                                    <Zoom>
                                        {props.projectName == 'Calculator' && (
                                            <CardMedia
                                                key={index}
                                                component="img"
                                                height="200"
                                                alt="project picture"
                                                image={imgUrl}
                                            />
                                        )}
                                    </Zoom>
                                );
                            })}
</code>```

答:
You should write key in <Zoom /> component rather than in <CardMedia /> like this

<Zoom key={index} />

Note: Always write key to first item component/element you are rendering here it is <Zoom />.

Body:
Hello I'm facing this error, question is how to propertly pass index in this component?

Error:

react-jsx-dev-runtime.development.js:117 Warning: Each child in a list should have a unique "key" prop.

Here is the component's code fragment:

                            {calculatorScreenshots.map((imgUrl: any, index) => {
                                return (
                                    <Zoom>
                                        {props.projectName == 'Calculator' && (
                                            <CardMedia
                                                key={index}
                                                component="img"
                                                height="200"
                                                alt="project picture"
                                                image={imgUrl}
                                            />
                                        )}
                                    </Zoom>
                                );
                            })}


来源: stackexchange

问:
Understanding the full architecture of Infinispan?
I am starting a project with a client where a central part is high performance caching of a large dataset. I am at the moment looking into various OSS projects and Infinispan looks very interesting. I have however yet to find a good "architecture" level overview of what cache configurations that are possible etc.
Our requirements are basically:

Ability to create a local (library) on-heap (Java) L1 cache, an off-heap or possible persisted L2 cache and possibly a distributed L3 cache.

The L1 and L2 caches need to be "exclusive" i.e. the entries of the L1 should NOT be present also in the L2 cache as this would cost too much memory.

The L1 cache should preferably use one of the latest and most efficient eviction algorithms (in my view TinyFLU is a good candidate for this).

Can anybody provide some guidance on if/how these things can be archived with Infinispan and where I can read up on how to create a multi-tier combined library + distributed setup as described (is the manual only resource or are there other more "architecture" level resources I can also use)?

答:
A Distributed cache may match most of the requirements (Distributed Cache Documentation)

In a distributed cache, your data is partitioned and stored in different nodes. When reading, if the node is an owner of that key, it reads from local memory (on-heap or off-heap), otherwise, it will do an RPC to the owner of that key. (so, your L3 cache).

About L2 requirement, it can be achieved with persistence storage (Persistence Storage Documentation) with passivation enabled. Passivation will ensure your data lives in memory or in the disk. Data will only be stored in the disk when the eviction strategy removes it from memory (Eviction Documentation).

The L1 requirement can be partially achieved by enabling L1 cache (L1 Cache for Distributed Cache Documentation). When reading the data from a remote node, it is stored in the local memory. This L1 data never goes to the persistence storage and it is removed when eviction needs to free some space or if the data is updated by the local or remote node.

Another alternative is Replicated Caches (Replicated Cache Documentation). A replicated cache keeps a copy of the full dataset in all nodes. With Eviction and Persistence Storage, it ensures your reads will find the data in memory or in the disk, and no RPC is required to fetch the data. The disadvantage is the writes, which have to sync all the nodes.

ContentLicense: CC BY-SA 4.0


问:
Which Riverpod Provider should one use to handle navigation state in combination with Navigator 2.0?
I'm developing a fairly complex cross-platform (Android / iOS / web) app in Flutter. I'm new to Flutter, coming to it from a background of native development for Android and iOS.

I have been researching the best way to handle navigation and state management in Flutter, and my conclusion so far is that the best approach would be to use the Navigator 2.0 API in combination with the Riverpod state management library. As far as I can see, these seem to be the most up-to-date and powerful libraries for navigation and state management in Flutter.

However, I have not found it easy to figure out how to integrate Riverpod with Navigator 2.0. As someone who is new to both libraries and indeed to Flutter in general, I would ideally like to have found some canonical example in the docs (either the Navigator or the Riverpod ones) which shows how this should be done, but I haven't found such an example. In the absence of that, I would be really grateful for any guidance about how to do this, and in particular about which of the many types of Riverpod Providers is best suited to the job of handling navigation state. For example, what would be a reason to prefer ChangeNotifierProvider over StateNotifierProvider, or vice versa? Is there some other kind of Riverpod Provider that would work better than either of these?

答:
I use

```<code>final intendedPathProvider = StateProvider<TypedPath>((_) => <TypedSegment>[]);
</code>```

The navigator then listens to the ongoingPathProvider change.

TypedSegment is an immutable class that represents single item in flutter navigation stack. You change the navigation by call e.g:

```<code>navigator.navigate([HomeSegment(), BooksSegment(), BookSegment(id:1)]);
</code>```

You can see an example of this approach here: https://pavelpz.github.io/doc_simple/#home.

Source code is here:
https://github.com/PavelPZ/riverpod_navigator/blob/main/examples/doc/lib/simple.dart

Body:
I use

final intendedPathProvider = StateProvider<TypedPath>((_) => <TypedSegment>[]);

The navigator then listens to the ongoingPathProvider change.

TypedSegment is an immutable class that represents single item in flutter navigation stack. You change the navigation by call e.g:

navigator.navigate([HomeSegment(), BooksSegment(), BookSegment(id:1)]);

You can see an example of this approach here: https://pavelpz.github.io/doc_simple/#home.

Source code is here:
https://github.com/PavelPZ/riverpod_navigator/blob/main/examples/doc/lib/simple.dart


问:
fastify-http-proxy: Failure with "Promise may not be fulfilled with 'undefined'
I am using the fastify with fastify-http-proxy with the following configuration:

const proxy = require('fastify-http-proxy');
fastify.register(proxy, {
    upstream: "https://myendpoint/occm/api/azure",
    prefix: '/azure',
    onResponse: (request, reply, res) => {
        console.log('Inside onResponse')
        reply.send('New body of different length');
    },
    onError: (reply, error) => {
        console.log('Inside onError')
        reply.send(`My Error: ${error}`);
    },
    replyOptions: {
        rewriteRequestHeaders: (originalRequest, headers) => {
            console.log('Inside rewriteRequestHeaders')
            return {
                ...headers,
            };
        },
    },
});
```
<p>I have configured a fastify route as this:</p>
<pre class="lang-js prettyprint-override"><code> fastify.route({
        method: 'GET',
        url: `/azure/vsa/working-environments`,
        schema: {
            description: 'Trying out',
            tags: ['notifications'],
            security: [{
                authorization: []
            }],
            params:{
                title: "Working Env GET",
                description:'Trying out...',
                type: 'object',
                example: 'No input',
                properties: {
                    'accountId': {
                        description: "Account ID",
                        type: 'string'
                    },
                },
            }
        },
        handler: async (request, reply) => {
        }
</code>```

I am calling it as:

GET http://localhost:xxxx/azure/vsa/working-environments

Basically I would like to proxy the request to this endpoint:

https://myendpoint/occm/api/azure/vsa/working-environments

Now whenever I am running it, getting this error:

```<code>{"level":30,"time":1644249539394,"pid":12100,"hostname":"pradipm02-PC","requestId":"Q3T9RjI11N","req":{"method":"GET","url":"/azure/vsa/working-environments","hostname":"localhost:8092","remoteAddress":"127.0.0.1","remotePort":63308},"msg":"incoming request"}
{"level":50,"time":1644249540657,"pid":12100,"hostname":"pradipm02-PC","requestId":"Q3T9RjI11N","err":{"type":"FastifyError","message":"Promise may not be fulfilled with 'undefined' when statusCode is not 204","stack":"FastifyError: Promise may not be fulfilled with 'undefined' when statusCode is not 204\n    at C:\\Users\\pradipm\\clients\\CloudManager\\cm_2\\occm\\service-infra\\notifications\\node_modules\\fastify\\lib\\wrapThenable.js:30:30\n    at processTicksAndRejections (node:internal/process/task_queues:96:5)","name":"FastifyError","code":"FST_ERR_PROMISE_NOT_FULFILLED","statusCode":500},"msg":"Promise may not be fulfilled with 'undefined' when statusCode is not 204"}

</code>```

Any of the console.log in the rewriteRequestHeaders, onReponse, onError are not showing up.

Any help is appreciated.

答:
This is discussed in the following thread in fastify-http-proxy forum.
It is suggested to use fastify-reply-from instead.
That solves my issue.</p>

Body:
I am using the fastify with fastify-http-proxy with the following configuration:

const proxy = require('fastify-http-proxy');
fastify.register(proxy, {
    upstream: "https://myendpoint/occm/api/azure",
    prefix: '/azure',
    onResponse: (request, reply, res) => {
        console.log('Inside onResponse')
        reply.send('New body of different length');
    },
    onError: (reply, error) => {
        console.log('Inside onError')
        reply.send(`My Error: ${error}`);
    },
    replyOptions: {
        rewriteRequestHeaders: (originalRequest, headers) => {
            console.log('Inside rewriteRequestHeaders')
            return {
                ...headers,
            };
        },
    },
});

I have configured a fastify route as this:

 fastify.route({
        method: 'GET',
        url: `/azure/vsa/working-environments`,
        schema: {
            description: 'Trying out',
            tags: ['notifications'],
            security: [{
                authorization: []
            }],
            params:{
                title: "Working Env GET",
                description:'Trying out...',
                type: 'object',
                example: 'No input',
                properties: {
                    'accountId': {
                        description: "Account ID",
                        type: 'string'
                    },
                },
            }
        },
        handler: async (request, reply) => {
        }

I am calling it as:

GET http://localhost:xxxx/azure/vsa/working-environments

Basically I would like to proxy the request to this endpoint:

https://myendpoint/occm/api/azure/vsa/working-environments

Now whenever I am running it, getting this error:

{"level":30,"time":1644249539394,"pid":12100,"hostname":"pradipm02-PC","requestId":"Q3T9RjI11N","req":{"method":"GET","url":"/azure/vsa/working-environments","hostname":"localhost:8092","remoteAddress":"127.0.0.1","remotePort":63308},"msg":"incoming request"}
{"level":50,"time":1644249540657,"pid":12100,"hostname":"pradipm02-PC","requestId":"Q3T9RjI11N","err":{"type":"FastifyError","message":"Promise may not be fulfilled with 'undefined' when statusCode is not 204","stack":"FastifyError: Promise may not be fulfilled with 'undefined' when statusCode is not 204\n    at C:\\Users\\pradipm\\clients\\CloudManager\\cm_2\\occm\\service-infra\\notifications\\node_modules\\fastify\\lib\\wrapThenable.js:30:30\n    at processTicksAndRejections (node:internal/process/task_queues:96:5)","name":"FastifyError","code":"FST_ERR_PROMISE_NOT_FULFILLED","statusCode":500},"msg":"Promise may not be fulfilled with 'undefined' when statusCode is not 204"}

Any of the console.log in the rewriteRequestHeaders, onReponse, onError are not showing up.

Any help is appreciated.


问:
QGridLayout issue with inserting widgets
(Using Qt 4.6.3, x64, linux)

I'm testing how to properly insert widgets into a existing a QGridLayout filled with various widgets. A broken down contrived case is the following:

```<code>QApplication app(argc,argv);
QWidget      w;
QGridLayout* gl     = new QGridLayout(&w);
QLabel*      label  = new QLabel("Image Size:");
QLineEdit*   wedit  = new QLineEdit("100");
QLabel*      xlabel = new QLabel("x");

wedit->setAlignment(Qt::AlignRight);
gl->addWidget(label);
gl->addWidget(xlabel, 0, 1, 1, 1);
gl->addWidget(wedit,  0, gl->columnCount());
</code>```

Which creates the following widget:

.

Assuming that have an existing QGridLayout as above, but without the "x" label, and I wished to insert this into the layout, switching the latter two addWidget lines might seem valid, i.e.:

```<code>\\ same as above
gl->addWidget(label);
gl->addWidget(wedit,  0, gl->columnCount());
gl->addWidget(xlabel, 0, 1, 1, 1);
</code>```

This however, creates the following:

The gl->columnCount() after this  is still 2, as both the x-label and the QLineEdit are filling the same cell. Based on this knowledge, the following code produces the initial desired result:

```<code>gl->addWidget(label);
gl->addWidget(wedit,  0, 2); // note: specified column 2, columnCount() is now 3
gl->addWidget(xlabel, 0, 1, 1, 1);
</code>```

Though this is not particularly useful, as the original layout in question isn't built with later layouts in mind.

Since addWidget allows for specifying cell position, as well as row/column span, it seems odd that Qt wouldn't automatically replace the existing widgets in the layout. Does anyone have a suggestion as to how I might overcome this? I assume it would be possible to recreate a QGridLayout and copy into it the children of the original, taking care to insert the additional widget in the right location. This however is ugly, and susceptible to Qt version issues (as I want to modify a built in widget).

Edit:

I realize that I'm making the assumption of thinking in a QHBoxLayout way, where inserting a widget is uniquely understood, whereas in a QGridLayout this isn't the case (?).

I can clarify that I ultimately would like to modify QFileDialog::getSaveFileName, by inserting a widget (similar to the widget shown above) right above the two lower rows (i.e. above "File &Name:").

Thanks

答:
A possible solution is to re-add the widgets that should be relocated. I.e.

QLayoutItem* x01 = gl->itemAtPosition(0,1);
gl->addWidget(x01->widget(), 0, 2);
gl->addWidget(xlabel, 0, 1, 1, 1);
```

<p>Now, this isn't particularly pretty, or easy to maintain, as a new version of Qt might change the original widget, and blindly handpicking and relocating children isn't that clever. The following real example (the one I actually wanted to solve) was to alter the Qt's "Save As" dialog window, that shows up using QFileDialog::getSaveFileName.</p>

<pre class="lang-C++ prettyprint-override"><code>class ImageFileDialog : public QFileDialog {
public:
  ImageFileDialog(QWidget* parent);
  ~ImageFileDialog();
  QString getFileName() const;
  QSize getImageSize() const;
  QDialog::DialogCode exec(); // Overriden

protected:
  void showEvent(QShowEvent* event); // Overriden

private:
  QString    fileName_;
  QSize      imageSize_;
  QLineEdit* widthLineEdit_;
  QLineEdit* heightLineEdit_;
};
</code>```

And in the source (showing just constructor, focus handling and exec):

ImageFileDialog::ImageFileDialog(QWidget* parent)
  : fileName_(""),
    imageSize_(0,0),
    widthLineEdit_(0),
    heightLineEdit_(0)
{
  setAcceptMode(QFileDialog::AcceptSave);
  setFileMode(QFileDialog::AnyFile);
  setConfirmOverwrite(true);

  QGridLayout* mainLayout = dynamic_cast<QGridLayout*>(layout());
  assert(mainLayout->columnCount() == 3);
  assert(mainLayout->rowCount()    == 4);

  QWidget*     container      = new QWidget();
  QGridLayout* glayout        = new QGridLayout();
  QLabel*      imageSizeLabel = new QLabel("Image Size:");
  widthLineEdit_              = new QLineEdit("400");
  heightLineEdit_             = new QLineEdit("300");
  widthLineEdit_->setAlignment(Qt::AlignRight);
  heightLineEdit_->setAlignment(Qt::AlignRight);

  container->setLayout(glayout);
  glayout->setAlignment(Qt::AlignLeft);
  glayout->addWidget(widthLineEdit_);
  glayout->addWidget(new QLabel("x"), 0, 1);
  glayout->addWidget(heightLineEdit_, 0, 2);
  glayout->addWidget(new QLabel("[pixels]"), 0, 3);
  glayout->addItem(new QSpacerItem(250, 0), 0, 4);
  glayout->setContentsMargins(0,0,0,0); // Removes unwanted spacing

  // Shifting relevant child widgets one row down.
  int rowCount = mainLayout->rowCount();
  QLayoutItem* x00 = mainLayout->itemAtPosition(mainLayout->rowCount()-2,0);
  QLayoutItem* x10 = mainLayout->itemAtPosition(mainLayout->rowCount()-1,0);
  QLayoutItem* x01 = mainLayout->itemAtPosition(mainLayout->rowCount()-2,1);
  QLayoutItem* x11 = mainLayout->itemAtPosition(mainLayout->rowCount()-1,1);
  QLayoutItem* x02 = mainLayout->itemAtPosition(mainLayout->rowCount()-1,2);
  assert(x00);   assert(x01);   assert(x10);   assert(x11);   assert(x02);

  mainLayout->addWidget(x00->widget(), rowCount-1, 0, 1, 1);
  mainLayout->addWidget(x10->widget(), rowCount,   0, 1, 1);
  mainLayout->addWidget(x01->widget(), rowCount-1, 1, 1, 1);
  mainLayout->addWidget(x11->widget(), rowCount,   1, 1, 1);
  mainLayout->addWidget(x02->widget(), rowCount-1, 2, 2, 1);

  // Adding the widgets in the now empty row.
  rowCount        = mainLayout->rowCount();
  mainLayout->addWidget(imageSizeLabel, rowCount-3, 0, 1, 1 );
  mainLayout->addWidget(container,      rowCount-3, 1, 1, 1);

  // Setting the proper tab-order
  QLayoutItem* tmp  = mainLayout->itemAtPosition(mainLayout->rowCount()-2,1);
  QLayoutItem* tmp2 = mainLayout->itemAtPosition(mainLayout->rowCount()-1,1);
  assert(tmp); assert(tmp2);
  QWidget::setTabOrder(heightLineEdit_      , tmp->widget());
  QWidget::setTabOrder(tmp->widget(), tmp2->widget());
}

// Makes sure the right widget is in focus
void ImageFileDialog::showEvent(QShowEvent* event)
{
  widthLineEdit_->setFocus(Qt::OtherFocusReason);
}

// Called to create the widget
QDialog::DialogCode ImageFileDialog::exec()
{
  if (QFileDialog::exec() == QDialog::Rejected)
    return QDialog::Rejected;
  // The code that processes the widget form and stores results for later calls to
  // getImageSize()
  return QDialog:Accepted;
}
```

<p>Which, using for instance</p>

<pre class="lang-C++ prettyprint-override"><code>ImageFileDialog* dialog = new ImageFileDialog(&w);
dialog->exec();
</code>```

Creates the following widget:

Comments and ways to do this better, or why this is just plain wrong are most welcome :)

ContentLicense: CC BY-SA 3.0

Body:
(Using Qt 4.6.3, x64, linux)

I'm testing how to properly insert widgets into a existing a QGridLayout filled with various widgets. A broken down contrived case is the following:

QApplication app(argc,argv);
QWidget      w;
QGridLayout* gl     = new QGridLayout(&w);
QLabel*      label  = new QLabel("Image Size:");
QLineEdit*   wedit  = new QLineEdit("100");
QLabel*      xlabel = new QLabel("x");

wedit->setAlignment(Qt::AlignRight);
gl->addWidget(label);
gl->addWidget(xlabel, 0, 1, 1, 1);
gl->addWidget(wedit,  0, gl->columnCount());

Which creates the following widget:

.

Assuming that have an existing QGridLayout as above, but without the "x" label, and I wished to insert this into the layout, switching the latter two addWidget lines might seem valid, i.e.:

\\ same as above
gl->addWidget(label);
gl->addWidget(wedit,  0, gl->columnCount());
gl->addWidget(xlabel, 0, 1, 1, 1);

This however, creates the following:

The gl->columnCount() after this  is still 2, as both the x-label and the QLineEdit are filling the same cell. Based on this knowledge, the following code produces the initial desired result:

gl->addWidget(label);
gl->addWidget(wedit,  0, 2); // note: specified column 2, columnCount() is now 3
gl->addWidget(xlabel, 0, 1, 1, 1);

Though this is not particularly useful, as the original layout in question isn't built with later layouts in mind.

Since addWidget allows for specifying cell position, as well as row/column span, it seems odd that Qt wouldn't automatically replace the existing widgets in the layout. Does anyone have a suggestion as to how I might overcome this? I assume it would be possible to recreate a QGridLayout and copy into it the children of the original, taking care to insert the additional widget in the right location. This however is ugly, and susceptible to Qt version issues (as I want to modify a built in widget).

Edit:

I realize that I'm making the assumption of thinking in a QHBoxLayout way, where inserting a widget is uniquely understood, whereas in a QGridLayout this isn't the case (?).

I can clarify that I ultimately would like to modify QFileDialog::getSaveFileName, by inserting a widget (similar to the widget shown above) right above the two lower rows (i.e. above "File &Name:").

Thanks

Body:
A possible solution is to re-add the widgets that should be relocated. I.e.

QLayoutItem* x01 = gl->itemAtPosition(0,1);
gl->addWidget(x01->widget(), 0, 2);
gl->addWidget(xlabel, 0, 1, 1, 1);

Now, this isn't particularly pretty, or easy to maintain, as a new version of Qt might change the original widget, and blindly handpicking and relocating children isn't that clever. The following real example (the one I actually wanted to solve) was to alter the Qt's "Save As" dialog window, that shows up using QFileDialog::getSaveFileName.

class ImageFileDialog : public QFileDialog {
public:
  ImageFileDialog(QWidget* parent);
  ~ImageFileDialog();
  QString getFileName() const;
  QSize getImageSize() const;
  QDialog::DialogCode exec(); // Overriden

protected:
  void showEvent(QShowEvent* event); // Overriden

private:
  QString    fileName_;
  QSize      imageSize_;
  QLineEdit* widthLineEdit_;
  QLineEdit* heightLineEdit_;
};

And in the source (showing just constructor, focus handling and exec):

ImageFileDialog::ImageFileDialog(QWidget* parent)
  : fileName_(""),
    imageSize_(0,0),
    widthLineEdit_(0),
    heightLineEdit_(0)
{
  setAcceptMode(QFileDialog::AcceptSave);
  setFileMode(QFileDialog::AnyFile);
  setConfirmOverwrite(true);

  QGridLayout* mainLayout = dynamic_cast<QGridLayout*>(layout());
  assert(mainLayout->columnCount() == 3);
  assert(mainLayout->rowCount()    == 4);

  QWidget*     container      = new QWidget();
  QGridLayout* glayout        = new QGridLayout();
  QLabel*      imageSizeLabel = new QLabel("Image Size:");
  widthLineEdit_              = new QLineEdit("400");
  heightLineEdit_             = new QLineEdit("300");
  widthLineEdit_->setAlignment(Qt::AlignRight);
  heightLineEdit_->setAlignment(Qt::AlignRight);

  container->setLayout(glayout);
  glayout->setAlignment(Qt::AlignLeft);
  glayout->addWidget(widthLineEdit_);
  glayout->addWidget(new QLabel("x"), 0, 1);
  glayout->addWidget(heightLineEdit_, 0, 2);
  glayout->addWidget(new QLabel("[pixels]"), 0, 3);
  glayout->addItem(new QSpacerItem(250, 0), 0, 4);
  glayout->setContentsMargins(0,0,0,0); // Removes unwanted spacing

  // Shifting relevant child widgets one row down.
  int rowCount = mainLayout->rowCount();
  QLayoutItem* x00 = mainLayout->itemAtPosition(mainLayout->rowCount()-2,0);
  QLayoutItem* x10 = mainLayout->itemAtPosition(mainLayout->rowCount()-1,0);
  QLayoutItem* x01 = mainLayout->itemAtPosition(mainLayout->rowCount()-2,1);
  QLayoutItem* x11 = mainLayout->itemAtPosition(mainLayout->rowCount()-1,1);
  QLayoutItem* x02 = mainLayout->itemAtPosition(mainLayout->rowCount()-1,2);
  assert(x00);   assert(x01);   assert(x10);   assert(x11);   assert(x02);

  mainLayout->addWidget(x00->widget(), rowCount-1, 0, 1, 1);
  mainLayout->addWidget(x10->widget(), rowCount,   0, 1, 1);
  mainLayout->addWidget(x01->widget(), rowCount-1, 1, 1, 1);
  mainLayout->addWidget(x11->widget(), rowCount,   1, 1, 1);
  mainLayout->addWidget(x02->widget(), rowCount-1, 2, 2, 1);

  // Adding the widgets in the now empty row.
  rowCount        = mainLayout->rowCount();
  mainLayout->addWidget(imageSizeLabel, rowCount-3, 0, 1, 1 );
  mainLayout->addWidget(container,      rowCount-3, 1, 1, 1);

  // Setting the proper tab-order
  QLayoutItem* tmp  = mainLayout->itemAtPosition(mainLayout->rowCount()-2,1);
  QLayoutItem* tmp2 = mainLayout->itemAtPosition(mainLayout->rowCount()-1,1);
  assert(tmp); assert(tmp2);
  QWidget::setTabOrder(heightLineEdit_      , tmp->widget());
  QWidget::setTabOrder(tmp->widget(), tmp2->widget());
}

// Makes sure the right widget is in focus
void ImageFileDialog::showEvent(QShowEvent* event)
{
  widthLineEdit_->setFocus(Qt::OtherFocusReason);
}

// Called to create the widget
QDialog::DialogCode ImageFileDialog::exec()
{
  if (QFileDialog::exec() == QDialog::Rejected)
    return QDialog::Rejected;
  // The code that processes the widget form and stores results for later calls to
  // getImageSize()
  return QDialog:Accepted;
}

Which, using for instance

ImageFileDialog* dialog = new ImageFileDialog(&w);
dialog->exec();

Creates the following widget:

Comments and ways to do this better, or why this is just plain wrong are most welcome :)


问:
Adding Click Event Listeners During Iteration?
I'm trying to add a click event listener to a bunch of newly created divs in a for loop. The issue I'm having is that only the last div keeps its event listener. I've read up about closures and read several other posts and questions and their answers, and as far as I can tell I have it set up correctly. But it still isn't working for me. Only the final div to be iterated is receiving the event listener.

function edit_entry(k) {
    wrd_input.value = k;
    def_input.value = lexicon[k][1];
    wrd_input.onkeyup();

    delete lexicon[k];
    rewrite_entries();
}

function rewrite_entries(keys = null) {
    if (keys === null) { keys = []; }
    let sorted_keys = sort_lex_keys();
    lex_body.style.color = 'rgb(200, 200, 200)';
    lex_body.innerHTML = '';

    sorted_keys.forEach((key) => {
        if (!keys.length || keys.includes(key)) {
        lex_body.innerHTML +=
        `<div class='lex-entry' id=${key}><i>${key}</i>\n<p class='pronunciation'>${lexicon[key][0]}</p>${lexicon[key][1]}</div>\n`;
        let entry = document.getElementById(key)
        entry.addEventListener('click', edit_entry.bind(this, key) );
        }
    });
}
```
<p>Current state of the relevant code above. If somebody knows the issue, it'd be very helpful.
If it's relevant, this code is running via Electron (17.0.0).</p>
<p>An attempted solution, using an anonymous arrow function instead of a bind:</p>
<pre class="lang-js prettyprint-override"><code>entry.addEventListener('click', () => edit_entry(key) );
</code>```

yields the same result.

Update:
Changing the .innerHTML attribute of something apparently strips all event listeners. So the solution was simply to create the element completely in js, add it to the container, and then add the listener. This change to the forEach loop solves the problem:

    sorted_keys.forEach((key) => {
        if (!keys.length || keys.includes(key)) {
            let entry = document.createElement('div');
            entry.className = 'lex-entry';

            let word = document.createElement('p');
            word.appendChild( document.createTextNode(key) );
            word.style.fontStyle = 'italic';

            let pron = document.createElement('p');
            pron.className = 'pronunciation';
            pron.appendChild( document.createTextNode(lexicon[key][0]) );

            let defn = document.createTextNode(lexicon[key][1]);

            entry.append(word, pron, defn);
            entry.addEventListener('click', () => edit_entry(key) );

            lex_body.appendChild(entry);
```

答:
So a few things crosses my mind:

Firstly, edit_entry.bind(this, key);: Are you certain this is pointing to what you want? It should be pointing to the window object. Also, is there any reason to bind context for that particular function?

Secondly innerHTML: Generally it's discouraged to use innerHTML directly. I don't know how/when the browser layouts changes to innerHTML, the div might not be on the page when you call getElementById. As an alternative, you could try document.createElement("div"), set its properties accordingly and finally append it to lex_body.

Edit

From mdn:

Please note that using innerHTML to append html elements (e.g. el.innerHTML += "link") will result in the removal of any previously set event listeners. That is, after you append any HTML element that way you won't be able to listen to the previously set event listeners.

Body:
I'm trying to add a click event listener to a bunch of newly created divs in a for loop. The issue I'm having is that only the last div keeps its event listener. I've read up about closures and read several other posts and questions and their answers, and as far as I can tell I have it set up correctly. But it still isn't working for me. Only the final div to be iterated is receiving the event listener.

function edit_entry(k) {
    wrd_input.value = k;
    def_input.value = lexicon[k][1];
    wrd_input.onkeyup();

    delete lexicon[k];
    rewrite_entries();
}

function rewrite_entries(keys = null) {
    if (keys === null) { keys = []; }
    let sorted_keys = sort_lex_keys();
    lex_body.style.color = 'rgb(200, 200, 200)';
    lex_body.innerHTML = '';

    sorted_keys.forEach((key) => {
        if (!keys.length || keys.includes(key)) {
        lex_body.innerHTML +=
        `<div class='lex-entry' id=${key}><i>${key}</i>\n<p class='pronunciation'>${lexicon[key][0]}</p>${lexicon[key][1]}</div>\n`;
        let entry = document.getElementById(key)
        entry.addEventListener('click', edit_entry.bind(this, key) );
        }
    });
}

Current state of the relevant code above. If somebody knows the issue, it'd be very helpful.
If it's relevant, this code is running via Electron (17.0.0).

An attempted solution, using an anonymous arrow function instead of a bind:

entry.addEventListener('click', () => edit_entry(key) );

yields the same result.

Update:
Changing the .innerHTML attribute of something apparently strips all event listeners. So the solution was simply to create the element completely in js, add it to the container, and then add the listener. This change to the forEach loop solves the problem:

    sorted_keys.forEach((key) => {
        if (!keys.length || keys.includes(key)) {
            let entry = document.createElement('div');
            entry.className = 'lex-entry';

            let word = document.createElement('p');
            word.appendChild( document.createTextNode(key) );
            word.style.fontStyle = 'italic';

            let pron = document.createElement('p');
            pron.className = 'pronunciation';
            pron.appendChild( document.createTextNode(lexicon[key][0]) );

            let defn = document.createTextNode(lexicon[key][1]);

            entry.append(word, pron, defn);
            entry.addEventListener('click', () => edit_entry(key) );

            lex_body.appendChild(entry);


问:
Pyspark: Row count is not matching to the count of records appended
I am trying to identify and insert only the delta records to the target hive table from pyspark program. I am using left anti join on ID columns and it's able to identify the new records successfully. But I could notice that the total number of delta records is not the same as the difference between table record count before load and afterload.

```<code>delta_df = src_df.join(tgt_df, src_df.JOIN_HASH == tgt_df.JOIN_HASH,how='leftanti')\
            .select(src_df.columns).drop("JOIN_HASH")
delta_df.count() #giving out correct delta count
delta_df.write.mode("append").format("hive").option("compression","snappy").saveAsTable(hivetable)
</code>```

But if I could see delta_df.count() is not the same as count( * ) from hivetable after writting data - count(*) from hivetable before writting data. The difference is always coming higher compared to the delta count.

I have a unique timestamp column for each load in the source, and to my surprise, the count of records in the target for the current load(grouping by unique timestamp) is less than the delta count.

I am not able to identify the issue here, do I have to write the df.write in some other way?

答:
It was a problem with the line delimiter. When the table is created with spark.write, in SERDEPROPERTIES there is no line.delim specified and column values with * were getting split into multiple rows.

Now I added the below SERDEPROPERTIES and it stores the data correctly.

'line.delim'='\n'

Body:
I am trying to identify and insert only the delta records to the target hive table from pyspark program. I am using left anti join on ID columns and it's able to identify the new records successfully. But I could notice that the total number of delta records is not the same as the difference between table record count before load and afterload.

delta_df = src_df.join(tgt_df, src_df.JOIN_HASH == tgt_df.JOIN_HASH,how='leftanti')\
            .select(src_df.columns).drop("JOIN_HASH")
delta_df.count() #giving out correct delta count
delta_df.write.mode("append").format("hive").option("compression","snappy").saveAsTable(hivetable)

But if I could see delta_df.count() is not the same as count( * ) from hivetable after writting data - count(*) from hivetable before writting data. The difference is always coming higher compared to the delta count.

I have a unique timestamp column for each load in the source, and to my surprise, the count of records in the target for the current load(grouping by unique timestamp) is less than the delta count.

I am not able to identify the issue here, do I have to write the df.write in some other way?


问:
How to optimize CSS styles?
I need to optimize CSS styles using property cursor: pointer just one time. But there are different rules for different cases. How I can do it? Please, do you have any ideas, guys?</p>
```<code>    .product {
  &.grid .grid-product__text:not(._price),

  &.grid .grid-product__text._price,

  &.grid .grid-product__text .grid-product__text_inner {
    color: inherit !important;
  }

  &._photo-name-transition {
    ._name,
    ._image {
      cursor: pointer;
    }
  }

  &._name-transition {
    ._name {
      cursor: pointer;
    }
  }

  &._photo-transition {
    ._image {
      cursor: pointer;
    }
  }
}
</code>```

答:
If I understand you correctly, you can use the selector [class$="foo"] that will select every item that have a class finishing by "foo".

So, in your case, this is the global idea.

```<code>&[class$="-transition"] {
    ._name,
    ._image {
        cursor: pointer;
    }
}
</code>```

If you understand the selector I pointed you, you should be able to optimize your code if my solution isn't exactly right, good luck!

More info here : https://www.w3schools.com/cssref/sel_attr_end.asp

Title: How to optimize CSS styles?

Body:
I need to optimize CSS styles using property cursor: pointer just one time. But there are different rules for different cases. How I can do it? Please, do you have any ideas, guys?

    .product {
  &.grid .grid-product__text:not(._price),

  &.grid .grid-product__text._price,

  &.grid .grid-product__text .grid-product__text_inner {
    color: inherit !important;
  }

  &._photo-name-transition {
    ._name,
    ._image {
      cursor: pointer;
    }
  }

  &._name-transition {
    ._name {
      cursor: pointer;
    }
  }

  &._photo-transition {
    ._image {
      cursor: pointer;
    }
  }
}

Body:
If I understand you correctly, you can use the selector [class$="foo"] that will select every item that have a class finishing by "foo".

So, in your case, this is the global idea.

&[class$="-transition"] {
    ._name,
    ._image {
        cursor: pointer;
    }
}

If you understand the selector I pointed you, you should be able to optimize your code if my solution isn't exactly right, good luck!

More info here : https://www.w3schools.com/cssref/sel_attr_end.asp


问:
Increment a counter inside a byte array
I have an array of 5 bytes (fixed length). First 21 bits represent a counter and the rest 19 some id. I need to increment the counter by one. How do I do that?</p>

答:
This answer is based on the memory layout as I understand it from the OP's comments:

```<code>array[0]: bits 0..7 are counter bits 0..7 (lsb)
array[1]: bits 0..7 are counter bits 8..15
array[2]: bits 0..4 are counter bits 16..20 (msb)
          bits 5..7 are part of the id
array[3]: bits 0..7 are part of the id
array[3]: bits 0..7 are part of the id
</code>```

Then

```<code>int byte0 = (int) array[0] & 0xff;
int byte1 = (int) array[1] & 0xff;
int byte2 = (int) array[2] & 0x1f;

int count = byte0 | (byte1 << 8) | (byte2 << 16);

count = (count+1) & 0x1fffff;

array[0] = (byte) (count & 0x0000ff);
array[1] = (byte) ((count & 0x00ff00) >> 8);
array[2] = (array[2] & 0xe0) | (byte) ((count & 0x1f0000) >> 16);
</code>```

should do the trick.

Title: Increment a counter inside a byte array

Body:
This answer is based on the memory layout as I understand it from the OP's comments:

array[0]: bits 0..7 are counter bits 0..7 (lsb)
array[1]: bits 0..7 are counter bits 8..15
array[2]: bits 0..4 are counter bits 16..20 (msb)
          bits 5..7 are part of the id
array[3]: bits 0..7 are part of the id
array[3]: bits 0..7 are part of the id

Then

int byte0 = (int) array[0] & 0xff;
int byte1 = (int) array[1] & 0xff;
int byte2 = (int) array[2] & 0x1f;

int count = byte0 | (byte1 << 8) | (byte2 << 16);

count = (count+1) & 0x1fffff;

array[0] = (byte) (count & 0x0000ff);
array[1] = (byte) ((count & 0x00ff00) >> 8);
array[2] = (array[2] & 0xe0) | (byte) ((count & 0x1f0000) >> 16);

should do the trick.


问:
Install shell extension conditionally
Reference: Integrate a packaged desktop app with File Explorer
https://learn.microsoft.com/en-us/windows/apps/desktop/modernize/integrate-packaged-app-with-file-explorer

I now know how to install a shell extension custom menu item in the File Explorer for my win32 packaged desktop app. But I want to give a choice to the user whether he really wants the shell extension. Is there a way to do that in Appx manifest?

答:
Microsoft removed the option to customize the install GUI of an MSIX, this means you cannot create a custom option where your users choose if they want the shell extension or not.

Therefore, the appxmanifest schema does not support the conditional installation of the shell extension, from what I know of.

Microsoft recommends moving all options configurations inside your application, including EULA and license registration procedures. So, theoretically you could try to add the shell registration from your application - I never tried this but maybe the links above from Simon Mourier will help.

Title: Install shell extension conditionally


问:
How to modify Vuetify's auto-generated CSS
What I'm Using

Vuetify 2.5.6

The Problem

I'm trying to disable an odious scroll bar

But can't quite figure out how to destroy it (and its ilk). Every suggestion I've tried still yields a Vuetify auto-generated class "v-navigation-drawer__content" that has overflow-y: auto;.

I'd like to learn how to modify the default behavior of these Vuetify-generated CSS files (for this issue and for future ones).

What I've Tried

I've tried:

adding style="overflow: hidden;" to the v-navigation-bar tag.

modifying adding .v-navigation-drawer__content { overflow: hidden !important } to the style section in the view component.

adding the following CSS and also adding mounted() and destroyed() hooks from this answer

Minimal Reproducible Example

```<code><template>
    <v-navigation-drawer
        app
        clipped
        class="side-nav-bar"
        permanent>
        <v-menu
            bottom
            offset-y>
            <template v-slot:activator="{ on, attrs }">

                <v-list-item
                    two-line
                    v-bind="attrs"
                    v-on="on">
                    <v-list-item-avatar>
                        <v-img src="https://randomuser.me/api/portraits/women/85.jpg"></v-img>
                    </v-list-item-avatar>
                    <v-list-item-content>
                        <v-list-item-title class="text-h6">Sandra Adams</v-list-item-title>
                        <v-list-item-subtitle>sandra_a88@gmail.com</v-list-item-subtitle>
                    </v-list-item-content>
                </v-list-item>

            </template>
            <v-list>
                <v-list-item
                    v-for="(workspace, i) in workspaces"
                    :key="i"
                    @click="changeWorkspaces(workspace)">
                    <v-list-item-title>{{ workspace.title  }}</v-list-item-title>
                </v-list-item>
                <v-divider />
                <v-list-item
                    @click="createNewWorkspace">
                    <v-list-item-title>Create Workspace</v-list-item-title>
                </v-list-item>
            </v-list>
        </v-menu>

        <v-divider />

        <v-list
            nav
            dense
            v-for="(item, i) in sideNavOptions"
            :key="i">

                <v-list-item
                    v-if="!item.subList"
                    :key="item.title"
                    :to="item.link">
                    <v-list-item-icon>
                        <v-icon>{{ item.icon }}</v-icon>
                    </v-list-item-icon>
                    <v-list-item-title class="title-bold">{{ item.title }}</v-list-item-title>
                </v-list-item>

                <v-list-group
                    v-else
                    :key="item.title"
                    :prepend-icon="item.icon"
                    no-action>
                    <template v-slot:activator>
                        <v-list-item>
                            <v-list-item-content>
                                <v-list-item-title class="title-bold">{{ item.title }}</v-list-item-title>
                            </v-list-item-content>
                        </v-list-item>
                    </template>
                    <v-list-item
                        v-for="sublist in item.subList"
                        :to="sublist.link"
                        :key="sublist.title">
                        <v-list-item-title>{{ sublist.title }}</v-list-item-title>
                    </v-list-item>
                </v-list-group>

        </v-list>
    </v-navigation-drawer>
</template>

<script>
export default {
    name: "SideNavBar",
    data() {
        return {
            workspaces: [],
            sideNavOptions:[
                { title: "Dashboard", icon: "mdi-monitor-dashboard", link: "/dashboard" },
                {
                    title: "Workflow",
                    icon: "mdi-cog",
                    subList: [
                        { title: "Inbox", link: "/workflows/inbox" },
                        { title: "Action Required", link: "/workflows/action_required" },
                        { title: "Waiting for Others", link: "/workflows/waiting_for_others" },
                        { title: "Approved", link: "/workflows/approved" },
                        { title: "Sent", link: "/workflows/sent" },
                        { title: "Completed", link: "/workflows/completed" },
                    ]
                },
                {
                    title: "Templates",
                    icon: "mdi-cog",
                    subList: [
                        { title: "Placeholder", link: "/templates/placeholder" }
                    ]
                },
                {
                    title: "Contacts",
                    icon: "mdi-cog",
                    subList: [
                        { title: "Placeholder", link: "/contacts/placeholder" }
                    ]
                },
                {
                    title: "Settings",
                    icon: "mdi-cog",
                    subList: [
                        { title: "Workspace Settings", link: "/settings/workspace" },
                        { title: "Company Settings", link: "/settings/company" },
                        { title: "Department Settings", link: "/settings/department" }
                    ]
                },
                { title: "Reminders", icon: "mdi-cog", link: "/reminders" }
            ]
        }
    },
    async beforeMount() {
        await this.getUserWorkspaces()
    },
    methods: {
        changeWorkspaces(workspace) {
            console.log(workspace)
        },
        createNewWorkspace() {
            console.log("Creating new workspace")
        },
        async getUserWorkspaces() {
            console.log("Getting user workspaces")
            this.workspaces = [ { title: "Placeholder_1" }, { title: "Placeholder_2" } ]
        }
    }
}
</script>

<style lang="sass" scoped>
.side-nav-bar {
    overflow: hidden !important;
    color: $white !important;
    background: $light_gray !important;
}

.v-navigation-drawer.v-navigation-drawer__content {
    overflow: hidden !important;
}
</style>
</code>```

Thanks in advance for any help!

Body:
What I'm Using

Vuetify 2.5.6

The Problem

I'm trying to disable an odious scroll bar

But can't quite figure out how to destroy it (and its ilk). Every suggestion I've tried still yields a Vuetify auto-generated class "v-navigation-drawer__content" that has overflow-y: auto;.

I'd like to learn how to modify the default behavior of these Vuetify-generated CSS files (for this issue and for future ones).

What I've Tried

I've tried:

adding style="overflow: hidden;" to the v-navigation-bar tag.

modifying adding .v-navigation-drawer__content { overflow: hidden !important } to the style section in the view component.

adding the following CSS and also adding mounted() and destroyed() hooks from this answer

Minimal Reproducible Example

<template>
    <v-navigation-drawer
        app
        clipped
        class="side-nav-bar"
        permanent>
        <v-menu
            bottom
            offset-y>
            <template v-slot:activator="{ on, attrs }">

                <v-list-item
                    two-line
                    v-bind="attrs"
                    v-on="on">
                    <v-list-item-avatar>
                        <v-img src="https://randomuser.me/api/portraits/women/85.jpg"></v-img>
                    </v-list-item-avatar>
                    <v-list-item-content>
                        <v-list-item-title class="text-h6">Sandra Adams</v-list-item-title>
                        <v-list-item-subtitle>sandra_a88@gmail.com</v-list-item-subtitle>
                    </v-list-item-content>
                </v-list-item>

            </template>
            <v-list>
                <v-list-item
                    v-for="(workspace, i) in workspaces"
                    :key="i"
                    @click="changeWorkspaces(workspace)">
                    <v-list-item-title>{{ workspace.title  }}</v-list-item-title>
                </v-list-item>
                <v-divider />
                <v-list-item
                    @click="createNewWorkspace">
                    <v-list-item-title>Create Workspace</v-list-item-title>
                </v-list-item>
            </v-list>
        </v-menu>

        <v-divider />

        <v-list
            nav
            dense
            v-for="(item, i) in sideNavOptions"
            :key="i">

                <v-list-item
                    v-if="!item.subList"
                    :key="item.title"
                    :to="item.link">
                    <v-list-item-icon>
                        <v-icon>{{ item.icon }}</v-icon>
                    </v-list-item-icon>
                    <v-list-item-title class="title-bold">{{ item.title }}</v-list-item-title>
                </v-list-item>

                <v-list-group
                    v-else
                    :key="item.title"
                    :prepend-icon="item.icon"
                    no-action>
                    <template v-slot:activator>
                        <v-list-item>
                            <v-list-item-content>
                                <v-list-item-title class="title-bold">{{ item.title }}</v-list-item-title>
                            </v-list-item-content>
                        </v-list-item>
                    </template>
                    <v-list-item
                        v-for="sublist in item.subList"
                        :to="sublist.link"
                        :key="sublist.title">
                        <v-list-item-title>{{ sublist.title }}</v-list-item-title>
                    </v-list-item>
                </v-list-group>

        </v-list>
    </v-navigation-drawer>
</template>

Thanks in advance for any help!

Body:
Adding .v-navigation-drawer__content { overflow: hidden !important } should work but it's not working, because you are trying to change the style of a component which not a part of your current component using scoped css.

Try to remove scoped from your <style> and it will work. I usually create a global stylesheet and add it in App.vue file and make changes in that file.

Read more here about the scoped feature.


问:
Type hinting for a function wrapping another function, accepting the same arguments
```<code>def function(a: int, b: str) -> None:
    pass

def wrapper(extra: int, *args, **kwargs) -> None:
    do_something_with_extra(extra)
    function(*args, **kwargs)
</code>```

Is there an easy way for wrapper to inherit function()'s type hints without retyping all of them?
Normally I'd write

```<code>def wrapper(extra: int, a: int, b: str) -> None:
</code>```

But it becomes very verbose with a lot of arguments, and I have to update wrapper() every time I update function()'s arguments, and using *args, **kwargs means there won't be proper autocomplete in vscode and other editors.

答:
The best that you can do is to use a decorator for this purpose, and you can use Concatenate and ParamSpec. I use python 3.8 and I had to install typing_extensions for them.
In the code below, if you type function in VSCode, it will show the int argument but without the "extra" name in front of it.

```<code>from typing import Callable, TypeVar
from typing_extensions import Concatenate, ParamSpec

P = ParamSpec('P')
R = TypeVar('R')

def wrapper(func: Callable[P, R]) -> Callable[Concatenate[int, P], R]:
    def inner(extra, *args, **kwargs):
        print(extra)
        func(*args, **kwargs)

    return inner

@wrapper
def function(a: int, b: str) -> None:
    print(a, b)
    pass

# typing function will show 'function: (int, a: int, b: str) -> None'
</code>```

Body:
def function(a: int, b: str) -> None:
    pass

def wrapper(extra: int, *args, **kwargs) -> None:
    do_something_with_extra(extra)
    function(*args, **kwargs)

Is there an easy way for wrapper to inherit function()'s type hints without retyping all of them?
Normally I'd write

def wrapper(extra: int, a: int, b: str) -> None:

But it becomes very verbose with a lot of arguments, and I have to update wrapper() every time I update function()'s arguments, and using *args, **kwargs means there won't be proper autocomplete in vscode and other editors.

Body:
The best that you can do is to use a decorator for this purpose, and you can use Concatenate and ParamSpec. I use python 3.8 and I had to install typing_extensions for them.
In the code below, if you type function in VSCode, it will show the int argument but without the "extra" name in front of it.

from typing import Callable, TypeVar
from typing_extensions import Concatenate, ParamSpec

P = ParamSpec('P')
R = TypeVar('R')

def wrapper(func: Callable[P, R]) -> Callable[Concatenate[int, P], R]:
    def inner(extra, *args, **kwargs):
        print(extra)
        func(*args, **kwargs)

    return inner

@wrapper
def function(a: int, b: str) -> None:
    print(a, b)
    pass

# typing function will show 'function: (int, a: int, b: str) -> None'


问:
ORACLE - Exporting Procedures / Packages to a file
I would like to programmatically  export my Procedures / Functions and Packages into individual files (as a backup) and using Oracle 9.2.

The closest solution i found was using DBMS_METADATA.GET_DDL , but how do i output the CLOB to a text file, without losing any parts (due to length or indentation) ?

Or maybe do you have other  solutions to backup packages or other functions individually (only the one i want, not all of them) ?

Thanks

答:
If you want to get the DDL, there really is no way except DBMS_METADATA like you already said.

Usually, this kind of a backup is done with exp (or expdp), although this doesn't create a SQL file like you would get with most other DBMS systems.

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: andri


问:
WPF: Label doesn't show up in code behind
Ok, so I've been looking all over for a anwser, but I starting to wonder if I would even know it if I saw it. I'm new to WPF, but have been doing Windows Forms in C# for a few years now.

My Question is: Why can't I access a label from the code behind that I "dragged-n-dropped" on to the grid and renamed?

XML CODE:

```<code><Window x:Class="IMCommand.NewProblemWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="New Problem" Height="800" Width="800" Loaded="Window_Loaded">
    <Grid>
        <GroupBox Header="Initial Detection and Recording" Height="168" HorizontalAlignment="Left" Margin="12,45,0,0" Name="groupBox1" VerticalAlignment="Top" Width="754" FontSize="15">
            <Grid>
                <Label Content="Application/Server" Height="28" HorizontalAlignment="Left" Margin="6,6,0,0" Name="label1" VerticalAlignment="Top" />
                <TextBox Height="23" HorizontalAlignment="Left" Margin="144,11,0,0" Name="textBox1" VerticalAlignment="Top" Width="324" Background="#FFCBCBCB"></TextBox>

                <Label Content="AE Problem Ticket #" Height="28" HorizontalAlignment="Left" Margin="6,52,0,0" Name="label2" VerticalAlignment="Top" />
                <TextBox Background="#FFCBCBCB" Height="23" HorizontalAlignment="Left" Margin="155,54,0,0" Name="BOX_AEProblem" VerticalAlignment="Top" Width="175" />

                <Label Content="Start Time" Height="28" HorizontalAlignment="Left" Margin="6,86,0,0" Name="label4" VerticalAlignment="Top" Width="85" />
                <TextBox Height="23" HorizontalAlignment="Left" Margin="97,91,0,0" Name="BOX_StartTime" VerticalAlignment="Top" Width="118" IsReadOnly="True" />

                <Label Content="Label" Height="28" HorizontalAlignment="Left" Margin="221,89,0,0" Name="LBL_StartTimeConvert" VerticalAlignment="Top" Width="128" />
            </Grid>
        </GroupBox>

        <GroupBox Header="Classification and Initial Support" Height="333" HorizontalAlignment="Left" Margin="12,260,0,0" Name="groupBox2" VerticalAlignment="Top" Width="754" FontSize="15">
            <Grid>
                <Label Content="Description" Height="28" HorizontalAlignment="Left" Margin="6,96,0,0" Name="LBL_Description" VerticalAlignment="Top" />
                <RichTextBox Height="137" HorizontalAlignment="Left" Margin="97,96,0,0" Name="richTextBox1" VerticalAlignment="Top" Width="590" Background="#FFCBCBCB" Cursor="IBeam" ToolTip="Describe the problem..." VerticalScrollBarVisibility="Visible" SpellCheck.IsEnabled="True" FontSize="12" BorderBrush="#FF151414" />
                <RichTextBox Height="28" HorizontalAlignment="Left" Margin="97,44,0,0" Name="richTextBox2" VerticalAlignment="Top" Width="590" Background="#FFCBCBCB" />
                <Label Content="Summary" Height="28" HorizontalAlignment="Left" Margin="6,44,0,0" Name="label3" VerticalAlignment="Top" />
            </Grid>
        </GroupBox>
    </Grid>
</Window>
</code>```

The particular label I'm refereing to is the last label in the first GroupBox named "LBL_StartTimeConvert"

```<code><Label Content="Label" Height="28" HorizontalAlignment="Left" Margin="221,89,0,0" Name="LBL_StartTimeConvert" VerticalAlignment="Top" Width="128" />
</code>```

When I go into the Code behind file, I am unable to get "LBL_StartTimeConvert" to show up in intellisense. How do I access this label from the C# code? I need to change the labels text. Thanks!

PS>> Any good resources/books that you can point me to on learning WPF (like WPF 101 or WPF for Dummies) would be much appreciated!

答:
You should use x:Name instead of Name

"x:Name: Specifies a run-time object name for the instance that exists in run-time code after an object element is processed. In general, you will frequently use a WPF-defined equivalent property for x:Name. Such properties map specifically to a CLR backing property and are thus more convenient for application programming, where you frequently use run time code to find the named elements from initialized XAML."

See XAML overview Here

Body:
Ok, so I've been looking all over for a anwser, but I starting to wonder if I would even know it if I saw it. I'm new to WPF, but have been doing Windows Forms in C# for a few years now.

My Question is: Why can't I access a label from the code behind that I "dragged-n-dropped" on to the grid and renamed?

XML CODE:

<Window x:Class="IMCommand.NewProblemWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="New Problem" Height="800" Width="800" Loaded="Window_Loaded">
    <Grid>
        <GroupBox Header="Initial Detection and Recording" Height="168" HorizontalAlignment="Left" Margin="12,45,0,0" Name="groupBox1" VerticalAlignment="Top" Width="754" FontSize="15">
            <Grid>

                <TextBox Height="23" HorizontalAlignment="Left" Margin="144,11,0,0" Name="textBox1" VerticalAlignment="Top" Width="324" Background="#FFCBCBCB"></TextBox>

                <TextBox Background="#FFCBCBCB" Height="23" HorizontalAlignment="Left" Margin="155,54,0,0" Name="BOX_AEProblem" VerticalAlignment="Top" Width="175" />

                <TextBox Height="23" HorizontalAlignment="Left" Margin="97,91,0,0" Name="BOX_StartTime" VerticalAlignment="Top" Width="118" IsReadOnly="True" />

            </Grid>
        </GroupBox>

        <GroupBox Header="Classification and Initial Support" Height="333" HorizontalAlignment="Left" Margin="12,260,0,0" Name="groupBox2" VerticalAlignment="Top" Width="754" FontSize="15">
            <Grid>

                <RichTextBox Height="137" HorizontalAlignment="Left" Margin="97,96,0,0" Name="richTextBox1" VerticalAlignment="Top" Width="590" Background="#FFCBCBCB" Cursor="IBeam" ToolTip="Describe the problem..." VerticalScrollBarVisibility="Visible" SpellCheck.IsEnabled="True" FontSize="12" BorderBrush="#FF151414" />
                <RichTextBox Height="28" HorizontalAlignment="Left" Margin="97,44,0,0" Name="richTextBox2" VerticalAlignment="Top" Width="590" Background="#FFCBCBCB" />

            </Grid>
        </GroupBox>
    </Grid>
</Window>

The particular label I'm refereing to is the last label in the first GroupBox named "LBL_StartTimeConvert"

When I go into the Code behind file, I am unable to get "LBL_StartTimeConvert" to show up in intellisense. How do I access this label from the C# code? I need to change the labels text. Thanks!

PS>> Any good resources/books that you can point me to on learning WPF (like WPF 101 or WPF for Dummies) would be much appreciated!


问:
Visual Studio show an error about PrismApplication
Now and then I get XamlC error XFC0000 : Cannot resolve type "PrismApplication" in the error list of my shared xamarin project. The error is from App.xaml and no squiggly is shown in that file, but the error is shown in the error list. Sometimes it goes away if a restart visual studio. I'm running Prism.Unity.Forms v7.2.0.1422.
I shoud mention that my android project still builds when the error is shown, but it's annoying and I like to know how to remove it?
Maybe it can be done like something like suppressing the error about Ambiguity between 'Resource.Layout.Tabbar' and 'Resource.Layout.Tabbar.</p>

答:
I am using Prism with DryIoc (and not unity). Following a suggestion from another thread I replaced

xmlns:prism="http://prismlibrary.com"

with

xmlns:prism="clr-namespace:Prism.DryIoc;assembly=Prism.DryIoc.Forms"

in my App.xaml file and the error disappeared.

I had the same error with PopupPage from Rg.Plugins.Popup, so I also replaced

xmlns:pages="http://rotorgames.com"

with

xmlns:pages="clr-namespace:Rg.Plugins.Popup.Pages;assembly=Rg.Plugins.Popup"

and that error disappeared as well.

As these are two different libraries, acting similarly, it might be a general VS issue. But could also be the same error in two libraries.

Another thread lead me to this article which basically says that using a custom namespace requires a direct reference to the assembly through C# code in order for VS to find it and not show this error.


问:
Is it possible to remove a file from git commit history in a protected branch?
I accidentally committed a private file to a protected branch and already deleted it but I can't clear it from my history. Because the branch is protected by someone that isn't me, I can't force push. I have tried using BFG repo-cleaner. Should I accept this commit will be in my history permanently?</p>

答:
Despite non-fast forward pushes is forbidden, it is possible that you still have permissions to remove the whole branch from a remote repository. So, you can remove the branch and then push a new brunch with the same name but without problematic commits.

If branch removal is also forbidden, you can't do anything yourself and the only way is to contact someone who have appropriate permissions to enable non-fast forward pushes or remove branch (e.g. repository owner/admin/etc)


问:
What is the path of the Json file in Android at Xamarin.Forms?

I am developing an application for Android using Xamarin.
I have created a JsonData folder in the Android project and created a Setting.json file.

```<code>\MyApp\MyApp.Android\JsonData\Setting.json
</code>```

In the properties, we set the Copy when new.
The following folders in the local environment contain the files.

```<code>\MyApp\MyApp.Android\bin\Debug\JsonData\Setting.json
</code>```

I want to load this file in the actual Android device.
When I do this, it tells me that the file is missing.

```<code>Could not find a part of the path "/JsonData/Setting.json."
</code>```
```<code>Try
{
    var text = File.ReadAllText("JsonData/Setting.json", Encoding.UTF8);
    var setting = JsonConvert.DeserializeObject<Setting>(text);
}
catch(Exception exception)
{
    var error = exception.Message;
}
</code>```

What is the path of the file in Android?

答:
I think you're using File Handling in Xamarin.Forms incorrectly.

From the parameter of function File.ReadAllText, the app  will  access the file system to getSetting.json  from folder JsonData in your android device.

The path of the file on each platform can be determined from a .NET Standard library by using a value of the Environment.SpecialFolder enumeration as the first argument to the Environment.GetFolderPath method. This can then be combined with a filename with the Path.Combine method:

```<code>string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "temp.txt");
</code>```

And you can read the file by  code:

```<code>string text = File.ReadAllText(fileName);
</code>```

In addition, from your code,I guess you want to Load your Embedded file( Setting.json)  as Resources,right?

In this case,we should make sure the Build Action of your Setting.json is Embedded Resource.

And GetManifestResourceStream is used to access the embedded file using its Resource ID.

You can refer to the following code:

```<code>var assembly = IntrospectionExtensions.GetTypeInfo(typeof(LoadResourceText)).Assembly;
Stream stream = assembly.GetManifestResourceStream("YourAppName.JsonData.Setting.json");
string text = "";
using (var reader = new System.IO.StreamReader (stream))
{
    text = reader.ReadToEnd ();
}
</code>```

For more , you can check document : File Handling in Xamarin.Forms.

And you can also check the sample code here: https://learn.microsoft.com/en-us/samples/xamarin/xamarin-forms-samples/workingwithfiles/ .

Body:
I am developing an application for Android using Xamarin.
I have created a JsonData folder in the Android project and created a Setting.json file.

\MyApp\MyApp.Android\JsonData\Setting.json

In the properties, we set the Copy when new.
The following folders in the local environment contain the files.

\MyApp\MyApp.Android\bin\Debug\JsonData\Setting.json

I want to load this file in the actual Android device.
When I do this, it tells me that the file is missing.

Could not find a part of the path "/JsonData/Setting.json."

Try
{
    var text = File.ReadAllText("JsonData/Setting.json", Encoding.UTF8);
    var setting = JsonConvert.DeserializeObject<Setting>(text);
}
catch(Exception exception)
{
    var error = exception.Message;
}

What is the path of the file in Android?

Body:
I think you're using File Handling in Xamarin.Forms incorrectly.

From the parameter of function File.ReadAllText, the app  will  access the file system to getSetting.json  from folder JsonData in your android device.

The path of the file on each platform can be determined from a .NET Standard library by using a value of the Environment.SpecialFolder enumeration as the first argument to the Environment.GetFolderPath method. This can then be combined with a filename with the Path.Combine method:

string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "temp.txt");

And you can read the file by  code:

string text = File.ReadAllText(fileName);

In addition, from your code,I guess you want to Load your Embedded file( Setting.json)  as Resources,right?

In this case,we should make sure the Build Action of your Setting.json is Embedded Resource.

And GetManifestResourceStream is used to access the embedded file using its Resource ID.

You can refer to the following code:

var assembly = IntrospectionExtensions.GetTypeInfo(typeof(LoadResourceText)).Assembly;
Stream stream = assembly.GetManifestResourceStream("YourAppName.JsonData.Setting.json");
string text = "";
using (var reader = new System.IO.StreamReader (stream))
{
    text = reader.ReadToEnd ();
}

For more , you can check document : File Handling in Xamarin.Forms.

And you can also check the sample code here: https://learn.microsoft.com/en-us/samples/xamarin/xamarin-forms-samples/workingwithfiles/ .


问:
How can I write a `try`/`except` block that catches all exceptions?
How can I write a try/except block that catches all exceptions?

答:
First of all, there are exceptions that you want them to break your code (as when this error happens your code will not function anyways!) and exceptions you want to capture silently/smoothly. Try differentiating them. You may not want to capture all exceptions there are!

Second, instead of capturing everything, you could take the time and go through the logs of your process. Let's say you are getting a different/third-party exception, for example from a cloud service provider like GCP. In the logs, you could find the exception you are getting. Then, you could do something like this:

```<code>from google.api_core.exceptions import ServiceUnavailable, RetryError

for i in range(10):
   try:
      print("do something")

   except ValueError:
      print("I know this might happen for now at times! skipping this and continuing with my loop"

   except ServiceUnavailable:
      print("our connection to a service (e.g. logging) of gcp has failed")
      print("initializing the cloud logger again and try continuing ...")

   except RetryError:
      print("gcp connection retry failed. breaking the loop. try again later!)
      break
</code>```

For the rest (errors that might or might not happen), I am leaving room for my code to crash if I get an unexpected exception! This way I could understand what is going on and improve my code by capturing edge cases.

If you want this to never crash for some reason, for example if it is a code embedded in a remote hardware that you cannot easily access, you can add a generic exception catcher at the end:

```<code>except Exception as e:
   print(f"something went wrong! - {e}")
</code>```

You can also take a look at Python 3 exception hierarchy here. The difference between Exception and BaseException is that, Exception will not catch SystemExit, KeyboardInterrupt, or GeneratorExit

Body:
First of all, there are exceptions that you want them to break your code (as when this error happens your code will not function anyways!) and exceptions you want to capture silently/smoothly. Try differentiating them. You may not want to capture all exceptions there are!

Second, instead of capturing everything, you could take the time and go through the logs of your process. Let's say you are getting a different/third-party exception, for example from a cloud service provider like GCP. In the logs, you could find the exception you are getting. Then, you could do something like this:

from google.api_core.exceptions import ServiceUnavailable, RetryError

for i in range(10):
   try:
      print("do something")

   except ValueError:
      print("I know this might happen for now at times! skipping this and continuing with my loop"

   except ServiceUnavailable:
      print("our connection to a service (e.g. logging) of gcp has failed")
      print("initializing the cloud logger again and try continuing ...")

   except RetryError:
      print("gcp connection retry failed. breaking the loop. try again later!)
      break

For the rest (errors that might or might not happen), I am leaving room for my code to crash if I get an unexpected exception! This way I could understand what is going on and improve my code by capturing edge cases.

If you want this to never crash for some reason, for example if it is a code embedded in a remote hardware that you cannot easily access, you can add a generic exception catcher at the end:

except Exception as e:
   print(f"something went wrong! - {e}")

You can also take a look at Python 3 exception hierarchy here. The difference between Exception and BaseException is that, Exception will not catch SystemExit, KeyboardInterrupt, or GeneratorExit


问:
Orientation on Jetpack Compose
Is there any Orientation helpers class in Jetpack Compose, like Flutter has https://flutter.dev/docs/cookbook/design/orientation ??
I need to know when orientation have been changed to adjust my layout properly.</p>

答:
Here's a little helper for swapping a compose row into a column when turning to portrait-mode. You may want to tweak it a bit for your purposes.

```<code>@Composable
fun OrientationSwapper(
    content1: @Composable (modifier: Modifier) -> Unit,
    content2: @Composable (modifier: Modifier) -> Unit
) {
    val portrait = LocalConfiguration.current.orientation == Configuration.ORIENTATION_PORTRAIT
    if (portrait) {
        Column(verticalArrangement = Arrangement.SpaceEvenly, modifier = Modifier.fillMaxSize()) {
            content1(modifier = Modifier.weight(1f))
            content2(modifier = Modifier.weight(1f))
        }
    } else {
        Row(horizontalArrangement = Arrangement.SpaceEvenly, modifier = Modifier.fillMaxSize()) {
            content1(modifier = Modifier.weight(1f))
            content2(modifier = Modifier.weight(1f))
        }
    }
}
</code>```

and use as:

```<code>    OrientationSwapper(
        content1 = { modifier ->
            Text("foo", modifier = modifier) },
        content2 = {  modifier ->
            Text("bar", modifier = modifier) })
</code>```

Title: Orientation on Jetpack Compose

Body:
Here's a little helper for swapping a compose row into a column when turning to portrait-mode. You may want to tweak it a bit for your purposes.

@Composable
fun OrientationSwapper(
    content1: @Composable (modifier: Modifier) -> Unit,
    content2: @Composable (modifier: Modifier) -> Unit
) {
    val portrait = LocalConfiguration.current.orientation == Configuration.ORIENTATION_PORTRAIT
    if (portrait) {
        Column(verticalArrangement = Arrangement.SpaceEvenly, modifier = Modifier.fillMaxSize()) {
            content1(modifier = Modifier.weight(1f))
            content2(modifier = Modifier.weight(1f))
        }
    } else {
        Row(horizontalArrangement = Arrangement.SpaceEvenly, modifier = Modifier.fillMaxSize()) {
            content1(modifier = Modifier.weight(1f))
            content2(modifier = Modifier.weight(1f))
        }
    }
}

and use as:

    OrientationSwapper(
        content1 = { modifier ->
            Text("foo", modifier = modifier) },
        content2 = {  modifier ->
            Text("bar", modifier = modifier) })


问:
I am having Issues counting values in a row with separators using SQL
I am new to snowflake and trying the count the number of values in a row with separators using SQL. I am not sure how to go about it. I've googled solutions for this but have not been able to find one.

table name: Lee_tab

user
names

id01
Jon;karl;lee;

id02
Abi;jackson;

id03
don;

id04

what I want to achieve

user
names
name_count

id01
Jon;karl;lee;
3

id02
Abi;jackson;
2

id03
don;
1

id04

0

答:
It depends on which DataBase you're using, because there are some different
things in syntax. I made your example with using SQLite Browser and I have a result like this one:

SELECT SUM(length(names) - length(replace(names, ';', '')) +1)
AS TotalCount
FROM Lee_tab where id = USER ID

As I know, in Postgres there's no length, it's just len there, so, pay an attention.

My query-it's just a formula to how count values, separated by ;
To get your result, you should learn how to join.


问:
I am trying to make an HTTP post, but json returns "message":"Unauthorized"
```<code>import httplib2
import hmac
import hashlib
import time
import sys
import struct
import json

root = "https://api.challenge.hennge.com/challenges/003"
content_type = "application/json"
userid = "toufiqurrahman45@gmail.com"
name = "HENNGECHALLENGE003"
shared_secret = userid+name

timestep = 30
T0 = 0

def HOTP(K, C, digits=10):
    K_bytes = str.encode(K)
    C_bytes = struct.pack(">Q", C)
    hmac_sha512 = hmac.new(key = K_bytes, msg=C_bytes, digestmod=hashlib.sha512).hexdigest()
    return Truncate(hmac_sha512)[-digits:]

def Truncate(hmac_sha512):
    offset = int(hmac_sha512[-1], 16)
    binary = int(hmac_sha512[(offset *2):((offset*2)+8)], 16) & 0x7FFFFFFF
    return str(binary)

def TOTP(K, digits=10, timeref = 0, timestep = 30):
    C = int ( time.time() - timeref ) // timestep
    return HOTP(K, C, digits = digits)

data = { "github_url": "https://gist.github.com/TaufiqurRahman45/f5347e5ba6e7d24aa61ac8c78fda452e", "contact_email": "toufiqurrahman45@gmail.com" }

password = TOTP(shared_secret, 10, T0, timestep).zfill(10)

h = httplib2.Http()
h.add_credentials( userid, password )
header = {"content-type": "application/json"}
resp, content = h.request(root, "POST", headers = header, body = json.dumps(data))
print(resp)
print(content)
</code>```

Authorization

The URL is protected by HTTP Basic Authentication, which is explained on Chapter 2 of RFC2617, so you have to provide an Authorization: header field in your POST request

For the userid of HTTP Basic Authentication, use the same email address you put in the JSON string.
For the password, provide a 10-digit time-based one time password conforming to RFC6238 TOTP.

I generating also password and using hash function HMAC-SHA-512

答:
The URL is protected by HTTP Basic Authentication, which is explained on Chapter 2 >of RFC2617, so you have to provide an Authorization: header field in your POST request
For the userid of HTTP Basic Authentication, use the same email address you put in >the JSON string. For the password, provide a 10-digit time-based one time password >conforming to RFC6238 TOTP.

As mentioned here, you have to provide an Authorization: header field like this:

headers={"Authorization":"OATH TOKEN","content-type": "application/json"}
```

You can get an OATH Token for github from https://github.com/settings/tokens

Body:
import httplib2
import hmac
import hashlib
import time
import sys
import struct
import json

root = "https://api.challenge.hennge.com/challenges/003"
content_type = "application/json"
userid = "toufiqurrahman45@gmail.com"
name = "HENNGECHALLENGE003"
shared_secret = userid+name

timestep = 30
T0 = 0

def HOTP(K, C, digits=10):
    K_bytes = str.encode(K)
    C_bytes = struct.pack(">Q", C)
    hmac_sha512 = hmac.new(key = K_bytes, msg=C_bytes, digestmod=hashlib.sha512).hexdigest()
    return Truncate(hmac_sha512)[-digits:]

def Truncate(hmac_sha512):
    offset = int(hmac_sha512[-1], 16)
    binary = int(hmac_sha512[(offset *2):((offset*2)+8)], 16) & 0x7FFFFFFF
    return str(binary)

def TOTP(K, digits=10, timeref = 0, timestep = 30):
    C = int ( time.time() - timeref ) // timestep
    return HOTP(K, C, digits = digits)

data = { "github_url": "https://gist.github.com/TaufiqurRahman45/f5347e5ba6e7d24aa61ac8c78fda452e", "contact_email": "toufiqurrahman45@gmail.com" }

password = TOTP(shared_secret, 10, T0, timestep).zfill(10)

h = httplib2.Http()
h.add_credentials( userid, password )
header = {"content-type": "application/json"}
resp, content = h.request(root, "POST", headers = header, body = json.dumps(data))
print(resp)
print(content)

Authorization

The URL is protected by HTTP Basic Authentication, which is explained on Chapter 2 of RFC2617, so you have to provide an Authorization: header field in your POST request

For the userid of HTTP Basic Authentication, use the same email address you put in the JSON string.
For the password, provide a 10-digit time-based one time password conforming to RFC6238 TOTP.

I generating also password and using hash function HMAC-SHA-512

Body:
The URL is protected by HTTP Basic Authentication, which is explained on Chapter 2 >of RFC2617, so you have to provide an Authorization: header field in your POST request
For the userid of HTTP Basic Authentication, use the same email address you put in >the JSON string. For the password, provide a 10-digit time-based one time password >conforming to RFC6238 TOTP.

As mentioned here, you have to provide an Authorization: header field like this:

headers={"Authorization":"OATH TOKEN","content-type": "application/json"}

You can get an OATH Token for github from https://github.com/settings/tokens


问:
why I can't keep observable alive after .onError() even I already use error handling like .catchError() onRxSwift?
So, I want to keep the observable keep alive (not disposhed) even after input onError(), so I can input onNext()

I already follow this answer

by adding .catchError() or .catchErrorReturn() but it didn't work like I expected

(nb: I run this code on playground)

```<code>    let bag = DisposeBag()
    let data = PublishSubject<Observable<Int>>()
    data.debug("debug").flatMap({
        $0.map({data in
            return data
        }).catchError({err in
            return Observable.empty()
        })
    }).subscribe(onNext:{
        print($0)
    },onCompleted:{
        print("end")
    }).disposed(by: bag)
    let inputData = PublishSubject<Int>()
    data.onNext(inputData)
    inputData.onNext(1)
    inputData.onNext(2)
    inputData.onError(MyError.anError)
    inputData.onNext(2)

</code>```

actual result I get

```<code>1
2
</code>```

expected result I want

```<code>1
2
2
</code>```

答:
For the best solution, I would suggest using materialize() with compactMap.
take a look at https://michaellong.medium.com/rxswift-better-error-handling-with-compactmap-48a5d314d0f1

Body:
So, I want to keep the observable keep alive (not disposhed) even after input onError(), so I can input onNext()

I already follow this answer

by adding .catchError() or .catchErrorReturn() but it didn't work like I expected

(nb: I run this code on playground)

    let bag = DisposeBag()
    let data = PublishSubject<Observable<Int>>()
    data.debug("debug").flatMap({
        $0.map({data in
            return data
        }).catchError({err in
            return Observable.empty()
        })
    }).subscribe(onNext:{
        print($0)
    },onCompleted:{
        print("end")
    }).disposed(by: bag)
    let inputData = PublishSubject<Int>()
    data.onNext(inputData)
    inputData.onNext(1)
    inputData.onNext(2)
    inputData.onError(MyError.anError)
    inputData.onNext(2)

actual result I get

1
2

expected result I want

1
2
2


问:
CSS Overflow issue in IE
I having problem to make the overflow hidden if the width is over the line
anyone know how to do it?

It does not work for IE at all.

```<code><style type="text/css">
body{
    font-family:Calibri;
    font-size:12pt;
}
table.excel {
    border-collapse:collapse;
    color:#000000;
    font-weight:400;
    font-style:inherit;
    text-align:left;
    vertical-align:bottom;
    border:1px solid #C0C0C0;
}

.datacell {
    border: 1px solid #C0C0C0;
}
</style>

<table class="excel" width="194px">
    <tr>
        <td style="width:30px;"> </td>
        <td style="width:64px;">A</td>
        <td style="width:100px;">B</td>
    </tr>
    <tr>
        <td style="height:50px;">1</td>
        <td class="datacell" style="max-width:64px;">
            <div style="float:left;min-width:160px;white-space: nowrap; overflow: hidden; position:relative;background-color:#FFFFFF;">I like to eat McDonalds double<br>cheese burger, i am lovin it!</div>
        </td>
        <td class="datacell">aa</td>
    </tr>
</table>
</code>```

答:
Add width and height attributes to your overflow-hidden
.

Title: CSS Overflow issue in IE

Body:
I having problem to make the overflow hidden if the width is over the line
anyone know how to do it?

It does not work for IE at all.

        A
        B

        1

I like to eat McDonalds double
cheese burger, i am lovin it!

        aa

Body: Add width and height attributes to your overflow-hidden <div>.


问:
Error when installing Discord Anti Spam package with NPM
I need help with this error its annoying and I did everything I possibly could like updating Discord.js. It seems to still say its not in the registry. Does anyone know what I am doing wrong here or what I am missing?</p>
```<code>npm ERR! 404  'discord-anti-spam-development@^2.4.1' is not in this registry.
npm ERR! 404 You should bug the author to publish it (or use the name yourself!)
</code>```

答:
You might looking for discord-anti-spam package, not discord-anti-spam-development

Install command should be:

```<code>npm install discord-anti-spam
</code>```

Body:
I need help with this error its annoying and I did everything I possibly could like updating Discord.js. It seems to still say its not in the registry. Does anyone know what I am doing wrong here or what I am missing?

npm ERR! 404  'discord-anti-spam-development@^2.4.1' is not in this registry.
npm ERR! 404 You should bug the author to publish it (or use the name yourself!)

Body:
You might looking for discord-anti-spam package, not discord-anti-spam-development

Install command should be:

npm install discord-anti-spam


问:
Pytorch to ONNX: Could not find an implementation for RandomNormalLike
I am trying to convert a fairly complex model from pytorch into ONNX. The conversion succeeds without error, but I am encountering this error when loading the model:

```<code>Traceback (most recent call last):
  File "/home/***/***/***.py", line 50, in <module>
    main()
  File "/home/***/***/***.py", line 38, in main
    ort_session = ort.InferenceSession(onnx_path, providers=[
  File "/home/***/miniconda3/envs/***/lib/python3.9/site-packages/onnxruntime/capi/onnxruntime_inference_collection.py", line 324, in __init__
    self._create_inference_session(providers, provider_options, disabled_optimizers)
  File "/home/***/miniconda3/envs/***/lib/python3.9/site-packages/onnxruntime/capi/onnxruntime_inference_collection.py", line 369, in _create_inference_session
    sess.initialize_session(providers, provider_options, disabled_optimizers)
onnxruntime.capi.onnxruntime_pybind11_state.NotImplemented: [ONNXRuntimeError] : 9 : NOT_IMPLEMENTED : Could not find an implementation for RandomNormalLike(1) node with name 'RandomNormalLike_598'
</code>```

I think that the RandomNormalLike node the error is complaining about might correspond to this module I have:

```<code>class NoiseInjection(nn.Module):
    def __init__(self):
        super().__init__()

        self.weight = nn.Parameter(torch.zeros(1), requires_grad=True)

    def forward(
        self,
        feat: torch.Tensor,
        noise: Optional[torch.Tensor] = None,
    ) -> torch.Tensor:
        if noise is None:
            batch, _, height, width = feat.shape
            noise = torch.randn(
                batch, 1, height, width,
                dtype=feat.dtype,
                device=feat.device,
            )

        return feat + self.weight * noise
</code>```

I also created a different implementation, but it leads to the same error: (edit: This version actually works. I made an unrelated mistake elsewhere that mislead me into thinking it did not work)

```<code>    def forward(
        self,
        feat: torch.Tensor,
        noise: Optional[torch.Tensor] = None,
    ) -> torch.Tensor:
        if noise is None:
            noise = torch.randn_like(feat[:, 0:1])

        return feat + self.weight * noise
</code>```

My pytorch and onnx version are as follows:

```<code>$ conda list torch
# Name                    Version                   Build  Channel
torch                     1.10.0+cu113             pypi_0    pypi
torchaudio                0.10.0+cu113             pypi_0    pypi
torchvision               0.11.1+cu113             pypi_0    pypi

$ conda list onnx
# Name                    Version                   Build  Channel
onnx                      1.10.2                   pypi_0    pypi
onnxruntime-gpu           1.9.0                    pypi_0    pypi
</code>```

What can be done to be able to export such a module to onnx and run it successfully?

答:
From checking online I found a similar issue on GitHub about conv (https://github.com/microsoft/onnxruntime/issues/3130), could be that the types of the parameters used in torch are not compatible with the implementation of RandomNormalLike available in ONNX.

Could you check in netron what's inside the RandomNormalLike node/nodes to see if they comply with the spec: https://github.com/onnx/onnx/blob/main/docs/Operators.md#RandomNormal or https://github.com/onnx/onnx/blob/main/docs/Operators.md#RandomNormalLike

Cheers

EDIT: turns out the RandomNormal node has a type of 10 which corresponds to fp16

While the onnxruntime implementation only supports float and doubles see source code here: https://github.com/microsoft/onnxruntime/blob/24e35fba3217bf33b0e4064bc71d271a61938ba0/onnxruntime/core/providers/cpu/generator/random.cc#L354

Solution here is either to run the whole model in fp32 or ask explicitely RandomNormalLike to use floats or doubles hoping that torch allows mixed computation on fp16 and fp32/fp64 I guess

Body:
I am trying to convert a fairly complex model from pytorch into ONNX. The conversion succeeds without error, but I am encountering this error when loading the model:

Traceback (most recent call last):
  File "/home/***/***/***.py", line 50, in <module>
    main()
  File "/home/***/***/***.py", line 38, in main
    ort_session = ort.InferenceSession(onnx_path, providers=[
  File "/home/***/miniconda3/envs/***/lib/python3.9/site-packages/onnxruntime/capi/onnxruntime_inference_collection.py", line 324, in __init__
    self._create_inference_session(providers, provider_options, disabled_optimizers)
  File "/home/***/miniconda3/envs/***/lib/python3.9/site-packages/onnxruntime/capi/onnxruntime_inference_collection.py", line 369, in _create_inference_session
    sess.initialize_session(providers, provider_options, disabled_optimizers)
onnxruntime.capi.onnxruntime_pybind11_state.NotImplemented: [ONNXRuntimeError] : 9 : NOT_IMPLEMENTED : Could not find an implementation for RandomNormalLike(1) node with name 'RandomNormalLike_598'

I think that the RandomNormalLike node the error is complaining about might correspond to this module I have:

class NoiseInjection(nn.Module):
    def __init__(self):
        super().__init__()

        self.weight = nn.Parameter(torch.zeros(1), requires_grad=True)

    def forward(
        self,
        feat: torch.Tensor,
        noise: Optional[torch.Tensor] = None,
    ) -> torch.Tensor:
        if noise is None:
            batch, _, height, width = feat.shape
            noise = torch.randn(
                batch, 1, height, width,
                dtype=feat.dtype,
                device=feat.device,
            )

        return feat + self.weight * noise

I also created a different implementation, but it leads to the same error: (edit: This version actually works. I made an unrelated mistake elsewhere that mislead me into thinking it did not work)

    def forward(
        self,
        feat: torch.Tensor,
        noise: Optional[torch.Tensor] = None,
    ) -> torch.Tensor:
        if noise is None:
            noise = torch.randn_like(feat[:, 0:1])

        return feat + self.weight * noise

My pytorch and onnx version are as follows:

$ conda list torch
# Name                    Version                   Build  Channel
torch                     1.10.0+cu113             pypi_0    pypi
torchaudio                0.10.0+cu113             pypi_0    pypi
torchvision               0.11.1+cu113             pypi_0    pypi

$ conda list onnx
# Name                    Version                   Build  Channel
onnx                      1.10.2                   pypi_0    pypi
onnxruntime-gpu           1.9.0                    pypi_0    pypi

What can be done to be able to export such a module to onnx and run it successfully?


问:
Can only compile and run when including .cpp file
I'm doing some linked list practices in C++ and created a simple class for the single linked list. When I try to include the header-file in the main program however I get an undefined reference error. If I include the .cpp file however it works as I want it to.

It's been a while since I last coded in C++ and I can't for the love of me figure out what's wrong. Some help would be deeply appreciated. I'm using Windows Termnial with git-bash interface and g++ -std=c++11. The code is included below!

```<code>//The main file .cpp
#include "SingleNode.h"

int main() {
        SingleNode* tail = new SingleNode(2);
        SingleNode* head = new SingleNode(1, tail);
        head->print();
        return 0;
}
</code>```
```<code>//SingleNode.h
#ifndef SINGLENODE_H
#define SINGLENODE_H

        class SingleNode {
                public:
                        int val;
                        SingleNode* next;
                        SingleNode();
                        SingleNode(int x);
                        SingleNode(int x, SingleNode* next);

                        void print();
        };
#endif
</code>```
```<code>//SingleNode.cpp
#include "SingleNode.h"
#include <iostream>

using namespace std;
        SingleNode::SingleNode() : val(0), next(nullptr) {}
        SingleNode::SingleNode(int x) : val(x), next(nullptr) {}
        SingleNode::SingleNode(int x, SingleNode* next) : val(x), next(next) {}

        void SingleNode::print() {
                if (this->next != nullptr) {
                        cout<<this->val<<"->";
                        this->next->print();
                } else {
                        cout<<this->val<<"->"<<"null"<<endl;
                }
        }
</code>```

When run:

```<code>$ g++ -std=c++11 LinkedList.cpp -o LinkedList.exe
C:\AppData\Local\Temp\ccEbmcRt.o:LinkedList.cpp:(.text+0x30): undefined reference to `SingleNode::SingleNode(int)'
C:\AppData\Local\Temp\ccEbmcRt.o:LinkedList.cpp:(.text+0x59): undefined reference to `SingleNode::SingleNode(int, SingleNode*)'
C:\AppData\Local\Temp\ccEbmcRt.o:LinkedList.cpp:(.text+0x69): undefined reference to `SingleNode::print()'
collect2.exe: error: ld returned 1 exit status
</code>```

If I instead #include "SingleNode.cpp" it works fine.

答:
You include the header file, so prototypes are available, and the compiler does not complain. The linker needs to find the source associated with those functions. Using g++ -std=c++11 LinkedList.cpp -o LinkedList.exe to compile means that you're only using the main file source and not the other file that contains the linked list implementation.

The solution is to also pass the SingleNode.cpp file to the compiler. Hence:

g++ -std=c++11 LinkedList.cpp SingleNode.cpp -o LinkedList.exe and include the SingleNode.h file in LinkedList.cpp.

The #include directive performs textual substitution, which means that when you include the .cpp file(which, in turn, includes the header file) you have one final translation unit that contains the required source of both source files.

Also see: Why should I not include cpp files and instead use a header?

Body:
I'm doing some linked list practices in C++ and created a simple class for the single linked list. When I try to include the header-file in the main program however I get an undefined reference error. If I include the .cpp file however it works as I want it to.

It's been a while since I last coded in C++ and I can't for the love of me figure out what's wrong. Some help would be deeply appreciated. I'm using Windows Termnial with git-bash interface and g++ -std=c++11. The code is included below!

//The main file .cpp
#include "SingleNode.h"

int main() {
        SingleNode* tail = new SingleNode(2);
        SingleNode* head = new SingleNode(1, tail);
        head->print();
        return 0;
}

//SingleNode.h
#ifndef SINGLENODE_H
#define SINGLENODE_H

        class SingleNode {
                public:
                        int val;
                        SingleNode* next;
                        SingleNode();
                        SingleNode(int x);
                        SingleNode(int x, SingleNode* next);

                        void print();
        };
#endif

//SingleNode.cpp
#include "SingleNode.h"
#include <iostream>

using namespace std;
        SingleNode::SingleNode() : val(0), next(nullptr) {}
        SingleNode::SingleNode(int x) : val(x), next(nullptr) {}
        SingleNode::SingleNode(int x, SingleNode* next) : val(x), next(next) {}

        void SingleNode::print() {
                if (this->next != nullptr) {
                        cout<<this->val<<"->";
                        this->next->print();
                } else {
                        cout<<this->val<<"->"<<"null"<<endl;
                }
        }

When run:

$ g++ -std=c++11 LinkedList.cpp -o LinkedList.exe
C:\AppData\Local\Temp\ccEbmcRt.o:LinkedList.cpp:(.text+0x30): undefined reference to `SingleNode::SingleNode(int)'
C:\AppData\Local\Temp\ccEbmcRt.o:LinkedList.cpp:(.text+0x59): undefined reference to `SingleNode::SingleNode(int, SingleNode*)'
C:\AppData\Local\Temp\ccEbmcRt.o:LinkedList.cpp:(.text+0x69): undefined reference to `SingleNode::print()'
collect2.exe: error: ld returned 1 exit status

If I instead #include "SingleNode.cpp" it works fine.


问:
iOS error "Embedded binary is not signed with the same certificate as the parent app"
Those are my first steps in IOS applications development and I'm facing some problem that I can't figure out.

```<code>error: Embedded binary is not signed with the same certificate as the parent app. Verify the embedded binary target's code sign settings match the parent app's.

    Embedded Binary Signing Certificate:    Not Code Signed
    Parent App Signing Certificate:         iPhone Developer: Emil Adz (9QNEF95395)
</code>```

I can't understand, what is a Embedded Binary Signing Certificate?

I went over the questions with the same error here, but none of them were related to the problem presented here (Not Code Signed).

I tried to revoke my certificate from the Apple Developer Member Center and request another certificate, but the issue persists.

Does some know how it could be fixed?

答: In my case the key was to delete 'Products' folder. Then the build was successful. Moreover, after that I made git reset --hard and tried again with the same successful result.

Body:
Those are my first steps in IOS applications development and I'm facing some problem that I can't figure out.

error: Embedded binary is not signed with the same certificate as the parent app. Verify the embedded binary target's code sign settings match the parent app's.

    Embedded Binary Signing Certificate:    Not Code Signed
    Parent App Signing Certificate:         iPhone Developer: Emil Adz (9QNEF95395)

I can't understand, what is a Embedded Binary Signing Certificate?

I went over the questions with the same error here, but none of them were related to the problem presented here (Not Code Signed).

I tried to revoke my certificate from the Apple Developer Member Center and request another certificate, but the issue persists.

Does some know how it could be fixed?