问:
QT Dialog has incorrect styling
I've been trying various methods of creating a new dialog that needs to be spawned from the main application.

I created a designer form, nothing special about it, and placed some stock widgets on it. Once I finally got it to launch from the main application properly, I noticed that the widgets have no styling to them. The buttons have no border or embossing, all text is white, and the background color of the buttons and LineEdit object are gray. The code used to launch the dialog is as follows:

    UpdateDialog dialog(NULL);
    dialog.setModal(true);
    dialog.exec();
```

<p>I figured maybe it was being inherited from the parent widget, so I passed NULL as the parent in the constructor for the dialog object and it still happened.</p>

<p>I found one answer to a similar question online suggesting that you can override inherited stylesheets from the parent by setting a stylesheet for the dialog that basically just looks like:</p>

<pre class="lang-css prettyprint-override"><code>    #objectName {}
</code>```

But this has no effect.

Styles applied to the widget after creation seem to work, as if I use the following line, the text color on the buttons becomes black:

    dialog->setStyleSheet("color: rgb(0,0,0)");
```

Does anyone know what could be causing this behavior? If it matters, we're using Qt 5.6.1 on Scientific Linux (RHEL 6).

EDIT: Here is a picture of the dialog.

There is supposed to be a LineEdit below the label, as well as a button to the right of it, and then two more buttons beneath the LineEdit. Unfortunately the picture quality doesn't let you see it, but there IS a very faint white text where the buttons are supposed to be, so they ARE there, they're just not styled.

EDIT: This styling also seems to get applied to the file dialog I spawn from the update dialog seen above.

答:
Qt does not have a strong visual identity of its own. Instead, it tries to provide a native look and feel on all its target platforms. All operating systems include some look-and-feel customization capabilities, but in this area Linux is special, because there is not a single, unique user interface like in Windows and macOS, but there are several. Two well known desktops for Linux (and other Unix-like Operating Systems) are Gnome and KDE. Some distributions install Gnome as default, and a few install the other. Most allow to install both, and the user can choose one at the login screen, or in a desktop configuration setting.

I've never tried Scientific Linux before, but I know Fedora so it wasn't a big deal to install SL6 in a VirtualBox VM to see if I could reproduce your issue (I couldn't!). What I've noticed is that SL6 defaults to Gnome desktop (like RH and Fedora, btw). It does not include Qt5 and it would be difficult to install a Qt5 development environment on it, because it ships an outdated GCC compiler. It is possible to deploy Qt 5.6 applications and libraries on it, though. I've installed KDE in the VM as well with this command:

```<code>    sudo yum -y groupinstall "KDE Desktop"
</code>```

SL6 does not include KDE Plasma, of course, because it requires Qt5. It is KDE4.3 instead, based on Qt4.6. So, in this version, correcting my previous comment, the configuration command for changing/inspecting KDE styles is:

```<code>    kcmshell4 style
</code>```

The default style for KDE4 is Oxygen, as I've deduced by your picture. The color scheme for KDE programs can be configured with this command:

```<code>    kcmshell4 colors
</code>```

To try your scenario, I've made a simple Qt5 Widgets program, which I could deploy on the VM along with the dependent Qt5 libraries. I've used linuxdeployqt to deploy the library and plugins required by the program and create a self contained directory for easy transfer and installing. Anyway, I want to show you how the program looks on my development Linux machine, with my preferred dark-breeze theme:

After deploying the program directory to the SL6 VM, running it under the default Gnome desktop, it looks like this:

And this is the look when running the program under KDE:

Remember that we are looking at the same build of the same program, just changing the running environment. Just for your information, I've instrumented my program a little, including in the main() function this debugging statement:

```<code>     qDebug() << QStyleFactory::keys();
</code>```

Which prints this output on Linux:

("Windows", "GTK+", "Fusion")

And also included this debug statement at the main window constructor:

```<code>    qDebug() << this->style();
</code>```

The output of that statement depends on the desktop environment. Under Gnome (which is based on the gtk+ toolkit) it outputs something like this:

QGtkStyle(0x11b39f0, name = "gtk+")

While under the KDE desktop it outputs:

QFusionStyle(0x1428990, name = "fusion")

I hope that at this point you can deduce like me that the origin of your problem must be the color configuration under KDE in your SL6. To prove that theory, please run some other Qt programs and see if they show the same inappropriate colors. In that case, my advice is to fix that configuration (by running kcmshell4 colors) instead of changing the program to force some fixed color scheme, because a good desktop integration is a valued asset for most Linux users.

Anyway, if you want to create a fixed color scheme hardcoded in your program, I give you this example that you can include in your main.cpp to be applied to the whole program.

```<code>static QPalette qt_fusionPalette()
{
    QColor backGround(239, 239, 239);
    QColor light = backGround.lighter(150);
    QColor mid(backGround.darker(130));
    QColor midLight = mid.lighter(110);
    QColor base = Qt::white;
    QColor disabledBase(backGround);
    QColor dark = backGround.darker(150);
    QColor darkDisabled = QColor(209, 209, 209).darker(110);
    QColor text = Qt::black;
    QColor hightlightedText = Qt::white;
    QColor disabledText = QColor(190, 190, 190);
    QColor button = backGround;
    QColor shadow = dark.darker(135);
    QColor disabledShadow = shadow.lighter(150);

    QPalette fusionPalette(Qt::black,backGround,light,dark,mid,text,base);
    fusionPalette.setBrush(QPalette::Midlight, midLight);
    fusionPalette.setBrush(QPalette::Button, button);
    fusionPalette.setBrush(QPalette::Shadow, shadow);
    fusionPalette.setBrush(QPalette::HighlightedText, hightlightedText);

    fusionPalette.setBrush(QPalette::Disabled, QPalette::Text, disabledText);
    fusionPalette.setBrush(QPalette::Disabled, QPalette::WindowText, disabledText);
    fusionPalette.setBrush(QPalette::Disabled, QPalette::ButtonText, disabledText);
    fusionPalette.setBrush(QPalette::Disabled, QPalette::Base, disabledBase);
    fusionPalette.setBrush(QPalette::Disabled, QPalette::Dark, darkDisabled);
    fusionPalette.setBrush(QPalette::Disabled, QPalette::Shadow, disabledShadow);

    fusionPalette.setBrush(QPalette::Active, QPalette::Highlight, QColor(48, 140, 198));
    fusionPalette.setBrush(QPalette::Inactive, QPalette::Highlight, QColor(48, 140, 198));
    fusionPalette.setBrush(QPalette::Disabled, QPalette::Highlight, QColor(145, 145, 145));
    return fusionPalette;
}

int main(int argc, char *argv[])
{
    QApplication::setPalette(qt_fusionPalette());
    QApplication a(argc, argv);
    qDebug() << QStyleFactory::keys();

    MainWindow w;
    w.show();
    return a.exec();
}
</code>```

This light color palette is the same as the standard Qt's "Fusion" palette. If you prefer a dark color scheme, you may find one here.

Title: QT Dialog has incorrect styling

Body:
I've been trying various methods of creating a new dialog that needs to be spawned from the main application.

I created a designer form, nothing special about it, and placed some stock widgets on it. Once I finally got it to launch from the main application properly, I noticed that the widgets have no styling to them. The buttons have no border or embossing, all text is white, and the background color of the buttons and LineEdit object are gray. The code used to launch the dialog is as follows:

    UpdateDialog dialog(NULL);
    dialog.setModal(true);
    dialog.exec();

I figured maybe it was being inherited from the parent widget, so I passed NULL as the parent in the constructor for the dialog object and it still happened.

I found one answer to a similar question online suggesting that you can override inherited stylesheets from the parent by setting a stylesheet for the dialog that basically just looks like:

    #objectName {}

But this has no effect.

Styles applied to the widget after creation seem to work, as if I use the following line, the text color on the buttons becomes black:

    dialog->setStyleSheet("color: rgb(0,0,0)");

Does anyone know what could be causing this behavior? If it matters, we're using Qt 5.6.1 on Scientific Linux (RHEL 6).

EDIT: Here is a picture of the dialog.

There is supposed to be a LineEdit below the label, as well as a button to the right of it, and then two more buttons beneath the LineEdit. Unfortunately the picture quality doesn't let you see it, but there IS a very faint white text where the buttons are supposed to be, so they ARE there, they're just not styled.

EDIT: This styling also seems to get applied to the file dialog I spawn from the update dialog seen above.

Body:
Qt does not have a strong visual identity of its own. Instead, it tries to provide a native look and feel on all its target platforms. All operating systems include some look-and-feel customization capabilities, but in this area Linux is special, because there is not a single, unique user interface like in Windows and macOS, but there are several. Two well known desktops for Linux (and other Unix-like Operating Systems) are Gnome and KDE. Some distributions install Gnome as default, and a few install the other. Most allow to install both, and the user can choose one at the login screen, or in a desktop configuration setting.

I've never tried Scientific Linux before, but I know Fedora so it wasn't a big deal to install SL6 in a VirtualBox VM to see if I could reproduce your issue (I couldn't!). What I've noticed is that SL6 defaults to Gnome desktop (like RH and Fedora, btw). It does not include Qt5 and it would be difficult to install a Qt5 development environment on it, because it ships an outdated GCC compiler. It is possible to deploy Qt 5.6 applications and libraries on it, though. I've installed KDE in the VM as well with this command:

    sudo yum -y groupinstall "KDE Desktop"

SL6 does not include KDE Plasma, of course, because it requires Qt5. It is KDE4.3 instead, based on Qt4.6. So, in this version, correcting my previous comment, the configuration command for changing/inspecting KDE styles is:

    kcmshell4 style

The default style for KDE4 is Oxygen, as I've deduced by your picture. The color scheme for KDE programs can be configured with this command:

    kcmshell4 colors

To try your scenario, I've made a simple Qt5 Widgets program, which I could deploy on the VM along with the dependent Qt5 libraries. I've used linuxdeployqt to deploy the library and plugins required by the program and create a self contained directory for easy transfer and installing. Anyway, I want to show you how the program looks on my development Linux machine, with my preferred dark-breeze theme:

After deploying the program directory to the SL6 VM, running it under the default Gnome desktop, it looks like this:

And this is the look when running the program under KDE:

Remember that we are looking at the same build of the same program, just changing the running environment. Just for your information, I've instrumented my program a little, including in the main() function this debugging statement:

     qDebug() << QStyleFactory::keys();

Which prints this output on Linux:

("Windows", "GTK+", "Fusion")

And also included this debug statement at the main window constructor:

    qDebug() << this->style();

The output of that statement depends on the desktop environment. Under Gnome (which is based on the gtk+ toolkit) it outputs something like this:

QGtkStyle(0x11b39f0, name = "gtk+")

While under the KDE desktop it outputs:

QFusionStyle(0x1428990, name = "fusion")

I hope that at this point you can deduce like me that the origin of your problem must be the color configuration under KDE in your SL6. To prove that theory, please run some other Qt programs and see if they show the same inappropriate colors. In that case, my advice is to fix that configuration (by running kcmshell4 colors) instead of changing the program to force some fixed color scheme, because a good desktop integration is a valued asset for most Linux users.

Anyway, if you want to create a fixed color scheme hardcoded in your program, I give you this example that you can include in your main.cpp to be applied to the whole program.

static QPalette qt_fusionPalette()
{
    QColor backGround(239, 239, 239);
    QColor light = backGround.lighter(150);
    QColor mid(backGround.darker(130));
    QColor midLight = mid.lighter(110);
    QColor base = Qt::white;
    QColor disabledBase(backGround);
    QColor dark = backGround.darker(150);
    QColor darkDisabled = QColor(209, 209, 209).darker(110);
    QColor text = Qt::black;
    QColor hightlightedText = Qt::white;
    QColor disabledText = QColor(190, 190, 190);
    QColor button = backGround;
    QColor shadow = dark.darker(135);
    QColor disabledShadow = shadow.lighter(150);

    QPalette fusionPalette(Qt::black,backGround,light,dark,mid,text,base);
    fusionPalette.setBrush(QPalette::Midlight, midLight);
    fusionPalette.setBrush(QPalette::Button, button);
    fusionPalette.setBrush(QPalette::Shadow, shadow);
    fusionPalette.setBrush(QPalette::HighlightedText, hightlightedText);

    fusionPalette.setBrush(QPalette::Disabled, QPalette::Text, disabledText);
    fusionPalette.setBrush(QPalette::Disabled, QPalette::WindowText, disabledText);
    fusionPalette.setBrush(QPalette::Disabled, QPalette::ButtonText, disabledText);
    fusionPalette.setBrush(QPalette::Disabled, QPalette::Base, disabledBase);
    fusionPalette.setBrush(QPalette::Disabled, QPalette::Dark, darkDisabled);
    fusionPalette.setBrush(QPalette::Disabled, QPalette::Shadow, disabledShadow);

    fusionPalette.setBrush(QPalette::Active, QPalette::Highlight, QColor(48, 140, 198));
    fusionPalette.setBrush(QPalette::Inactive, QPalette::Highlight, QColor(48, 140, 198));
    fusionPalette.setBrush(QPalette::Disabled, QPalette::Highlight, QColor(145, 145, 145));
    return fusionPalette;
}

int main(int argc, char *argv[])
{
    QApplication::setPalette(qt_fusionPalette());
    QApplication a(argc, argv);
    qDebug() << QStyleFactory::keys();

    MainWindow w;
    w.show();
    return a.exec();
}

This light color palette is the same as the standard Qt's "Fusion" palette. If you prefer a dark color scheme, you may find one here.


来源: stackexchange

问:
react native:typeerror null is not an object (evaluating '_reactnative simdata.default.get sim info().DeviceId0)
I Developed an Aplication in Expo.And finally Need to get User DeviceId that doesn't Support in Expo.
so I Had to eject my project to react native,
But after ejecting When I tried to use react native sim data It Doesn't Work.
This Error Appears Every Time:

typeerror null is not an object (evaluating
  '_reactnativesimdata.default.getsiminfo().DeviceId0)

What I Done:
First of all I installed this module by this command:

npm i react-native-sim-data
then linked that to myproject By this Command:
react-native link react-native-sim-data
This Is My Code:

```<code>import React from 'react';
import { PermissionsAndroid ,Button,View} from 'react-native';

import RNSimData from 'react-native-sim-data'

export default class App extends React.Component {

  render() {

    return (
    <View>

          <Button title="permission" onPress={()=>{   PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.READ_PHONE_STATE);}}></Button>
          <Button title="Show Id" onPress={()=>{  var x=RNSimData.getSimInfo().deviceId0;
  if(x!=null)alert(x); else alert('nooooo');}}></Button>

    </View>
  )
}
}
</code>```

Please Help Me,
this problem made me crazy

答:
Are you trying to use this on an emulator that doesn't have a sim card? See https://github.com/pocesar/react-native-sim-data#caveats in the README for react-native-sim-data.

If you are running on an actual device with a real sim card and you're still seeing this error I would suggest modifying your button's event handler to null check some of the various steps in the process:

```<code>var buttonClickEventHandler = ()=> {
  var simInfo = RNSimData.getSimInfo();
  if (!simInfo) {
    alert("no info")
  } else {
    var deviceId = simInfo.deviceId0;
    if (!deviceId) {
      alert("no device Id");
    } else {
      alert(deviceId);
    }
  }
}

</code>```

ContentLicense: CC BY-SA 4.0

Body:
I Developed an Aplication in Expo.And finally Need to get User DeviceId that doesn't Support in Expo.
so I Had to eject my project to react native,
But after ejecting When I tried to use react native sim data It Doesn't Work.
This Error Appears Every Time:

typeerror null is not an object (evaluating
  '_reactnativesimdata.default.getsiminfo().DeviceId0)

What I Done:
First of all I installed this module by this command:

npm i react-native-sim-data
then linked that to myproject By this Command:
react-native link react-native-sim-data
This Is My Code:

import React from 'react';
import { PermissionsAndroid ,Button,View} from 'react-native';

import RNSimData from 'react-native-sim-data'

export default class App extends React.Component {

  render() {

    return (
    <View>

          <Button title="permission" onPress={()=>{   PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.READ_PHONE_STATE);}}></Button>
          <Button title="Show Id" onPress={()=>{  var x=RNSimData.getSimInfo().deviceId0;
  if(x!=null)alert(x); else alert('nooooo');}}></Button>

    </View>
  )
}
}

Please Help Me,
this problem made me crazy

Body:
Are you trying to use this on an emulator that doesn't have a sim card? See https://github.com/pocesar/react-native-sim-data#caveats in the README for react-native-sim-data.

If you are running on an actual device with a real sim card and you're still seeing this error I would suggest modifying your button's event handler to null check some of the various steps in the process:

var buttonClickEventHandler = ()=> {
  var simInfo = RNSimData.getSimInfo();
  if (!simInfo) {
    alert("no info")
  } else {
    var deviceId = simInfo.deviceId0;
    if (!deviceId) {
      alert("no device Id");
    } else {
      alert(deviceId);
    }
  }
}


问:
How to prevent webpack DefinePlugin from changing vendor bundle file name?
I have followed webpack caching guide and now I have 3 bundles: main, runtime, and vendors.

However, in my webpack.config.js, I use DefinePlugin to export package.json version to the UI, like so:

new DefinePlugin({
  'process.env': {
    VERSION: JSON.stringify(`v${packageJSON.version}`)
   }
}),
```

This causes my vendor bundle file name to change with each release of the UI.

How can I put the globals defined with DefinePlugin into the main bundle?

答:
Turned out the problem is with the key defined with DefinePlugin: 'process.env'.

We missed to read plugin warning box, so webpack was replacing every occurrence of process.env in third-party libraries with our object. As we also include the app version, the resulting vendors.*.js bundle were different for each release.

By renaming process.env to just env (and changing our code accordingly), webpack is now able to produce the same vendors.*.js bundle, regardless of our app version.

Body:
I have followed webpack caching guide and now I have 3 bundles: main, runtime, and vendors.

However, in my webpack.config.js, I use DefinePlugin to export package.json version to the UI, like so:

new DefinePlugin({
  'process.env': {
    VERSION: JSON.stringify(`v${packageJSON.version}`)
   }
}),

This causes my vendor bundle file name to change with each release of the UI.

How can I put the globals defined with DefinePlugin into the main bundle?


问:
Best practice to record large amount of hits into MySQL database
Well, this is the thing. Let's say that my future PHP CMS need to drive 500k visitors daily and I need to record them all in MySQL database (referrer, ip address, time etc.). This way I need to insert 300-500 rows per minute and update 50 more. The main problem is that script would call database every time I want to insert new row, which is every time someone hits a page.

My question, is there any way to locally cache incoming hits first (and what is the best solution for that apc, csv...?) and periodically send them to database every 10 minutes for example? Is this good solution and what is the best practice for this situation?

答:
I have also previously seen a system which records the data into a flat file on the local disc on each web server (be careful to do only atomic appends if using multiple proceses), and periodically asynchronously write them into the database using a daemon process or cron job.

This appears to be the prevailing optimium solution; your web app remains available if the audit database is down and users don't suffer poor performance if the database is slow for any reason.

The only thing I can say, is be sure that you have monitoring on these locally-generated files - a build-up definitely indicates a problem and your Ops engineers might not otherwise notice.

ContentLicense: CC BY-SA 3.0


问:
Datatables rowchild to generated table
I have an angular app to get fields from a database and generate a table with it.
I'm using datatables on that generated table because I want the sorting and page buttons and entries per page.

I'd like to add a rowchild with hidden values like this one
This is my index.html:

```<code>                <table class="table table-bordered table-hover" id="table">
                    <thead class="thead-dark">
                        <tr>
                            <th></th>
                            <th><h4>Name</h4></th>
                            <th><h4>Price</h4></th>
                            <th><h4>Qt</h4></th>
                            <th class="d-none"><h4>Picture1</h4></th>
                            <th class="d-none"><h4>Picture2</h4></th>
                            <th class="d-none"><h4>Picture3</h4></th>
                        </tr>
                    </thead>
                    <tbody class="bg-light">
                        <tr class="gradeU" ng-repeat="x in fruits">
                            <td class="details-control"></td>
                            <th class="name">{{ x.name }}</th>
                            <td>{{ x.price}}€</td>
                            <td>{{ x.qt}}</td>
                            <td class="d-none p1">{{x.pic1}}</td>
                            <td class="d-none p2">{{x.pic2}}</td>
                            <td class="d-none p3">{{x.pic3}}</td>
                        </tr>
                    </tbody>
                </table>
                <style>
                    td.details-control {
                        background: url('http://datatables.net/examples/resources/details_open.png') no-repeat center center;
                        cursor: pointer;
                    }
                    tr.shown td.details-control {
                        background: url('http://datatables.net/examples/resources/details_close.png')
                        no-repeat center center;
                    }
                </style>
</code>```

This is my app.js:

```<code>var app = angular.module('myApp', []);
// fruit list
app.controller('fruitController', function($scope, $http) {
    $http.get("db.php").then(function (response) {
        $scope.fruits = response.data.fruits;
    });
});
// table
$(document).ready( function () {
    $('#table').DataTable();
} );
</code>```

Right now I have a table with hidden content to show it on a childrow, but I can't find a way to do it on a generated table.

I jsut want to show hidden content on a childrow when td.details-control is clicked.

答:
Update your $(document).ready() function as below:

```<code>$(document).ready( function () {

    var table = $('#table').DataTable();

    $('#table').on('click', 'td.details-control', function () {
        var tr = $(this).closest('tr');
        var row = table.row(tr);

        if (row.child.isShown()) {
            row.child.hide();
        }
        else {
            row.child("content for child row").show();
        }
    });
});
</code>```

Title: Datatables rowchild to generated table

Body:
I have an angular app to get fields from a database and generate a table with it.
I'm using datatables on that generated table because I want the sorting and page buttons and entries per page.

I'd like to add a rowchild with hidden values like this one
This is my index.html:

Name

Price

Qt

Picture1

Picture2

Picture3

                            {{ x.name }}
                            {{ x.price}}€
                            {{ x.qt}}
                            {{x.pic1}}
                            {{x.pic2}}
                            {{x.pic3}}

This is my app.js:

var app = angular.module('myApp', []);
// fruit list
app.controller('fruitController', function($scope, $http) {
    $http.get("db.php").then(function (response) {
        $scope.fruits = response.data.fruits;
    });
});
// table
$(document).ready( function () {
    $('#table').DataTable();
} );

Right now I have a table with hidden content to show it on a childrow, but I can't find a way to do it on a generated table.

I jsut want to show hidden content on a childrow when td.details-control is clicked.

Body:
Update your $(document).ready() function as below:

$(document).ready( function () {

    var table = $('#table').DataTable();

    $('#table').on('click', 'td.details-control', function () {
        var tr = $(this).closest('tr');
        var row = table.row(tr);

        if (row.child.isShown()) {
            row.child.hide();
        }
        else {
            row.child("content for child row").show();
        }
    });
});


问:
How to deal with double quotes in conditional formatting's formula
I was having a look at this question, and in order to help, I wrote a conditional formatting rule, based on this formula:

```<code>="ABS(B3-A3)>=1,5" // the double-quotes are automatically added by Excel
</code>```

This, however, seems not to work, although the formula seems to be correct (in the cell at the right, I asked whether this was true and I got a positive result, as you can see (WAAR is Dutch for true)):

I'm not interested in the final solution, I just want to know how I can debug such a situation: apparantly the formula is true, but still the conditional formatting is not applied. This might mean that:

Something is wrong with the language settings.

Something is wrong with the dot/comma decimal separator.

Something else is wrong with the formula (absolute references, relative references, ...)

How can I, step by step, evaluate the formula, entered in a conditional formatting configuration, in order to see what might be wrong?

Thanks in advance

答:
Sorry, guys, but the truth is really nerve-wrecking:

The answer of Error 1004 is correct. Thanks for the screenshot.

The answer of Jario is correct too.

So what's the deal?

Apparently there seems to be a problem with the decimal separator : when I enter a dot, using Excel regularly, it gets converted into a comma. When I enter a dot in a conditional formatting formula, this conversion is not done, resulting in a wrong formula, where Excel automatically adds double quotes. As the double quotes result in a wrong formula, the conditional formatting won't be applied.

So:

From the moment you see double quotes in a conditional formula, this is an indication that something's wrong, and that your conditional formatting won't work!

Body:
I was having a look at this question, and in order to help, I wrote a conditional formatting rule, based on this formula:

="ABS(B3-A3)>=1,5" // the double-quotes are automatically added by Excel

This, however, seems not to work, although the formula seems to be correct (in the cell at the right, I asked whether this was true and I got a positive result, as you can see (WAAR is Dutch for true)):

I'm not interested in the final solution, I just want to know how I can debug such a situation: apparantly the formula is true, but still the conditional formatting is not applied. This might mean that:

Something is wrong with the language settings.

Something is wrong with the dot/comma decimal separator.

Something else is wrong with the formula (absolute references, relative references, ...)

How can I, step by step, evaluate the formula, entered in a conditional formatting configuration, in order to see what might be wrong?

Thanks in advance


问:
All possible exact sums from multiple arrays
I've been given the following problem and my code has become a horrible mess and I'm quite stuck.

You are given an allowance to spend at some shops (something like $15, just some positive integer)
You may only spend this money under two conditions:

1) You buy exactly one item from each shop.

2) You spend all of your money (nothing left over, and no debt)

Find all possible ways you could have purchased items to satisfy the above.

In actuality, you're given a budget int and some array like

9 and [[1,2,3],[0,5],[2,3,8]]

where each inner array lists the prices of items in the a shop. There can be arbitrarily many shops with arbitrarily many items. Costs cannot be negative, but they can be free!

The expected solution here would be:

[[1,5,3],[2,5,2],[1,0,8]]

As each array contains one item from each shop, each totals 9, and all possibilities are present.
Just to make it more difficult, speed is paramount.

The following is my code that has descended into madness and a near complete lack of functionality:

def Stepper(bud,LOL):
    n=len(LOL)
    lasts=[]
    indices=[0 for j in range(n)]
    focus=0
    funds=[0 for j in range(n+1)]
    funds[0]=bud
    sols=[]
    moveable=[]
    for j in range(n):
        length=len(LOL[j])
        if(length==0):
            return []
        lasts.append(length-1)
        if(moveable==[]):
            if(length==1):
                funds[j+1]=funds[j]-LOL[j][0]
            else:
                moveable.append(j)
                focus=j
    while(moveable!=[]):
        while(LOL[focus][indices[focus]] > funds[focus]):
            indices[focus]+=1
        if(indices[focus]==lasts[focus]):
            if(moveable[-1]==focus):
                moveable.remove(focus)
            if(moveable==[]):
                if(focus<n-1):
                    moveable.append(focus+1)
        funds[focus+1]=funds[focus]-LOL[focus][indices[focus]]
        #print(n,lasts,indices,focus,moveable,funds,sols)
        if((funds[focus+1]!=0) and (focus<n-1)):
                focus+=1
                indices[focus]=0
        else:
            if(funds[focus+1]==0):
                for j in range(focus+1,n):
                    indices[j]=lasts[j]
                sols.append(list(indices))
            if(moveable[-1]==n-1):
                moveable.remove(n-1)
            if(moveable!=[]):
                focus=moveable[-1]
                indices[focus]+=1
                if(indices[focus]==lasts[focus]):
                    if(moveable[-1]==focus):
                        moveable.remove(focus)
                    if(moveable==[]):
                        if(focus<n-1):
                            moveable.append(focus+1)
                funds[focus+1]=funds[focus]-LOL[focus][indices[focus]]
                focus+=1
                indices[focus]=0
    return(sols)
```

where bud is the budget and LOL is the list of lists (the shops and prices)

答:
If you're still interested in an algorithm this is my solution:

def Stepper(bud, shops, combinations = None):
    if combinations is None:
        combinations = [[item] for item in shops[0]]
        #if empty, populate  the list of combinations with list containing every item of the first shop
        shops = shops[1:] #remove the shop from the list

    if len(shops) == 1: #if only one shop remains
        counter = 0
        while counter < len(combinations):
            comb = combinations[counter] # take a combination
            diff = bud - sum(comb)       # check how much you have to spend
            if diff in shops[0]:
                #if the shop have what you're looking for you keep the combination
                comb.append(diff)
                counter += 1
            else:
                # there is no way to spend all the money
                combinations.remove(comb)

        return combinations

    new_combinations = list()
    for old_combination in combinations:
        for item in shops[0]:
            comb = old_combination + [item] #create every possible combination mixing the old combinations with the items of the next stop
            if sum(comb) < bud: new_combinations.append(comb) # the combination is valid only if you have 0 or more money left
    return Stepper(bud,shops[1:],new_combinations) # calculate combinations with the remaining shops
```

<p>To test it simply call</p>

```Stepper(9, [[1,2,3],[0,5],[2,3,8]])
```

Body:
I've been given the following problem and my code has become a horrible mess and I'm quite stuck.

You are given an allowance to spend at some shops (something like $15, just some positive integer)
You may only spend this money under two conditions:

1) You buy exactly one item from each shop.

2) You spend all of your money (nothing left over, and no debt)

Find all possible ways you could have purchased items to satisfy the above.

In actuality, you're given a budget int and some array like

9 and [[1,2,3],[0,5],[2,3,8]]

where each inner array lists the prices of items in the a shop. There can be arbitrarily many shops with arbitrarily many items. Costs cannot be negative, but they can be free!

The expected solution here would be:

[[1,5,3],[2,5,2],[1,0,8]]

As each array contains one item from each shop, each totals 9, and all possibilities are present.
Just to make it more difficult, speed is paramount.

The following is my code that has descended into madness and a near complete lack of functionality:

def Stepper(bud,LOL):
    n=len(LOL)
    lasts=[]
    indices=[0 for j in range(n)]
    focus=0
    funds=[0 for j in range(n+1)]
    funds[0]=bud
    sols=[]
    moveable=[]
    for j in range(n):
        length=len(LOL[j])
        if(length==0):
            return []
        lasts.append(length-1)
        if(moveable==[]):
            if(length==1):
                funds[j+1]=funds[j]-LOL[j][0]
            else:
                moveable.append(j)
                focus=j
    while(moveable!=[]):
        while(LOL[focus][indices[focus]] > funds[focus]):
            indices[focus]+=1
        if(indices[focus]==lasts[focus]):
            if(moveable[-1]==focus):
                moveable.remove(focus)
            if(moveable==[]):
                if(focus<n-1):
                    moveable.append(focus+1)
        funds[focus+1]=funds[focus]-LOL[focus][indices[focus]]
        #print(n,lasts,indices,focus,moveable,funds,sols)
        if((funds[focus+1]!=0) and (focus<n-1)):
                focus+=1
                indices[focus]=0
        else:
            if(funds[focus+1]==0):
                for j in range(focus+1,n):
                    indices[j]=lasts[j]
                sols.append(list(indices))
            if(moveable[-1]==n-1):
                moveable.remove(n-1)
            if(moveable!=[]):
                focus=moveable[-1]
                indices[focus]+=1
                if(indices[focus]==lasts[focus]):
                    if(moveable[-1]==focus):
                        moveable.remove(focus)
                    if(moveable==[]):
                        if(focus<n-1):
                            moveable.append(focus+1)
                funds[focus+1]=funds[focus]-LOL[focus][indices[focus]]
                focus+=1
                indices[focus]=0
    return(sols)

where bud is the budget and LOL is the list of lists (the shops and prices)

Body:
If you're still interested in an algorithm this is my solution:

def Stepper(bud, shops, combinations = None):
    if combinations is None:
        combinations = [[item] for item in shops[0]]
        #if empty, populate  the list of combinations with list containing every item of the first shop
        shops = shops[1:] #remove the shop from the list

    if len(shops) == 1: #if only one shop remains
        counter = 0
        while counter < len(combinations):
            comb = combinations[counter] # take a combination
            diff = bud - sum(comb)       # check how much you have to spend
            if diff in shops[0]:
                #if the shop have what you're looking for you keep the combination
                comb.append(diff)
                counter += 1
            else:
                # there is no way to spend all the money
                combinations.remove(comb)

        return combinations

    new_combinations = list()
    for old_combination in combinations:
        for item in shops[0]:
            comb = old_combination + [item] #create every possible combination mixing the old combinations with the items of the next stop
            if sum(comb) < bud: new_combinations.append(comb) # the combination is valid only if you have 0 or more money left
    return Stepper(bud,shops[1:],new_combinations) # calculate combinations with the remaining shops

To test it simply call

Stepper(9, [[1,2,3],[0,5],[2,3,8]])


问:
How to sum numbers considered as strings?
I have a column in my dataset like this:

```<code>col1
1
1, 1, 1, 1
1, 1
1, 1, 1, 1, 1
1
</code>```

I am trying to sum each row in a new column like this output:

```<code>col2
1
4
2
5
1
</code>```

I have tried doing:

```<code>rowSums(as.numeric(as.character(df$col1)))
Error in rowSums(as.numeric(as.character(df$col1))) :
  'x' must be an array of at least two dimensions
In addition: Warning message:
In is.data.frame(x) : NAs introduced by coercion
</code>```

I am new to R and likely missing something obvious, but I can't find any similar problems online also in R to adapt to my data, any help or advice on what functions to use would be appreciated.

Data:

```<code>structure(list(col1 = c("1", "1, 1, 1, 1", "1, 1", "1, 1, 1, 1, 1", "1"),
row.names = c(NA, -5L), class = "data.frame")

</code>```

答:
One idea is to use eval(parse) after you replace , with +, i.e.

```<code>sapply(gsub(', ', '+', d3$col1, fixed = TRUE), function(i)eval(parse(text = i)))
#        1   1+1+1+1       1+1 1+1+1+1+1         1
#        1         4         2         5         1
</code>```

Another is to split and sum,

```<code>sapply(strsplit(d3$col1, ', '), function(i)sum(as.numeric(i)))
#[1] 1 4 2 5 1
</code>```

However, If you only have 1 to sum, then you can simply count them. Using stringr,

```<code>stringr::str_count(d3$col1, '1')
[1] 1 4 2 5 1
</code>```

Body:
I have a column in my dataset like this:

col1
1
1, 1, 1, 1
1, 1
1, 1, 1, 1, 1
1

I am trying to sum each row in a new column like this output:

col2
1
4
2
5
1

I have tried doing:

rowSums(as.numeric(as.character(df$col1)))
Error in rowSums(as.numeric(as.character(df$col1))) :
  'x' must be an array of at least two dimensions
In addition: Warning message:
In is.data.frame(x) : NAs introduced by coercion

I am new to R and likely missing something obvious, but I can't find any similar problems online also in R to adapt to my data, any help or advice on what functions to use would be appreciated.

Data:

structure(list(col1 = c("1", "1, 1, 1, 1", "1, 1", "1, 1, 1, 1, 1", "1"),
row.names = c(NA, -5L), class = "data.frame")

Body:
One idea is to use eval(parse) after you replace , with +, i.e.

sapply(gsub(', ', '+', d3$col1, fixed = TRUE), function(i)eval(parse(text = i)))
#        1   1+1+1+1       1+1 1+1+1+1+1         1
#        1         4         2         5         1

Another is to split and sum,

sapply(strsplit(d3$col1, ', '), function(i)sum(as.numeric(i)))
#[1] 1 4 2 5 1

However, If you only have 1 to sum, then you can simply count them. Using stringr,

stringr::str_count(d3$col1, '1')
[1] 1 4 2 5 1


问:
CMake: Howto test for compiler, before enable a language
In my project some code can be optional compiled in a different language (nasm & fortran), but it's also fine to compile the project without having these compiler installed. E.g. on Windows.

I would like to check if the the compiler are installed, before enabling the languages with enable_language

```<code>enable_language(ASM_NASM)
enable_language(Fortran)
</code>```

If I use enable_language without an additional check, CMake stops with an error message.

(At the moment I check for if (MSVC) as workaround.)

Btw. I have a similar problem with the check for Qt. The check don't stop with an error, but generate a lot of noisy warnings.

答: So use check_language to check if a language can be enabled.</p>

Body:
In my project some code can be optional compiled in a different language (nasm & fortran), but it's also fine to compile the project without having these compiler installed. E.g. on Windows.

I would like to check if the the compiler are installed, before enabling the languages with enable_language

enable_language(ASM_NASM)
enable_language(Fortran)

If I use enable_language without an additional check, CMake stops with an error message.

(At the moment I check for if (MSVC) as workaround.)

Btw. I have a similar problem with the check for Qt. The check don't stop with an error, but generate a lot of noisy warnings.


问:
Error "want to read 4 bytes from Storage, but only 3 remaining" when running example stabilizing_the_ring.py
I am already install flow0.5, sumo 1.1, RLlib and Stable Baseline.
I didn't know how to use sumo_binaries folder automatically downloaded with flow, so I installed sumo 1.1 from source.

The example python examples/sumo/sugiyama.py runs well.

But when I try running python examples/stable_baselines/stabilizing_the_ring.py
error occurs like

```<code>Error: tcpip::Storage::readIsSafe: want to read 4 bytes from Storage, but only 3 remaining
Quitting (on error).
Error during start: Traceback (most recent call last):
  File "/home/elizabeth/0MA/flow/flow/core/kernel/simulation/traci.py", line 159, in start_simulation
    traci_connection.simulationStep()
  File "/home/elizabeth/anaconda3/envs/MultiAgent/lib/python3.6/site-packages/traci/connection.py", line 323, in simulationStep
    result = self._sendExact()
  File "/home/elizabeth/anaconda3/envs/MultiAgent/lib/python3.6/site-packages/traci/connection.py", line 99, in _sendExact
    raise FatalTraCIError("connection closed by SUMO")
traci.exceptions.FatalTraCIError: connection closed by SUMO
</code>```

I wonder what exactly the problem is.
I am not sure if it is because of my sumo version doesn't match traci version.
But I don't know how to check the traci version and match them.

Is there anyone meet the same problem?
Could you please tell me more info about this issue?

Many thanks!

答: You can also get this error when you try to run flow experiments from a different environment other than flow, that is if you have multiple versions of SUMO installed.</p>

Body:
I am already install flow0.5, sumo 1.1, RLlib and Stable Baseline.
I didn't know how to use sumo_binaries folder automatically downloaded with flow, so I installed sumo 1.1 from source.

The example python examples/sumo/sugiyama.py runs well.

But when I try running python examples/stable_baselines/stabilizing_the_ring.py
error occurs like

Error: tcpip::Storage::readIsSafe: want to read 4 bytes from Storage, but only 3 remaining
Quitting (on error).
Error during start: Traceback (most recent call last):
  File "/home/elizabeth/0MA/flow/flow/core/kernel/simulation/traci.py", line 159, in start_simulation
    traci_connection.simulationStep()
  File "/home/elizabeth/anaconda3/envs/MultiAgent/lib/python3.6/site-packages/traci/connection.py", line 323, in simulationStep
    result = self._sendExact()
  File "/home/elizabeth/anaconda3/envs/MultiAgent/lib/python3.6/site-packages/traci/connection.py", line 99, in _sendExact
    raise FatalTraCIError("connection closed by SUMO")
traci.exceptions.FatalTraCIError: connection closed by SUMO

I wonder what exactly the problem is.
I am not sure if it is because of my sumo version doesn't match traci version.
But I don't know how to check the traci version and match them.

Is there anyone meet the same problem?
Could you please tell me more info about this issue?

Many thanks!


问:
MXNET CMake reports "GPU support is disabled"
I am trying to build money from source in a GPU-enabled machine. I have a NVIDIA P 100 GPU.  When I build MXNET using make, it reports that:

The snippet from CMake log is given below

```<code>-- The CUDA compiler identification is NVIDIA 10.2.89
-- Check for working CUDA compiler: /usr/local/cuda-10.2/bin/nvcc
-- Check for working CUDA compiler: /usr/local/cuda-10.2/bin/nvcc -- works
-- Detecting CUDA compiler ABI info
-- Detecting CUDA compiler ABI info - done

-- GPU support is disabled
</code>```

I want to build it with GPU support. What can I do?

答:
When building MXNet from source, the message GPU support is disabled in the output of CMake is a bit confusing. This specific message has nothing to do with CUDA. It is actually generated if we try to enable Intel MKL DNN support (-DUSE_MKLDNN=1) and the Intel OpenCL runtime is not installed in the system ( see the CMake file in which it is printed ). CMake tries to look for Intel OpenCL runtime and throws this message if not found. I believe the OpenCL runtime enables GPU support for Intel's GPUs ( Intel HD Graphics, Intel Iris and Intel Iris Pro ).

Don't worry about this error message if you do not intend to use Intel Graphics support. It won't affect the CUDA support for MXNet. If you want to suppress this message, then disable MKL DNN support (-DUSE_MKLDNN=0). If you care about Intel Graphics too, then install Intel OpenCL Runtime.

Body:
I am trying to build money from source in a GPU-enabled machine. I have a NVIDIA P 100 GPU.  When I build MXNET using make, it reports that:

The snippet from CMake log is given below

-- The CUDA compiler identification is NVIDIA 10.2.89
-- Check for working CUDA compiler: /usr/local/cuda-10.2/bin/nvcc
-- Check for working CUDA compiler: /usr/local/cuda-10.2/bin/nvcc -- works
-- Detecting CUDA compiler ABI info
-- Detecting CUDA compiler ABI info - done

-- GPU support is disabled

I want to build it with GPU support. What can I do?


问:
IE11 CSS alternative to "unset"
I have a fixed div on my page which is positioned with the following CSS properties:

```<code>width: 320px;
height: 160px;
position: fixed;
right: 15px;
bottom: 15px;
top: unset;
z-index: -1;
</code>```

The div appears fine in the bottom right of the page in other browsers, but in Internet Explorer 11 the div appears in the top right. I believe this issue is coming from top: unset; which doesnt appear to be supported in IE.

Are there any workarounds using CSS or JS that could be used to achieve the same positioning?

答: In my case top: auto didn't work, I had a bottom value instead. The default value is position: static and this worked for me in IE 11.

Title: IE11 CSS alternative to "unset"

Body:
I have a fixed div on my page which is positioned with the following CSS properties:

width: 320px;
height: 160px;
position: fixed;
right: 15px;
bottom: 15px;
top: unset;
z-index: -1;

The div appears fine in the bottom right of the page in other browsers, but in Internet Explorer 11 the div appears in the top right. I believe this issue is coming from top: unset; which doesnt appear to be supported in IE.

Are there any workarounds using CSS or JS that could be used to achieve the same positioning?


问:
How do I get ngx-mask npm package for masking phone numbers in Angular to work?
I am trying to use the ngx-mask npm package to work. The instructions are as follow:

Package found here:
https://www.npmjs.com/package/ngx-mask

```<code>import {NgxMaskModule} from 'ngx-mask'

export const options: Partial<IConfig> | (() => Partial<IConfig>);

@NgModule({
  (...)
  imports: [
    NgxMaskModule.forRoot(options)
  ]
  (...)
})
</code>```

But I am getting an error on the second line:

```<code>export const options: Partial<IConfig> | (() => Partial<IConfig>);
</code>```

The error says "const options" declaration must be initialized. What do I initialized it to?

答:
change

```<code>import { NgxMaskModule} from 'ngx-mask';
</code>```

to

```<code>import { NgxMaskModule, IConfig } from 'ngx-mask';
</code>```

Body:
I am trying to use the ngx-mask npm package to work. The instructions are as follow:

Package found here:
https://www.npmjs.com/package/ngx-mask

import {NgxMaskModule} from 'ngx-mask'

export const options: Partial<IConfig> | (() => Partial<IConfig>);

@NgModule({
  (...)
  imports: [
    NgxMaskModule.forRoot(options)
  ]
  (...)
})

But I am getting an error on the second line:

export const options: Partial<IConfig> | (() => Partial<IConfig>);

The error says "const options" declaration must be initialized. What do I initialized it to?

Body:
change

import { NgxMaskModule} from 'ngx-mask';

to

import { NgxMaskModule, IConfig } from 'ngx-mask';


问:
ActiveRecord for core data
i use this library: https://github.com/jwang/activerecord-fetching-for-core-data

```<code>- (NSManagedObjectModel *)managedObjectModel {
    if (managedObjectModel != nil) {
        return managedObjectModel;
    }
    NSString *modelPath = [[NSBundle mainBundle] pathForResource:@"BranchData" ofType:@"momd"];
    NSURL *modelURL = [NSURL fileURLWithPath:modelPath];
    managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return managedObjectModel;

}

///////

[NSManagedObjectModel setDefaultManagedObjectModel:self.managedObjectModel];
[ActiveRecordHelpers setupCoreDataStackWithStoreNamed:@"BranchData.sqlite"];

NSManagedObjectContext *context = [NSManagedObjectContext context];
[NSManagedObjectContext setDefaultContext:context];

NSLog(@"%i", [[DataBranch findAll] count]);

DataBranch *branch = [DataBranch createEntity];

NSLog(@"%i", [[DataBranch findAll] count]);

[[NSManagedObjectContext context] save];
</code>```

It works the logs prints out 0 and then 1
But if i restart my application it is not saved into the sqlite. and all data is lost
what do i do wrong ?

答: I confused the context i needed to save to the defaultContext and not the context as it woul create a new one</p>

Title: ActiveRecord for core data

Body:
i use this library: https://github.com/jwang/activerecord-fetching-for-core-data

- (NSManagedObjectModel *)managedObjectModel {
    if (managedObjectModel != nil) {
        return managedObjectModel;
    }
    NSString *modelPath = [[NSBundle mainBundle] pathForResource:@"BranchData" ofType:@"momd"];
    NSURL *modelURL = [NSURL fileURLWithPath:modelPath];
    managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return managedObjectModel;

}

///////

[NSManagedObjectModel setDefaultManagedObjectModel:self.managedObjectModel];
[ActiveRecordHelpers setupCoreDataStackWithStoreNamed:@"BranchData.sqlite"];

NSManagedObjectContext *context = [NSManagedObjectContext context];
[NSManagedObjectContext setDefaultContext:context];

NSLog(@"%i", [[DataBranch findAll] count]);

DataBranch *branch = [DataBranch createEntity];

NSLog(@"%i", [[DataBranch findAll] count]);

[[NSManagedObjectContext context] save];

It works the logs prints out 0 and then 1
But if i restart my application it is not saved into the sqlite. and all data is lost
what do i do wrong ?


问:
Wget download pdf
I am trying to download a pdf file using wget.

When I do:

wget <url> it downloads a corrupted file however if I run wget -i test.txt with the pdf URL inside this test txt file it works and the file is not corrupted.

Does anyone know why?

From the logs I can see the following.

In the first case, it is downloading a note found page.

Length: 11322 (11K) [text/html] Saving to: ‘media.nl?id=39194.1’

In the second it is a proper pdf.

Length: 58272 (57K) [application/pdf] Saving to:
  ‘media.nl?id=39194&c=4667446&h=34c63dbaaa7adc7c8a33&_xt=.pdf’

Thanks,

答:
Put your URL into quotes. Not quoting the URL can lead to strange effects, in your case the & is interpreted by the shell.

E.g.

```<code>wget "https://www.roofingsuppliesuk.co.uk/core/media/media.nl?id=39194&c=4667446&h=34c63dbaaa7adc7c8a33&_xt=.pdf"
</code>```

or

```<code>wget 'https://www.roofingsuppliesuk.co.uk/core/media/media.nl?id=39194&c=4667446&h=34c63dbaaa7adc7c8a33&_xt=.pdf'
</code>```

or with escaping of &

```<code>wget https://www.roofingsuppliesuk.co.uk/core/media/media.nl?id=39194\&c=4667446\&h=34c63dbaaa7adc7c8a33\&_xt=.pdf
</code>```

Title: Wget download pdf

Body:
Put your URL into quotes. Not quoting the URL can lead to strange effects, in your case the & is interpreted by the shell.

E.g.

wget "https://www.roofingsuppliesuk.co.uk/core/media/media.nl?id=39194&c=4667446&h=34c63dbaaa7adc7c8a33&_xt=.pdf"

or

wget 'https://www.roofingsuppliesuk.co.uk/core/media/media.nl?id=39194&c=4667446&h=34c63dbaaa7adc7c8a33&_xt=.pdf'

or with escaping of &

wget https://www.roofingsuppliesuk.co.uk/core/media/media.nl?id=39194\&c=4667446\&h=34c63dbaaa7adc7c8a33\&_xt=.pdf


问:
Check if any value in any 2 arrays with different dimension is same in php
I have 2 arrays -

```<code>$arr1 =

Array
(
    [0] => Array
        (
            [id] => 1
            [sender_email] => test1@test.com
            [to_email] => test@test.com
            [description] => 5390BF675E1464F32202B
            [created_at] => 2020-01-21 04:50:21
            [status] => 1
        )

    [1] => Array
        (
            [id] => 30
            [sender_email] => abcd@gmail.com
            [to_email] => test@test.com
            [description] => 729237A55E2EDCB80B18F
            [created_at] => 2020-01-27 12:51:34
            [status] => 1
        )
[2] => Array
        (
            [id] => 31
            [sender_email] => abc@gmail.com
            [to_email] => test@test.com
            [description] => 729237A55E2EDCB80B18F
            [created_at] => 2020-01-27 12:51:34
            [status] => 1
        )

)

$arr2 =
Array
(
    [0] => test1@test.com
    [1] =>  abb@abb.com
    [2] =>  abc@gmail.com
)
</code>```

I am trying to find the matching values from $arr2 which also exist in $arr1.

I tried with

```<code>if(array_intersect($arr2, $arr1)) {
            die('wrong');
        }
</code>```

But it show error like -

```<code> Notice: Array to string conversion in
</code>```

I think due to difference in structure. How can this be achieved? It will be really helpful if I can get all matching values in one array. The column name will always be same but I request to not make that an inclusion in the code.

答:
This should work:</p>

```<code>$matches = []; // array which will contains matches
foreach($arr1 as &$el){ // loop through the elements
   if(array_intersect($arr2,$el)) array_push($matches, $el); //and if there is at least one elements as intersect of the two arrays, add it
}
</code>```

Body:
I have 2 arrays -

$arr1 =

Array
(
    [0] => Array
        (
            [id] => 1
            [sender_email] => test1@test.com
            [to_email] => test@test.com
            [description] => 5390BF675E1464F32202B
            [created_at] => 2020-01-21 04:50:21
            [status] => 1
        )

    [1] => Array
        (
            [id] => 30
            [sender_email] => abcd@gmail.com
            [to_email] => test@test.com
            [description] => 729237A55E2EDCB80B18F
            [created_at] => 2020-01-27 12:51:34
            [status] => 1
        )
[2] => Array
        (
            [id] => 31
            [sender_email] => abc@gmail.com
            [to_email] => test@test.com
            [description] => 729237A55E2EDCB80B18F
            [created_at] => 2020-01-27 12:51:34
            [status] => 1
        )

)

$arr2 =
Array
(
    [0] => test1@test.com
    [1] =>  abb@abb.com
    [2] =>  abc@gmail.com
)

I am trying to find the matching values from $arr2 which also exist in $arr1.

I tried with

if(array_intersect($arr2, $arr1)) {
            die('wrong');
        }

But it show error like -

 Notice: Array to string conversion in

I think due to difference in structure. How can this be achieved? It will be really helpful if I can get all matching values in one array. The column name will always be same but I request to not make that an inclusion in the code.

Body:
This should work:

$matches = []; // array which will contains matches
foreach($arr1 as &$el){ // loop through the elements
   if(array_intersect($arr2,$el)) array_push($matches, $el); //and if there is at least one elements as intersect of the two arrays, add it
}


问:
React Navigation 5 - Native Stack Navigator with custom header which has a searchbar
I'm currently in a project for which we are using React Navigation 5 with the native stack navigator due to its increased performance. We are needing to add a searchbar to the header cause the client isn't gonna like it to be somewhere else. Is there any way to make a custom header?
using options={{ headerShown: false }} is not an option cause inside the native stack navigator we have a bottom stack navigator and inside this bottom tab navigator we have a top stack navigator with the screens inside it. So using headerShown: false and a custom header inside the screens would only render it below the top tabs and that would not be acceptable.
Any ideas on how to make this? is using the common stack navigator with a custom react element as the header prop the only solution?

Greatly appreciate any ideas on how to solve this.

答: Solved it using the headerRight option and passing it a full custom header component.</p>


问:
Need a PHP MySQL script to search for keywords in a database
I need to implement a search option for user comments that are stored in a MySQL database. I would optimally like it to work in a similar manner to a standard web page search engine, but I am trying to avoid the large scale solutions. I'd like to just get a feel for the queries that would give me decent results. Any suggestions? Thanks.</p>

答:
As an entry point, you can use MySQL LIKE queries.

For example if you have a table 'comments' with a column named 'comment', and you want to find all comments that contain the word 'red', use:

```<code>SELECT comment FROM comments WHERE comment LIKE '% red %';
</code>```

Please note that fulltext searches can be slow, so if your database is very large or if you run this query a lot, you will want to find an optimized solution, such as Sphinx (http://sphinxsearch.com).

Body:
As an entry point, you can use MySQL LIKE queries.

For example if you have a table 'comments' with a column named 'comment', and you want to find all comments that contain the word 'red', use:

SELECT comment FROM comments WHERE comment LIKE '% red %';

Please note that fulltext searches can be slow, so if your database is very large or if you run this query a lot, you will want to find an optimized solution, such as Sphinx (http://sphinxsearch.com).


问:
How create data structure with similar numpy nd array
i have next function:

```<code>def check_smaller_zeros(v):
   return v < 0
</code>```

When i create array with numpy i can write next code for element-by-element measurement:

```<code>v_1 = numpy.array([1, 2, -4, -1])
result = check_smaller_zeros(v_1)
# result: [False, False, True, True]
</code>```

but when i try repeat it with tuple, set, frozenset and list/array reise next error:

```<code>TypeError: '<' not supported between instances of 'tuple' and 'int'
</code>```

what exactly allows numpy array to have the capability for this behavior? This looks convenient, but is a bit non-obvious

答:
Python allows you to override operators with special "dunder" (double underscore) methods.  For example, let's make a custom data structure that inherits from tuple.  To make < perform item-wise comparisons, we simply need to overwrite the __lt__ method.

```<code>In [1]: class MyList(tuple):
      :     def __lt__(self, other):
      :         return tuple(v < other for v in self)
      :

In [1]:

In [2]: l = MyList([1,2,3,4,5])

In [3]: l < 3
Out[3]: (True, True, False, False, False)
</code>```

A list of all such methods can be found in the Python documentation under Data Model.

Body:
i have next function:

def check_smaller_zeros(v):
   return v < 0

When i create array with numpy i can write next code for element-by-element measurement:

v_1 = numpy.array([1, 2, -4, -1])
result = check_smaller_zeros(v_1)
# result: [False, False, True, True]

but when i try repeat it with tuple, set, frozenset and list/array reise next error:

TypeError: '<' not supported between instances of 'tuple' and 'int'

what exactly allows numpy array to have the capability for this behavior? This looks convenient, but is a bit non-obvious

Body:
Python allows you to override operators with special "dunder" (double underscore) methods.  For example, let's make a custom data structure that inherits from tuple.  To make < perform item-wise comparisons, we simply need to overwrite the __lt__ method.

In [1]: class MyList(tuple):
      :     def __lt__(self, other):
      :         return tuple(v < other for v in self)
      :

In [1]:

In [2]: l = MyList([1,2,3,4,5])

In [3]: l < 3
Out[3]: (True, True, False, False, False)

A list of all such methods can be found in the Python documentation under Data Model.


问:
cmd := exec.Command("ssh", "ec2-user@publicip") exits with Permission denied (publickey,gssapi-keyex,gssapi-with-mic)
I'm using org/x/crypto/ssh package to build a cli application to ssh through bastion to a server using ssh certs. Basic workflow is;
cli tool gets the users public key  and get it signed from vault ssh ca, and that resulting cert is used to authenticate the user to the servers.
It worked fine.

```<code>configure := &ssh.ClientConfig{
            User: "ec2-user",
            Auth: []ssh.AuthMethod{
                // Use the PublicKeys method for remote authentication.
                ssh.PublicKeys(certSigner),
            },
            HostKeyCallback: ssh.InsecureIgnoreHostKey(),
        }
        //log.Println(config.bastionserver.publicIP)

        // Connect to the remote server and perform the SSH handshake.
        proxyClient, err := ssh.Dial("tcp", net.JoinHostPort(config.bastion.publicIP, "22"), configure)
        if err != nil {
            log.Fatalln(err)
        }

        session, err := proxyClient.NewSession()
        if err != nil {
            log.Fatalln(err)
        }
        defer session.Close()

        if err = session.Shell(); err != nil {
            log.Fatalln(err)
        }

        session.Wait()
</code>```

I made some changes and reverted back to the code and I started getting the following error. I used git to revert.

ssh: handshake failed: ssh: unable to authenticate, attempted methods [publickey none], no supported methods remain

So I reduced the complexity and tried the following block to try to connect just to the bastion through the cli app I'm building.

```<code>cmd := exec.Command("ssh", "-i", signedKeyPath, "-i", privateKeyPath, "ec2-user@host")

    fmt.Println(cmd.String())
    cmd.Stdin = os.Stdin
    cmd.Stdout = os.Stdout
    cmd.Stderr = os.Stderr
    err = cmd.Run()
    if err != nil {
        log.Fatalln(err)
    }
</code>```

still it exits with

/usr/bin/ssh -i /home/rochana/.ssh/id_rsa-cert.pub -i /home/rochana/.ssh/id_rsa ec2-user@host
  ec2-user@host: Permission denied (publickey,gssapi-keyex,gssapi-with-mic).
  2020-02-17 11:01:25.168548 I | exit status 255.

I tried compiling and running it on a different PC and I get the same results. I tried saving the cert to disk and giving the path.

but if I run the same command on terminal. It works fine and connects to the instance.

ssh -i ~/.ssh/id_rsa-cert.pub -i ~/.ssh/id_rsa ec2-user@host

or just copy and paste cmd.String() output

/usr/bin/ssh -i /home/rochana/.ssh/id_rsa-cert.pub -i /home/rochana/.ssh/id_rsa ec2-user@host

everything works fine when I run directly on terminal but not with exec command

答: The error was due to, Vault server not being able to sync up its time. </p>

Body:
I'm using org/x/crypto/ssh package to build a cli application to ssh through bastion to a server using ssh certs. Basic workflow is;
cli tool gets the users public key  and get it signed from vault ssh ca, and that resulting cert is used to authenticate the user to the servers.
It worked fine.

configure := &ssh.ClientConfig{
            User: "ec2-user",
            Auth: []ssh.AuthMethod{
                // Use the PublicKeys method for remote authentication.
                ssh.PublicKeys(certSigner),
            },
            HostKeyCallback: ssh.InsecureIgnoreHostKey(),
        }
        //log.Println(config.bastionserver.publicIP)

        // Connect to the remote server and perform the SSH handshake.
        proxyClient, err := ssh.Dial("tcp", net.JoinHostPort(config.bastion.publicIP, "22"), configure)
        if err != nil {
            log.Fatalln(err)
        }

        session, err := proxyClient.NewSession()
        if err != nil {
            log.Fatalln(err)
        }
        defer session.Close()

        if err = session.Shell(); err != nil {
            log.Fatalln(err)
        }

        session.Wait()

I made some changes and reverted back to the code and I started getting the following error. I used git to revert.

ssh: handshake failed: ssh: unable to authenticate, attempted methods [publickey none], no supported methods remain

So I reduced the complexity and tried the following block to try to connect just to the bastion through the cli app I'm building.

cmd := exec.Command("ssh", "-i", signedKeyPath, "-i", privateKeyPath, "ec2-user@host")

    fmt.Println(cmd.String())
    cmd.Stdin = os.Stdin
    cmd.Stdout = os.Stdout
    cmd.Stderr = os.Stderr
    err = cmd.Run()
    if err != nil {
        log.Fatalln(err)
    }

still it exits with

/usr/bin/ssh -i /home/rochana/.ssh/id_rsa-cert.pub -i /home/rochana/.ssh/id_rsa ec2-user@host
  ec2-user@host: Permission denied (publickey,gssapi-keyex,gssapi-with-mic).
  2020-02-17 11:01:25.168548 I | exit status 255.

I tried compiling and running it on a different PC and I get the same results. I tried saving the cert to disk and giving the path.

but if I run the same command on terminal. It works fine and connects to the instance.

ssh -i ~/.ssh/id_rsa-cert.pub -i ~/.ssh/id_rsa ec2-user@host

or just copy and paste cmd.String() output

/usr/bin/ssh -i /home/rochana/.ssh/id_rsa-cert.pub -i /home/rochana/.ssh/id_rsa ec2-user@host

everything works fine when I run directly on terminal but not with exec command


问:
Does dart allows users to write platform specific implementation?
If not - are there are any plans to make it so?

I know that dart itself has different backends that might have different implementation. I was curious if users can do the same, e.g. have a function that delegates to one @patch for js runtime and to another @patch in case of dart vm.

答:
The way to make platform specific code (or rather platform library specific code) is to use conditional imports.

The syntax is:

import "helper_default.dart"
  if (dart.library.js) "helper_js.dart"
  if (dart.library.io) "helper_io.dart";
```

<p>This import statement will import one of three libraries. If the <code>dart:js</code> library is available on the platform you are compiling for, you will import <code>helper_js.dart</code>. If not, and <code>dart:io</code> is available, then you will import <code>helper_io.dart</code>. If that's also not there, you will import <code>helper_default.dart</code>.</p>

<p>The trick is then to have the same library API implemented in all three libraries, but based only on the available platform library.
The <code>helper_js.dart</code> library can implement something using <code>dart:js</code> and <code>helper_io.dart</code> can import <code>dart:io</code>. The default library will likely not be able to do anything useful, so it might just throw an <code>UnsupportedError</code> if you try to use it.</p>

<p>The code in the importing library must be valid for all three imports, which is why they must have "the same" API. That might include declaring a class, but you'd usually define the interface of that class in a non-platform dependent library that the three implementations can share, to ensure that they actually have the same interface.</p>

<p>Example:</p>

<pre class="lang-dart prettyprint-override"><code>library mypkg.shared_types;
import "helper_default.dart"
  if (dart.library.js) "helper_js.dart"
  if (dart.library.io) "helper_io.dart"
  as helper;

class SharedClass {
  factory SharedClass(int something) = helper.SharedClassImpl;
  int get value;
}
</code>```

and

library mypkg.helper_io;
import "dart:io";
import "shared_types.dart";
class SharedClassImpl implements SharedClass {
  int _id;
  SharedClassImpl(this._id);
  int get value { // Something depending on dart:io.
    var bytes = File("pathToSomething-$id").readAsBytesSync();
    return bytes[0];
  }
}
```

Body:
The way to make platform specific code (or rather platform library specific code) is to use conditional imports.

The syntax is:

import "helper_default.dart"
  if (dart.library.js) "helper_js.dart"
  if (dart.library.io) "helper_io.dart";

This import statement will import one of three libraries. If the dart:js library is available on the platform you are compiling for, you will import helper_js.dart. If not, and dart:io is available, then you will import helper_io.dart. If that's also not there, you will import helper_default.dart.

The trick is then to have the same library API implemented in all three libraries, but based only on the available platform library.
The helper_js.dart library can implement something using dart:js and helper_io.dart can import dart:io. The default library will likely not be able to do anything useful, so it might just throw an UnsupportedError if you try to use it.

The code in the importing library must be valid for all three imports, which is why they must have "the same" API. That might include declaring a class, but you'd usually define the interface of that class in a non-platform dependent library that the three implementations can share, to ensure that they actually have the same interface.

Example:

library mypkg.shared_types;
import "helper_default.dart"
  if (dart.library.js) "helper_js.dart"
  if (dart.library.io) "helper_io.dart"
  as helper;

class SharedClass {
  factory SharedClass(int something) = helper.SharedClassImpl;
  int get value;
}

and

library mypkg.helper_io;
import "dart:io";
import "shared_types.dart";
class SharedClassImpl implements SharedClass {
  int _id;
  SharedClassImpl(this._id);
  int get value { // Something depending on dart:io.
    var bytes = File("pathToSomething-$id").readAsBytesSync();
    return bytes[0];
  }
}


问:
Copying a filtered data from a table set and paste it on the next empty row of another sheet
I tried to copy a set of filtered data from the worksheet "PEP" (Filter: Emetteurs, in column 18) and paste it in the next empty row in the worksheet"Sanctions". I found this text code online and add the section NextRow in order to paste it on the next Empty Row in the "Sanctions" Worksheet. I just started using VBA not long ago, so I tried to use codes online however in this case, I think the problem here is that I cannot define the value of range. I tried to look it up online but no result. Thank you in advance for all your help!

```<code>Dim k,j,i As Interger
ActiveWorkbook.Sheets("Sanctions").Select
NextRow=Cells(Range("A"&Rows.Count).End(xlUp).Row+1,1

k=1
With sheets("PEP")
 T=.Range("A1:AS"&.Cells(Rows.Count,1).End(xlUp).Row)
 .Rows(1).Copy Sheets("Sanctions").Range("NextRow")
End With

For i=2 To UBound(T,1)
 If T(i,18)="Emetteurs" Then
   k=k+1
   For j =1 to UBound(T,2)
    T(k,j)=T(i,j)
   Next j
 End If

Next i
With Sheets("Sanctions")
 Application.ScreenUpdating=False
 .Range("NextRow").Resiwe(k,UBound(T,2))=T.Offset(1)
 .Columns.AutoFit
 Application.ScreenUpdating=True
End With
End Sub
</code>```

And if possible I would also like to find a solution to remove the header once I do the Copy-Paste process.

答:
Read the code's comments and adjust it to fit your needs.

Some things to begin:

Use option explicit so you don't have unexpected behavior with undefined variables

Always indent your code (see www.rubberduckvba.com a free tool that helps you with that)

Try to separate your logic defining variables and the reusing them

EDIT: Some reviews to your code:

As mentioned by @Pᴇʜ you need to declare each of your variables types.

This:

```<code>Dim k,j,i As Interger
</code>```

is the same as declaring:

```<code>Dim k As Variant
Dim j As Variant
Dim i As Integer
</code>```

Side note. You had a typo in Interger

Which is not what you really want, knowing that all of them are going to store numbers

Declare the objects that you're going to work with. For example, you refer to the sheet Sanctions three times in your code:

```<code>ActiveWorkbook.Sheets("Sanctions")
</code>```

This can be set once like this:

```<code>Set targetSheet = ThisWorkbook.Worksheets("Sanctions")
</code>```

And then reused in lines like this:

```<code>With Sheets("Sanctions")
</code>```

or this:

```<code>Sheets("Sanctions").Range("NextRow")
</code>```

by writing this:

```<code>With targetSheet
</code>```

in this way, if you ever need to change it (the person working with your code, or your future you will be really thankful)

Declaring your variables to just letters, makes your code really hard to understand.

```<code>Dim j,k,l
</code>```

is different when you have:

```<code>Dim lastRow As Long
Dim lastColumn As Long
etc.
</code>```

I suggest that you use the key F8 and step through the code, and see the logic behind it. That way you can learn more.

Code:

```<code>Public Sub ConditionalRowCopy()

    ' Declare object variables
    Dim sourceSheet As Worksheet
    Dim targetSheet As Worksheet
    Dim cell As Range

    ' Declare other variables
    Dim sourceLastRow As Long
    Dim targetLastRow As Long

    ' Set a reference to the sheets so you can access them later
    Set sourceSheet = ThisWorkbook.Worksheets("PEP")
    Set targetSheet = ThisWorkbook.Worksheets("Sanctions")

    ' Find last row in source sheet based on column "R"
    sourceLastRow = sourceSheet.Cells(sourceSheet.Rows.Count, "R").End(xlUp).Row

    ' Find cell with word "Emetteurs", search in column R)
    For Each cell In sourceSheet.Range("R1:R" & sourceLastRow).Cells

        ' If match
        If cell.Value = "Emetteurs" Then
            ' Find last row in target sheet based on column "A"
            targetLastRow = targetSheet.Cells(targetSheet.Rows.Count, "A").End(xlUp).Row
            ' Copy entire row to next empty row in target sheet
            cell.EntireRow.Copy Destination:=targetSheet.Range("A" & targetLastRow).Offset(RowOffset:=1)
        End If

    Next cell

End Sub
</code>```

Let me know if it works!

Body:
I tried to copy a set of filtered data from the worksheet "PEP" (Filter: Emetteurs, in column 18) and paste it in the next empty row in the worksheet"Sanctions". I found this text code online and add the section NextRow in order to paste it on the next Empty Row in the "Sanctions" Worksheet. I just started using VBA not long ago, so I tried to use codes online however in this case, I think the problem here is that I cannot define the value of range. I tried to look it up online but no result. Thank you in advance for all your help!

Dim k,j,i As Interger
ActiveWorkbook.Sheets("Sanctions").Select
NextRow=Cells(Range("A"&Rows.Count).End(xlUp).Row+1,1

k=1
With sheets("PEP")
 T=.Range("A1:AS"&.Cells(Rows.Count,1).End(xlUp).Row)
 .Rows(1).Copy Sheets("Sanctions").Range("NextRow")
End With

For i=2 To UBound(T,1)
 If T(i,18)="Emetteurs" Then
   k=k+1
   For j =1 to UBound(T,2)
    T(k,j)=T(i,j)
   Next j
 End If

Next i
With Sheets("Sanctions")
 Application.ScreenUpdating=False
 .Range("NextRow").Resiwe(k,UBound(T,2))=T.Offset(1)
 .Columns.AutoFit
 Application.ScreenUpdating=True
End With
End Sub

And if possible I would also like to find a solution to remove the header once I do the Copy-Paste process.

Body:
Read the code's comments and adjust it to fit your needs.

Some things to begin:

Use option explicit so you don't have unexpected behavior with undefined variables

Always indent your code (see www.rubberduckvba.com a free tool that helps you with that)

Try to separate your logic defining variables and the reusing them

EDIT: Some reviews to your code:

As mentioned by @Pᴇʜ you need to declare each of your variables types.

This:

Dim k,j,i As Interger

is the same as declaring:

Dim k As Variant
Dim j As Variant
Dim i As Integer

Side note. You had a typo in Interger

Which is not what you really want, knowing that all of them are going to store numbers

Declare the objects that you're going to work with. For example, you refer to the sheet Sanctions three times in your code:

ActiveWorkbook.Sheets("Sanctions")

This can be set once like this:

Set targetSheet = ThisWorkbook.Worksheets("Sanctions")

And then reused in lines like this:

With Sheets("Sanctions")

or this:

Sheets("Sanctions").Range("NextRow")

by writing this:

With targetSheet

in this way, if you ever need to change it (the person working with your code, or your future you will be really thankful)

Declaring your variables to just letters, makes your code really hard to understand.

Dim j,k,l

is different when you have:

Dim lastRow As Long
Dim lastColumn As Long
etc.

I suggest that you use the key F8 and step through the code, and see the logic behind it. That way you can learn more.

Code:

Public Sub ConditionalRowCopy()

    ' Declare object variables
    Dim sourceSheet As Worksheet
    Dim targetSheet As Worksheet
    Dim cell As Range

    ' Declare other variables
    Dim sourceLastRow As Long
    Dim targetLastRow As Long

    ' Set a reference to the sheets so you can access them later
    Set sourceSheet = ThisWorkbook.Worksheets("PEP")
    Set targetSheet = ThisWorkbook.Worksheets("Sanctions")

    ' Find last row in source sheet based on column "R"
    sourceLastRow = sourceSheet.Cells(sourceSheet.Rows.Count, "R").End(xlUp).Row

    ' Find cell with word "Emetteurs", search in column R)
    For Each cell In sourceSheet.Range("R1:R" & sourceLastRow).Cells

        ' If match
        If cell.Value = "Emetteurs" Then
            ' Find last row in target sheet based on column "A"
            targetLastRow = targetSheet.Cells(targetSheet.Rows.Count, "A").End(xlUp).Row
            ' Copy entire row to next empty row in target sheet
            cell.EntireRow.Copy Destination:=targetSheet.Range("A" & targetLastRow).Offset(RowOffset:=1)
        End If

    Next cell

End Sub

Let me know if it works!


问:
ordering a list in C#
I have a list of Employee objects .Employee Class can be as below:

```<code>Class Emplyoyee
{
    public string name;
    public string DateOFJoining; //Please note here date is in string format
}
</code>```

Now i want to display the list of employee with latest employee on top so am using below code for it :

```<code>List<Employee> lst = GetEmployes();
lst = lst.OrderByDescending(x => x.DateOFJoining).ToList();

//Here binding to the repeater
rptEmp.DataSource = lst.Take(2);
rptEmp.DataBind();
</code>```

Problem: Here its ordering treating date as string .But i want to order by date.Can anyone help me on this?

Thanks in advance.

答:
You can have Employee implement the System.IComparable interface. and then just use the List.Sort() method to order the employees.

for example:

```<code>Class Employee : IComparable
{
    public string name;
    public string DateOFJoining; //Please note here date is in string format

    public int CompareTo(object obj) {
        if(obj is Employee) {
            Employee= (Employee) obj;

            return Convert.ToDateTime(DateOfJoining).CompareTo(Convert.ToDateTime(e.DateOfJoining));
        }

        throw new ArgumentException("object is not an Employee");
    }
}
</code>```

Title: ordering a list in C#

Body:
I have a list of Employee objects .Employee Class can be as below:

Class Emplyoyee
{
    public string name;
    public string DateOFJoining; //Please note here date is in string format
}

Now i want to display the list of employee with latest employee on top so am using below code for it :

List<Employee> lst = GetEmployes();
lst = lst.OrderByDescending(x => x.DateOFJoining).ToList();

//Here binding to the repeater
rptEmp.DataSource = lst.Take(2);
rptEmp.DataBind();

Problem: Here its ordering treating date as string .But i want to order by date.Can anyone help me on this?

Thanks in advance.

Body:
You can have Employee implement the System.IComparable interface. and then just use the List.Sort() method to order the employees.

for example:

Class Employee : IComparable
{
    public string name;
    public string DateOFJoining; //Please note here date is in string format

    public int CompareTo(object obj) {
        if(obj is Employee) {
            Employee= (Employee) obj;

            return Convert.ToDateTime(DateOfJoining).CompareTo(Convert.ToDateTime(e.DateOfJoining));
        }

        throw new ArgumentException("object is not an Employee");
    }
}


问:
Why do I receive error 1241 when trying to Create and Insert data into a new table (on phpMyAdmin)?
I am trying to create a new table and insert values into it however I keep receiving "#1241 - Operand should contain 1 column(s)".
Please could someone help to identify what is wrong with my code as I am unsure what this error is referencing?

The code I am inserting into the phpMyAdmin database under the SQL tab. I have tried to remove the auto increment attributes and have tried looking at other examples to check my syntax, but I can't spot the issue. Some guidance on this would be greatly appreciated.

The code I entered begins like this:

```<code># AppSoft Project - Greg Roberts

DROP table if exists Department;
DROP table if exists Role;
DROP table if exists User;
DROP table if exists Appraisal;
DROP table if exists Question;
DROP table if exists Answer;

CREATE table Department(
    DeptID int NOT NULL AUTO_INCREMENT,
    DeptName varchar(30) NOT NULL,
    primary key (DeptID));

INSERT into Department values(
    (00, 'SuperAdmin'),
    (01, 'Support Staff'),
    (02, 'Teaching Staff'),
    (03, 'SLT'));

CREATE table Role(
    RoleID int NOT NULL AUTO_INCREMENT,
    RoleTitle varchar(30) NOT NULL,
    primary key (RoleID));

INSERT into Role values(
    (00, 'SuperAdmin'),
    (01, 'Office Administrator'),
    (02, 'Teaching Partner'),
    (03, 'Mid Day Supervisor'),
    (04, 'Cooks'),
    (05, 'Cleaners'),
    (06, 'Maintenance'),
    (07, 'Teacher'),
    (08, 'Department Head'),
    (09, 'SENCO'),
    (10, 'Head Teacher'),
    (11, 'Executive Head'));
</code>```

Error Code that Occurs

答:
You dont need to insert primary keys, if they are set to auto_increment.

```<code>DeptID int NOT NULL AUTO_INCREMENT
</code>```

Just insert the department name, there are no additional braces required for Values.

```<code>INSERT into Department( DeptName) values
('SuperAdmin'),
('Support Staff'),
('Teaching Staff'),
('SLT');
</code>```

You would need to do the same for Role table as well.

Also if you try to insert 0 into the primary key, it will actually insert 1 you can read about it in the Standard Docs

you seem to be getting the error because your first record inserts 1 into the table and then your second record tries to insert 1 again in the primary key column

Body:
I am trying to create a new table and insert values into it however I keep receiving "#1241 - Operand should contain 1 column(s)".
Please could someone help to identify what is wrong with my code as I am unsure what this error is referencing?

The code I am inserting into the phpMyAdmin database under the SQL tab. I have tried to remove the auto increment attributes and have tried looking at other examples to check my syntax, but I can't spot the issue. Some guidance on this would be greatly appreciated.

The code I entered begins like this:

# AppSoft Project - Greg Roberts

DROP table if exists Department;
DROP table if exists Role;
DROP table if exists User;
DROP table if exists Appraisal;
DROP table if exists Question;
DROP table if exists Answer;

CREATE table Department(
    DeptID int NOT NULL AUTO_INCREMENT,
    DeptName varchar(30) NOT NULL,
    primary key (DeptID));

INSERT into Department values(
    (00, 'SuperAdmin'),
    (01, 'Support Staff'),
    (02, 'Teaching Staff'),
    (03, 'SLT'));

CREATE table Role(
    RoleID int NOT NULL AUTO_INCREMENT,
    RoleTitle varchar(30) NOT NULL,
    primary key (RoleID));

INSERT into Role values(
    (00, 'SuperAdmin'),
    (01, 'Office Administrator'),
    (02, 'Teaching Partner'),
    (03, 'Mid Day Supervisor'),
    (04, 'Cooks'),
    (05, 'Cleaners'),
    (06, 'Maintenance'),
    (07, 'Teacher'),
    (08, 'Department Head'),
    (09, 'SENCO'),
    (10, 'Head Teacher'),
    (11, 'Executive Head'));

Error Code that Occurs

Body:
You dont need to insert primary keys, if they are set to auto_increment.

DeptID int NOT NULL AUTO_INCREMENT

Just insert the department name, there are no additional braces required for Values.

INSERT into Department( DeptName) values
('SuperAdmin'),
('Support Staff'),
('Teaching Staff'),
('SLT');

You would need to do the same for Role table as well.

Also if you try to insert 0 into the primary key, it will actually insert 1 you can read about it in the Standard Docs

you seem to be getting the error because your first record inserts 1 into the table and then your second record tries to insert 1 again in the primary key column


问:
When do Redis PUB/SUB events fire-and-forget?
Redis events are fire-and-forget. If no one is listening, they will just remain undetected. There's no history. But nowhere on the internet did I find anything that answers the following question (I'm using redis-py and aioredis for python):

Does the code actually need to LISTEN to the events to receive it or will the redis connection cache events for me?

Let's suppose I have this loop:

```<code>redis_db = Redis(...)

while True:
    print("Hey, I'm listening now!")
    msg = redis_db.blocking_subscribe("some_topic") # pseudo-code, because I'm using various libraries
    if msg == "calc":
        do_a_heavy_5_seconds_calculation()
        print("YAY, I was busy and am back up now!")
</code>```

So will I miss all events that occur in the 5s calculation or will my redis_db cache them for me?

In other words... does fire-and-forget apply if I don't have a connection or if I have a connection, but am not listening ?

答:
"Fire and forget" applies to the server's contract with the client. It means that the message will be sent only once, assuming that the client is connected. If the message is lost in the network and never gets to the client, then that's that. If the message gets to the client and the client process/server crashes before reading it, then that's that.

In your case, the client (redis-py) listens to the network socket that makes the connection to the server. The socket itself is handled by the OS and buffers the incoming messages. As long as you keep draining the socket by reading from it messages aren't lost.

Body:
Redis events are fire-and-forget. If no one is listening, they will just remain undetected. There's no history. But nowhere on the internet did I find anything that answers the following question (I'm using redis-py and aioredis for python):

Does the code actually need to LISTEN to the events to receive it or will the redis connection cache events for me?

Let's suppose I have this loop:

redis_db = Redis(...)

while True:
    print("Hey, I'm listening now!")
    msg = redis_db.blocking_subscribe("some_topic") # pseudo-code, because I'm using various libraries
    if msg == "calc":
        do_a_heavy_5_seconds_calculation()
        print("YAY, I was busy and am back up now!")

So will I miss all events that occur in the 5s calculation or will my redis_db cache them for me?

In other words... does fire-and-forget apply if I don't have a connection or if I have a connection, but am not listening ?


问:
Slicing NumPy array representing nested list
I'm familiar with slicing, I just can't wrap my head around this, and I've tried changing some of the values to try and illustrate what's going on, but it makes no sense to me.

Here's the example:

```<code>import numpy
l = numpy.array([[0, 0, 0], [0, 1, 0], [1, 0, 0], [1, 1, 1]])
print(l[:,0:2].tolist())
</code>```

Resulting in:

```<code>[[0, 0], [0, 1], [1, 0], [1, 1]]
</code>```

I'm trying to translate this as "slice from index 0 to 0,2, incrementing by 2" which makes no sense to me.

答:
The following should work for ordinary lists.  Assuming that it is a list of lists,
and all the sublists are of the same length, then you can do this (python 2)

```<code>A = [[1, 2], [3, 4], [5, 6]]
print (f"A = {A}")

flatA = sum(A, [])     # Flattens the 2D list
print (f"flatA = {flatA}")
len0 = len(A[0])
lenall = len(flatA)
B = [flatA[i:lenall:len0] for i in range(len0)]
print (f"B = {B}")
</code>```

Output will be:

```<code>A = [[1, 2], [3, 4], [5, 6]]
flatA = [1, 2, 3, 4, 5, 6]
B = [[1, 3, 5], [2, 4, 6]]
</code>```

Body:
I'm familiar with slicing, I just can't wrap my head around this, and I've tried changing some of the values to try and illustrate what's going on, but it makes no sense to me.

Here's the example:

import numpy
l = numpy.array([[0, 0, 0], [0, 1, 0], [1, 0, 0], [1, 1, 1]])
print(l[:,0:2].tolist())

Resulting in:

[[0, 0], [0, 1], [1, 0], [1, 1]]

I'm trying to translate this as "slice from index 0 to 0,2, incrementing by 2" which makes no sense to me.

Body:
The following should work for ordinary lists.  Assuming that it is a list of lists,
and all the sublists are of the same length, then you can do this (python 2)

A = [[1, 2], [3, 4], [5, 6]]
print (f"A = {A}")

flatA = sum(A, [])     # Flattens the 2D list
print (f"flatA = {flatA}")
len0 = len(A[0])
lenall = len(flatA)
B = [flatA[i:lenall:len0] for i in range(len0)]
print (f"B = {B}")

Output will be:

A = [[1, 2], [3, 4], [5, 6]]
flatA = [1, 2, 3, 4, 5, 6]
B = [[1, 3, 5], [2, 4, 6]]