text:
Q: Save image as 24 bit png Is there a way to save an image as 24 bit png? I didn't manage with GIMP.
Keep in mind this is pixel art so keeping the exact colors are important.
I tried several things in GIMP, but it always said this:
$ file Junction.png
Junction.png: PNG image data, 160 x 60, 8-bit/color RGBA, non-interlaced

Instead of 24 bit.

A: Your problem is that you don't understand the output of the file command.  I used Paint.NET to save an image as 32-bit PNG, 24-bit PNG, and 8-bit PNG.  Then I ran the file command on them:
$ file *bit.png
08-bit.png: PNG image data, 800 x 600, 8-bit colormap, non-interlaced
24-bit.png: PNG image data, 800 x 600, 8-bit/color RGB, non-interlaced
32-bit.png: PNG image data, 800 x 600, 8-bit/color RGBA, non-interlaced

As you can see 8-bit/color RGBA is actually what Paint.NET calls a 32-bit PNG, because it's 8 bits per color * (3 colors + 1 alpha channel).  8 * 4 = 32.  A 24-bit PNG is the same, but without the alpha channel: 8 * 3 = 24.
If you want what Paint.NET calls a 24-bit PNG, you need to remove the alpha channel.  As far as I can tell, GIMP always exports a PNG with an alpha channel if any of your layers has an alpha channel.
If you're only using 1 layer, then it's simple: Go to Layer > Transparency > Remove Alpha Channel and then export.  You'll get a 24-bit PNG.
If you're using multiple layers and need transparency effects, then jthill pointed out that you can use Image > Flatten Image to remove the layers with transparency before exporting.  You can then Undo to restore the layers.
You can also post-process the exported PNG to remove the alpha channel.  You could load the exported image back into GIMP, which will make it 1 layer, remove the alpha channel from that layer, and export again.  A better way is to use optipng, which will usually compress a PNG better than GIMP can in addition to removing a useless alpha channel.

A: NOTE: If you're looking for 16-bits per channel support then this answer applies to that. Otherwise if you're miss understanding 24-bit support (8-bit * 3 colors (RGB) = 24-bits, then see @cjm's answer as to how to understand how that works.

From the GIMP FAQ:
excerpt

When can we see 16-bit per channel support (or better)?
For some industries, especially photography, 24-bit colour depths (8 bits per channel) are a real barrier to entry. Once again, it's GEGL to the rescue. Work on integrating GEGL into GIMP began after 2.4 was released, and will span across several stable releases. This work will be completed in GIMP 3.0, which will have full support for high bit depths. If you need such support now and can't wait, cinepaint and Krita support 16 bits per channel now.
The current development branch, GIMP 2.9.x, supports higher bit depths than the 2.8 and older 8-Bit-per-component...

In case you're not familiar with GEGL:
excerpt

GEGL (Generic Graphics Library) is a graph based image processing framework.
GEGL provides infrastructure to do demand based cached non destructive image editing on larger than RAM buffers. Through babl it provides support for a wide range of color models and pixel storage formats for input and output.
Features

*

*Floating point handling and processing and output of larger 8bit, 16bit integer and 32bit floating

*....

A: Image->Flatten
File->Export
Edit->Undo

~/Documents$ file Untitled.png
Untitled.png: PNG image data, 640 x 400, 8-bit/color RGB, non-interlaced


text:
Q: Maximizing "log det + log sum exp" function I'm trying to find a numerical solution to the following optimization problem
$$
\text{maximize } f(M) = \frac{1}{2} \log \det(M) + \log  \sum_{i=1}^n \exp \left\{ - \frac{1}{2} x_i^T M x_i + a_i \right\} \\
\text{subject to } M \preceq A,
$$
where $A, x_i, a_i$ are all given. Unfortunately, log-det is concave and log-sum-exp is convex.
Edit: I think some background might help. The origin of the objective function is the following function
$$
f(V) = \sum_{i=1}^n w_i \, \mathcal{N}(x_i | \, 0, V)
$$
where $\mathcal{N}(x_i| \, 0, V)$ is the density of a multivariate normal distribution with mean 0 and covariance matrix $V$ (then I took the log to see if that helped). I basically want to find $V$ that maximizes the expression above subject to a constraint.
Any pointers or references to any algorithm or heuristic would be much appreciated, thanks!

A: You made mistake taking logariphm from multivariate likelihood. $\log(\det(M)$ should go with the minus sign.Thus everything is convex.Derivative of $\log(det(M)^\prime_M=M^{-1}$. Additionally it must be mulitplier $N$ here.
Derivative of $\sum_i x_i^TMx=\sum x_ix_i^T$. So you final optimal solution will be $M= (\sum x_ix_i^T/N)^{-1}$ - the inverse of covariance matrix as it should be.
EDITION. I made mistake because forgot that $M$ is inverse of covariance matrix. So $\log(det(M)$ comes with the correct sign. However, likelihood is a product of exponents and loglikelihood is logarihtm of product of exponents rather the logarithm of sum exponents. So fianlly you jave concave + linear function which has the perfect maximum.
This is a wrong idea to make summation of logarithm of distributions. We have to take the logarithm of product with leads to sum of logarithms.
More precisely the correct way to look for optimal covariance matrix is try to maximize of $\Sigma$ the following mulitvariate loglikelihood
$$
  \prod_i \frac{1}{\sqrt{(2\pi)^k|\boldsymbol\Sigma|}} \exp\left(-\frac{1}{2}{\mathbf x_i}^T{\boldsymbol\Sigma}^{-1}{\mathbf x_i} \right),
$$
If your have weights then
$$
  \prod_i \frac{1}{\sqrt{(2\pi)^k|\boldsymbol\Sigma|^{w_i}}} \exp\left(-w_i\frac{1}{2}{\mathbf x_i}^T{\boldsymbol\Sigma}^{-1}{\mathbf x_i} \right),
$$
Taking logarithm you will get the weighted loglikelihood.

A: Seems similar to the covariance update for the mixture of Gaussians model. Standard method is to use expectation-maximization (EM). It would be maximizing a lower bound, and only finds a local maximum.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Angular ERROR: Access denied for user 'root'@'localhost' (usining password: NO) I work on Angular Project and trying to connect mysql Database using npx sequelize db:migrate
but run command after some error (Angular ERROR: Access denied for user 'root'@'localhost' (usining password: NO))
Database and password is perfect my .env and  config.js file
config.js
require('dotenv').config();
moduleexports ={
    "development": {
        "username": process.env.DB_USERNAME,
        "password": process.env.DB_PASSWORD,
        "database": process.env.DB_DATABASE,
        "host": process.env.DB_HOST,
        "dialect": "mysql"
    },
    "test":{
        "username": "root",
        "password": null,
        "database": "database_test",
        "host": 127.0.0.1,
        "dialect": "mysql"
    }

    "production":{
        "username": "root",
        "password": null,
        "database": "database_producting",
        "host": 127.0.0.1,
        "dialect": "mysql"
    }
}

.env
NODE_ENV=development
DB_HOST=127.0.0.1
DB_DATABASE=banner_automation
DB_USERNAME=root
DB_PASSWORD=


text:
Q: magento install gets to a 500 error I am facing a issue while trying to install magento.
I am getting the following error:
Fatal error: Uncaught Error: Function name must be a string in /var/www/html/magento/app/code/core/Mage/Core/Model/Layout.php:555
Stack trace:
#0 /var/www/html/magento/app/code/core/Mage/Core/Controller/Varien/Action.php(390): Mage_Core_Model_Layout->getOutput()
#1 /var/www/html/magento/app/code/core/Mage/Install/controllers/WizardController.php(120): Mage_Core_Controller_Varien_Action->renderLayout()
#2 /var/www/html/magento/app/code/core/Mage/Core/Controller/Varien/Action.php(419): Mage_Install_WizardController->beginAction()
#3 /var/www/html/magento/app/code/core/Mage/Core/Controller/Varien/Router/Standard.php(250): Mage_Core_Controller_Varien_Action->dispatch('begin')
#4 /var/www/html/magento/app/code/core/Mage/Core/Controller/Varien/Front.php(176): Mage_Core_Controller_Varien_Router_Standard->match(Object(Mage_Core_Controller_Request_Http))
#5  /var/www/html/magento/app/code/core/Mage/Core/Model/App.php(354): Mage_Core_Controller_Varien_Front->dispatch()
#6 /var/www/html/magento/app/Mage.php(682): Mage_Core_Model_App- in /var/www/html/magento/app/code/core/Mage/Core/Model/Layout.php on line 555

Configuration details:

*

*OS: ubuntu 15.10

*Apache: 2.4.18

*php: 7.0.2

*mysql: 5.7.10

A: Magento 1.x is not fully compatible with PHP 7, see: Is Magento ready for PHP 7?
This specific bug can be fixed, by overriding Mage_Core_Model_Layout and change line 555 from:
$out .= $this->getBlock($callback[0])->$callback[1]();

to
$out .= $this->getBlock($callback[0])->{$callback[1]}();


text:
Q: Flutter TabBar: Update tab (stateful widget) everytime a tab gets visible happy new year! :)
I have three tabs, each holding a stateful widget. The data presented in tab #2 could be changed by the user within tab #3. Thus, when moving back from tab #3 to tab #2, I need to call an update() method within tab #2. Is there a stateful widget method that gets fired everytime the widget gets visible? If not, what opporutinites do I have in order to achieve this?
Best, Nico

A: The reason it's not updating is due to the widget already been rendered and now cached until the user exits the app. You can try numerous methods to make this work. For example, VoidCallBack method, adding an async function or leaving a blank setState in the initState itself. At the end of the day, it depends on how your app works. If you have a custom tabbar I'd recommend using the VoidCallBack method or maybe adding an async function which will be called before you return a render. Regardless these methods should work.


text:
Q: Using the SQL syntax CASE returning unknown error message "THEN1" Hi can anyone help me with the below,  I have tried changing the DEC to INT which has no effect, my system is running a DERBY syntax which CASE is accepted so not sure why the below isn't working.
The error message being received is:

BIC00004. DAL01008. An error occurred while accessing the database.
Syntax error: Encountered "THEN1" at line 1, column 416."

My query is as follows:
SELECT
    G."GROUP"
    , G."GROUP.DESC"
    , G.SIZE
    , G."SIZE.DESC"
    , G."WH.AREA"
    , G.OSQTY AS "SALES.RATIO.QTY"
    , F.QTY AS "MAX HOLDING"
    , E."DUE OUT OSQTY" AS  "OUT THIS WEEK"
    , D."OUT THIS WEEK OSQTY"
    , C."DUE IN THIS WEEK OSQTY"
    , B."CURRENT STOCK"
    , A."ACTUAL ORDERS"
    , H.NAME
    , (CASE
        WHEN CAST (G."WH.AREA" AS DEC) = CAST (90 AS DEC) THEN CAST (SUM(G.OSQTY) AS DEC)
        WHEN CAST (G."WH.AREA" AS DEC) = CAST (91 AS DEC) THEN CAST (SUM(G.OSQTY) AS DEC)
        WHEN CAST (G."WH.AREA" AS DEC) = CAST (93 AS DEC) THEN CAST (SUM(G.OSQTY) AS DEC)
        WHEN CAST (G."WH.AREA" AS DEC) = CAST (900 AS DEC) THEN CAST (SUM(G.OSQTY) AS DEC)
        WHEN CAST (G."WH.AREA" AS DEC) = CAST (901 AS DEC) THEN CAST (SUM(G.OSQTY) AS DEC)
        WHEN CAST (G."WH.AREA" AS DEC) = CAST (903 AS DEC) THEN CAST (SUM(G.OSQTY) AS DEC)
        WHEN CAST (G."WH.AREA" AS DEC) = CAST (904 AS DEC) THEN CAST (SUM(G.OSQTY) AS DEC)
        ELSE CAST('99999999999'AS DEC)
    END) AS "salesratiosum"
FROM "vol.sales.ratio" G
    INNER JOIN "vol.max.holding" F
    ON (F.SIZE = G.SIZE AND F."PRODUCT.GROUP" = G."GROUP" AND F.WH = G."WH.AREA")
    LEFT JOIN "vol.due.out.this.week" E
    ON (F.WH = E."WH.AREA" AND F.SIZE = E.SIZE AND F."PRODUCT.GROUP" = E."GROUP")
    LEFT JOIN "vol.due.out.next.week" D
    ON (F.WH = D."WH.AREA" AND F.SIZE = D.SIZE AND F."PRODUCT.GROUP" = D."GROUP")
    LEFT JOIN "vol.due.in.this.week" C
    ON (F.WH = C.BRANCH AND F.SIZE = C. SIZE AND F."PRODUCT.GROUP" = C."GROUP")
    INNER JOIN "vol.current.stock.holding" B
    ON (F.WH = B.WAREHOUSE AND F.SIZE = B.SIZE AND F."PRODUCT.GROUP" = B."GROUP")
    LEFT JOIN "vol.actual.orders" A
    ON (F.WH = A.BRANCH AND F.SIZE = A.SIZE AND F."PRODUCT.GROUP" = A."GROUP")
    INNER JOIN Warehouses H
    ON (F.WH = H.WAREHOUSE)
GROUP BY
    G."GROUP"
    , G."GROUP.DESC"
    , G.SIZE
    , G."SIZE.DESC"
    , G."WH.AREA"
    , G.OSQTY
    , F.QTY
    , E."DUE OUT OSQTY"
    , D."OUT THIS WEEK OSQTY"
    , C."DUE IN THIS WEEK OSQTY"
    , B."CURRENT STOCK"
    , A."ACTUAL ORDERS"
    , H.NAME


text:
Q: CRM 2013 Limit the date field I have 3 date and time fields (its date only).
But I want to limit the user not to be able to select future date.
I mean dates after today's couldn't be selected in the date picker.
How can I do it?

A: You have to write a validator, either in plugin or JavaScript (or business rules), or perhaps both.
JS only works in the forms but has the possibility to give a prettier error message, with the business rules you can have a valitation which gives messages inline. If you only add data using the GUI, it might be enough to just use JS/business rules but if data can come any other way I would secure it with a plugin as well.
The validator is pretty simple, retrieve the field and compare it with a date object today. It could be a bit worse if there are a lot of timezones involved, we don't like timezones....

A: Crm datetime field doesn't support this type of functionality. You'll need to create your own html webresource and use a well-known library / control such as jquery datepicker.
Once you have the resource in place syncing the picker value with the hidden datetime value should be relatively easy using the form onload and onsave events.


text:
Q: Trying to get the date range boundaries of a google daterangefilter I've hooked up an event listener to notify me when the values on the slider change. However, I'm not able to read them.
google.visualization.events.addListener(dfHistorical,'statechange',function(e) {

                    alert("Min value: " + dfHistorical.getOption('minValue') + " Max value: " + dfHistorical.getOption('maxValue'));

            });

A: the 'state' property of the DateRangeFilter has four properties...

lowValue - The lower extent of the selected range, inclusive.
highValue - The higher extent of the selected range, inclusive.
lowThumbAtMinimum - Whether the lower thumb of the slider is locked at the minimum allowed range. If set, overrides lowValue.
highThumbAtMaximum - Whether the higher thumb of the slider is locked at the maximum allowed range. If set, overrides highValue.

to access the properties, use the getState() method
DateRangeFilter.getState().lowValue
e.g.
google.visualization.events.addListener(dfHistorical, 'statechange', function () {
  var valHigh = dfHistorical.getState().highValue;
  var valLow = dfHistorical.getState().lowValue;

  console.log(valLow, valHigh);
});


text:
Q: Will differentiation always give us the maxima and minima If a given a curve with a maxima and a minima will differentiation always give us the maxima and minima values ?
Is it possible that the curve will have the critical points and derivatives won't give us those values ?
Sorry if this seems to simple ,I am a newbie at calculus.
Edit : my question does not seem to be clear ," if a function has a maxima and minima will differentiation ALWAYS give us the critical points .

A: The necessary condition for the existence of a local max or min at $x=a$ is that either $f'(a)$ does not exist or it it exists then $f'(a)=0$. Even if $f'(a)=0$ exists you may not get the explicit value of $a$.
For example $f(x)=x^4-x^3+2x+1 \implies f'(x)=4x^3-3x^2+2,$ but $4x^3+3x^2-1=0$ is not solvable by hand however its real root is at $x=-0.607007...$ which is obtainable numerically. In principle, $f(x)$ has one local min at $x=-0.607007...$
In books and in exams when you are asked to find max/min of $f(x)$, the Authors and Examiners see to it that $f'(x)=0$ is solvable by hand.

A: Differentiation of a differentiable function $f$ always give you stationary points by looking for the points $x$ where $f'(x)=0$.
And amongst these will be inflexion points as well as local minimi and maxima and the global minimal or maximal; that is -  if it has them.

A: Here is an extract from an educational source on this topic:

Since the derivative is zero or undefined at both local maximum and local minimum points, we need a way to determine which, if either, actually occurs. The most elementary approach, but one that is often tedious or difficult, is to test directly whether the y coordinates "near" the potential maximum or minimum are above or below the y coordinate at the point of interest. Of course, there are too many points "near'' the point to test, but a little thought shows we need only test two provided we know that f is continuous (recall that this means that the graph of f has no jumps or gaps).

So apparently, one of the key points for being able to ascertain that the inflexion point(s) constitutes the existence of local maximum (minimum) points is based on a continuity assumption.
Note, one of this thread's questions is "Is it possible that the curve will have the critical points and derivatives won't give us those values ?" and there is nowhere use of the term "differentiable function".
Whereupon, per Wikipedia, to quote:

In particular, any differentiable function must be continuous at every point in its domain. The converse does not hold: a continuous function need not be differentiable. For example, a function with a bend, cusp, or vertical tangent may be continuous, but fails to be differentiable at the location of the anomaly.

So, I would answer yes, as in the event the derivative cannot be computed at the anomaly (may not exist), one needs to inspect to the right and left of the curve (permissible per the continuity assumption) to determine the true nature of the inflexion point.


text:
Q: Javascript map is not a function what trying to read data I am trying to populate a chart so I'm getting the data into 2 lists in order to do this.
This is the data:
var data = [{
    "id": "622",
    "name": "some name",
    "boats": {
        "637": {
            "id": "637",
            "name": " Subcat 1",
            "translations": null
        },
        "638": {
            "id": "638",
            "name": "Subcat 2",
            "translations": null
        }
    },
    "image": "73e043a7fae04b55855bede22da6286b"
}];

And I am running this code in order to populate the lists:
var chList = [];
var boatList = [];
var boatCount = [];

for (var i = 0; i < data.length; i++) {

    var obj = data[i];

    var cl = obj.name + " [" + obj.id + "]";

    if (obj.boats != null) {
        chList.push(cl);
    }

    if(obj.boats) {

        var nme = obj.boats.map( function(item){
            return item.name;
        });

        boatList = boatList.concat(nme);
        boatCount.push(nme.length);

    }

}

console.log(boatList);
console.log(boatCount);

My problem is that I keep getting:
TypeError: obj.boats.map is not a function
How can I fix this?
Note: The data is actually this:
{
    "id": "622",
    "name": "some name",
    "boats": {
        "637": {
            "id": "637",
            "name": " Subcat 1",
            "translations": null
        },
        "638": {
            "id": "638",
            "name": "Subcat 2",
            "translations": null
        }
    },
    "image": "73e043a7fae04b55855bede22da6286b"
};

But I added [ and ] to it in order to use data.length and the lists where empty too ... Do I then leave this data as it is?

A: The problem is that obj.boats is an object, not an array, hence doesn't have the map method.
Try this instead:
Object.keys(obj.boats).map(function(k) { return obj.boats[k].name; });

See MDN

A: boats is an object, not an array. Map is for arrays.
You could use a for ( in ) loop or Object.keys() to get an array of keys and work with that.

A: The two other answers are right, I'd change the data though:
"boats": [
    {
        "id": "637",
        "name": " Subcat 1",
        "translations": null
    },
    {
        "id": "638",
        "name": "Subcat 2",
        "translations": null
    }
],

Using the id as key and then giving the containing object a "id" property is kinda pointless. When you change the data to this structure your code will work fine.

A: Besides all other answers that already correctly point to obj.boats being an Object and not an Array, I'd like providing a solution that demonstrates the elegant beauty of Array.reduce ...

var boatChartData = [{
  "id": "622",
  "name": "some name",
  "boats": {
    "637": {
      "id": "637",
      "name": "Subcat 1",
      "translations": null
    },
    "638": {
      "id": "638",
      "name": "Subcat 2",
      "translations": null
    }
  },
  "image": "73e043a7fae04b55855bede22da6286b"
}, {
  "id": "623",
  "name": "other name",
  "boats": {
    "639": {
      "id": "639",
      "name": "Supercat",
      "translations": null
    },
    "640": {
      "id": "640",
      "name": "Supercat II",
      "translations": null
    },
    "641": {
      "id": "641",
      "name": "Supercat III",
      "translations": null
    }
  },
  "image": "73e043a7fae04b55855bede22da6295c"
}];

function collectBoatChartData(collector, chartItem/*, idx, list*/) {
  var
    boatNameList,
    boatMap = chartItem.boats;

  if (boatMap != null) {
    collector.chartItemTitleList.push([

      chartItem.name,
      " [",
      chartItem.id,
      "]"

    ].join(""));

    boatNameList = Object.keys(boatMap).map(collector.getBoatNameByKey, boatMap);

    collector.boatNameList = collector.boatNameList.concat(boatNameList);

  //collector.chartItemBoatNameList.push(boatNameList);
    collector.chartItemBoatCountList.push(boatNameList.length);
  }
  return collector;
}

var processedBoatChartData = boatChartData.reduce(collectBoatChartData, {

  getBoatNameByKey: function (key) {
    return this[key].name;
  },
  boatNameList: [],
  chartItemTitleList: [],
//chartItemBoatNameList: [],
  chartItemBoatCountList: []
});

console.log("processedBoatChartData.boatNameList : ", processedBoatChartData.boatNameList);
console.log("processedBoatChartData.chartItemTitleList : ", processedBoatChartData.chartItemTitleList);
  //console.log("processedBoatChartData.chartItemBoatNameList : ", processedBoatChartData.chartItemBoatNameList);
console.log("processedBoatChartData.chartItemBoatCountList : ", processedBoatChartData.chartItemBoatCountList);

Note
Taking into account the OP's additional comment, mentioning the provided axample's real data structure, the above provided solution of mine just changes to ...
var boatChartData = {
  "id": "622",
  "name": "some name",
  "boats": {
    "637": {
      "id": "637",
      "name": "Subcat 1",
      "translations": null
    },
    "638": {
      "id": "638",
      "name": "Subcat 2",
      "translations": null
    }
  },
  "image": "73e043a7fae04b55855bede22da6286b"
};

var processedBoatChartData = [boatChartData].reduce(collectBoatChartData, {

  getBoatNameByKey: function (key) {
    return this[key].name;
  },
  boatNameList: [],
  chartItemTitleList: [],
//chartItemBoatNameList: [],
  chartItemBoatCountList: []
});

.., proving that generic solutions can be recycled/adapted easily, if e.g. data structures do change.


text:
Q: How to replace part of str using `re.sub()`? I can replace oldText with newText1 as re.sub("'(.*)'", 'newText', "test = 'oldText'")
But I am trying to use re.sub() as re.sub("'test = (.*)'", 'newText', "test = 'oldText'")
Can I pass actual text in pattern?
I think numbers were bad example I updated with str. The first one works but second one doesn't. Isn't it allowed to have actual text in pattern?

A: >>> import re
>>>
>>> re.sub(r"(test = )'.*'", r"\1'" + str(22) + r"'", "test = '21'")
"test = '22'"

You can do it but you need to grab all the other parts of the match and piece it back together with the new result.


text:
Q: How to decrease the chart opacity in highcharts I am trying to decrease the opacity of charts instead of hiding when click the legend.
Example: When i click the Tokyo legend series blue color column hiding instead of hiding I want to decrease the opacity to 0.34 of blue color column. same for other legend when clicking. So, How to do it?
Highcharts.chart('container', {
chart: {
    type: 'column'
},
title: {
    text: 'Monthly Average Rainfall'
},
subtitle: {
    text: 'Source: WorldClimate.com'
},
xAxis: {
    categories: [
        'Jan',
        'Feb',
        'Mar',
        'Apr',
        'May',
        'Jun',
        'Jul',
        'Aug',
        'Sep',
        'Oct',
        'Nov',
        'Dec'
    ],
    crosshair: true
},
yAxis: {
    min: 0,
    title: {
        text: 'Rainfall (mm)'
    }
},
tooltip: {
    headerFormat: '{point.key}
',
    pointFormat: '
{series.name}: 	' +
        '{point.y:.1f} mm
',
    footerFormat: '
',
    shared: true,
    useHTML: true
},
plotOptions: {
    column: {
        pointPadding: 0.2,
        borderWidth: 0
    },
       series: {
        events: {
            legendItemClick: function(event) {
                var visibility = this.visible ? '0.35' : '';
                alert(event);
            }
        }
    },
},
series: [{
    name: 'Tokyo',
    data: [49.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4,
        194.1, 95.6, 54.4]

}, {
    name: 'New York',
    data: [83.6, 78.8, 98.5, 93.4, 106.0, 84.5, 105.0, 104.3, 91.2, 83.5,
        106.6, 92.3]

}, {
    name: 'London',
    data: [48.9, 38.8, 39.3, 41.4, 47.0, 48.3, 59.0, 59.6, 52.4, 65.2, 59.3,
        51.2]

}, {
    name: 'Berlin',
    data: [42.4, 33.2, 34.5, 39.7, 52.6, 75.5, 57.4, 60.4, 47.6, 39.1, 46.8,
        51.1]

}]
});

https://www.highcharts.com/demo/column-basic
Demo:
https://jsfiddle.net/4t6arfg8/

A: You used the correct event, the remaining thing is to change opacity of the proper SVG element and colorize the legend item.
series: {
  events: {
    legendItemClick: function(e) {
      const series = this;
      const chart = series.chart;
      const hasChangedOpacity = series.hasChangedOpacity;

      series.group.attr({
        opacity: hasChangedOpacity ? 1 : 0.2
      });
      chart.legend.colorizeItem(series, hasChangedOpacity);
      series.hasChangedOpacity = !hasChangedOpacity;
      // prevent default behaviour
      return false;
    }
  }
}

Also, to keep the default series states behaviour, you need to add the below small plugin:
(function(H) {
  H.wrap(H.Series.prototype, 'setState', function(proceed) {
    if (!this.hasChangedOpacity) {
      proceed.apply(this, Array.prototype.slice.call(arguments, 1));
    }
  });
}(Highcharts));

Live demo: https://jsfiddle.net/BlackLabel/p1x6937f/
API Reference: https://api.highcharts.com/highcharts/series.column.events.legendItemClick
Docs: https://www.highcharts.com/docs/extending-highcharts/extending-highcharts


text:
Q: Overwrite a specific value in a dataframe, based on matching values My data is in a format like this:
#>   country year value
#> 1     AUS 2019   100
#> 2     USA 2019   120
#> 3     AUS 2018    90

df <- data.frame(stringsAsFactors=FALSE,
     country = c("AUS", "USA", "AUS"),
        year = c(2019, 2019, 2018),
       value = c(100, 120, 90)
)

and I have an one row dataframe that represents a revision that should overwrite the existing record in my data.
#>   country year value
#> 1     AUS 2019   500

df2 <- data.frame(stringsAsFactors=FALSE,
                  country = c("AUS"),
                     year = c(2018),
                    value = c(500)
             )

My desired output is:
#>   country year value
#> 1     AUS 2019   100
#> 2     USA 2019   120
#> 3     AUS 2018   500

I know how to find the row to overwrite:
library(tidyverse)
df %>% filter(country == overwrite$country & year == overwrite$year) %>%
  mutate(value = overwrite$value)

but how do I put that back in the original dataframe?
Tidyverse answers are easier for me to work with, but I'm open to any solutions.

A: Here, an efficient approach is join on with data.table.  Convert the 'data.frame' to 'data.table' (setDT(df)), join on with the 'df2' on 'country', 'year' assign (:=) the 'value' column from second dataset (i.value) to replace the 'value' in original dataset
library(data.table)
setDT(df)[df2, value := i.value, on = .(country, year)]
df
#    country year value
#1:     AUS 2019   100
#2:     USA 2019   120
#3:     AUS 2018   500

A: Using mutate and if_else:
library(tidyverse)

df %>%
mutate(value = if_else(country %in% df2$country & year %in% df2$year, df2$value, value))

Results in:
country year value
1     AUS 2019   100
2     USA 2019   120
3     AUS 2018   500

A: One possible tidyverse approach using 1). anti_join to remove the rows from df that will be replaced and 2). bind_rows to add the replacement rows from df2:
library(dplyr)

anti_join(df, df2, by = c("country", "year")) %>% bind_rows(df2)
#>   country year value
#> 1     AUS 2019   100
#> 2     USA 2019   120
#> 3     AUS 2018   500

Or, another one using 1). right_join to join the old and new values and 2). coalesce to keep only the new values:
right_join(df2, df, by = c("country", "year")) %>%
    transmute(country, year, value = coalesce(value.x, value.y))
#>   country year value
#> 1     AUS 2019   100
#> 2     USA 2019   120
#> 3     AUS 2018   500


text:
Q: Return value from MySQL stored procedure So I've finally decided to get around to learning how to use stored procedures, and although I do have them working, I'm unsure if I'm doing it correctly - aka. the best way. So here's what I've got.
Three procedures: TryAddTag, CheckTagExists, and AddTag.
TryAddTag is the procedure that is my intermediary between other code (eg. PHP, etc...) and the other two procedures, so this is the one that gets called.

TryAddTag
DELIMITER //
 CREATE PROCEDURE TryAddTag(
  IN tagName VARCHAR(255)
 )

 BEGIN

 -- Check if tag already exists
 CALL CheckTagExists(tagName, @doesTagExist);

 -- If it does not exist, add it
 IF @doesTagExist = FALSE THEN
  CALL AddTag(tagName);
 END IF;

END //
DELIMITER ;

AddTag
DELIMITER //
 CREATE PROCEDURE AddTag(
  IN tagName VARCHAR(255)
 )
 BEGIN

 INSERT INTO
  tags
 VALUES(
  NULL,
  tagName
 );

END //
DELIMITER ;

CheckTagExists
DELIMITER //
 CREATE PROCEDURE CheckTagExists(
  IN
   tagName VARCHAR(255),
  OUT
   doesTagExist BOOL
 )
 BEGIN

 -- Check if tag exists
 SELECT
  EXISTS(
   SELECT
    *
   FROM
    tags
   WHERE
    tags.NAME = tagName
  )
 INTO
  doesTagExist;

END //
DELIMITER ;

My problems stem from this and use of @doesTagExist.
-- Check if tag already exists
CALL CheckTagExists(tagName, @doesTagExist);

Is the the correct way to use one of these variables? And/or, how can I use a DECLARE'd variable to store the result of CheckTagExists within TryAddTag? I expected something along the lines of
...
DECLARE doesTagExist BOOL;
SET doesTagExist = CheckTagExist('str');
...

or something like that...

A: Stored PROCEDURES can return a resultset.  The last thing you SELECT in a stored procedure is available as a resultset to the calling environment..  Stored FUNCTIONS can return only a single result primitive.
You may also mark your parameters as INOUT parameters.

A: your stored procedure is a little over-engineered for my liking - keep it simple :)
MySQL
drop table if exists tags;
create table tags
(
tag_id int unsigned not null auto_increment primary key,
name varchar(255) unique not null
)
engine=innodb;

drop procedure if exists insert_tag;

delimiter #

create procedure insert_tag
(
in p_name varchar(255)
)
proc_main:begin

declare v_tag_id int unsigned default 0;

    if exists (select 1 from tags where name = p_name) then
        select -1 as tag_id, 'duplicate name' as msg; -- could use multiple out variables...i prefer this
        leave proc_main;
    end if;

    insert into tags (name) values (p_name);

    set v_tag_id = last_insert_id();

    -- do stuff with v_tag_id...

    -- return success
    select v_tag_id as tag_id, 'OK' as msg;

end proc_main #

delimiter ;

PHP
<?php

ob_start();

try{

    $conn = new mysqli("localhost", "foo_dbo", "pass", "foo_db", 3306);

    $conn->autocommit(FALSE); // start transaction

    // create the tag

    $name = 'f00';

    $sql = sprintf("call insert_tag('%s')", $conn->real_escape_string($name));

    $result = $conn->query($sql);
    $row = $result->fetch_array();
    $result->close();
    $conn->next_result();

    $tagID = $row["tag_id"]; //  new tag_id returned by sproc

    if($tagID < 0) throw new exception($row["msg"]);

    $conn->commit();

    echo sprintf("tag %d created
refresh me...", $tagID);

}
catch(exception $ex){
    ob_clean();
    //handle errors and rollback
    $conn->rollback();
    echo sprintf("oops error - %s
", $ex->getMessage());
}

// finally
$conn->close();
ob_end_flush();
?>

A: If you want this:
DECLARE doesTagExist BOOL;
SET doesTagExist = CheckTagExist('str');

then you should use functions:
DELIMITER //
 CREATE FUNCTION CheckTagExists(
   tagName VARCHAR(255)
 )
 BEGIN
   DECLARE doesTagExist BOOL;

 -- Check if tag exists
 SELECT
  EXISTS(
   SELECT
    *
   FROM
    tags
   WHERE
    tags.NAME = tagName
  )
 INTO
  doesTagExist;

  RETURN doesTagExist;
END //
DELIMITER ;

A: DECLARE doesTagExist BOOL;
SET CheckTagExist('str',doesTagExist);

is the correct way of doing it with just store procedures. There are no 'regular' return values.


text:
Q: Implementing tabs and menu in a single page in ionic4 I have a project which is done in ionic1 with tabs and menu in the same page.I want to implement the same in  ionic4.
The existing problem in ionic4 is that, those pages being redirected on clicking the menu are not supporting tabs. I am not able to include the code for menu and tab in the same page.

A: you can flow this tutorial Combine side menu, tabs and login page with Ionic 4
that implements side-menu and tabs on the same page
another useful tutorial is here from IonicAcademy


text:
Q: I'm trying to translate an example of TypeScript into JavaScript, and I'm not sure how to convert it I'm working with an example of NativeScript which uses TypeScript to process the logic. My working project uses JavaScript and I want to bring the example into my project.
I tried to bring the code into the TS playground
import { EventData } from "tns-core-modules/data/observable";
import { Page, View } from "tns-core-modules/ui/page";
import { SwipeActionsEventData } from "nativescript-ui-listview";

import { HomeViewModel } from "./home-view-model";

export function navigatingTo(args: EventData) {
    const page = <Page>args.object;

    page.bindingContext = new HomeViewModel();
}

export function onSwipeCellStarted(args: SwipeActionsEventData) {
    const swipeLimits = args.data.swipeLimits;
    swipeLimits.left = 360;
    swipeLimits.right = 0;
    swipeLimits.threshold = 200;
}

I'm just wanting to know how it would be formated using JS

A: import { HomeViewModel } from "./home-view-model";
export function navigatingTo(args) {
    const page = args.object;
    page.bindingContext = new HomeViewModel();
}
export function onSwipeCellStarted(args) {
    const swipeLimits = args.data.swipeLimits;
    swipeLimits.left = 360;
    swipeLimits.right = 0;
    swipeLimits.threshold = 200;
}

Or if the application doesn't support 'import' syntax
const HomeViewModel = require("./home-view-model").HomeViewModel;
export function navigatingTo(args) {
    const page = args.object;
    page.bindingContext = new HomeViewModel();
}
export function onSwipeCellStarted(args) {
    const swipeLimits = args.data.swipeLimits;
    swipeLimits.left = 360;
    swipeLimits.right = 0;
    swipeLimits.threshold = 200;
}


text:
Q: Extracting frames from all videos in a directory using FFmpeg I'm trying to use FFmpeg to extract one frame per second from every file in a directory.
I use this command for individual files, but I can't figure out how to input a directory instead:
ffmpeg -i "C:\input\clip1.mp4" -vf fps=1 -qscale:v 2 "C:\output\clip1\clip1A"%d.jpg

Ideally, I want the frames saved to their own folder like below, but I think I can work that part out myself. It's fine if they're all output to the same folder with the same prefix and sequential numbering.
C:\output\clip1\clip1-001.jpg, clip1-002.jpg
C:\output\clip2\clip2-001.jpg, clip2-002.jpg
I've been trying for many hours now and I'm still completely lost. Any help at all would be extremely appreciated.

A: Done it! This code will output frames to folders of the same name as the video they came from. The frames will be prefixed by the video name and suffixed by sequential numbers starting at 001. So for my files it spits out "/clip1/clip1-001.jpg" etc.
Just in case you're like me and don't have a clue what you're doing, paste the below code in to notepad, save as "extractframesorwhatever.bat", and run from from the directory where your clips are.
for %%F in (*.mp4) do (
If not Exist "%%~nF" MkDir "%%~nF"
ffmpeg -i %%F -r 1 -qscale:v 2 %%~nF\%%~nF-%%3d.jpg
)

If you want to output the folders somewhere else, change:
If not Exist "%%~nF" MkDir "%%~nF"

To something like this:
If not Exist "C:\wherever\%%~nF" MkDir "C:\wherever\%%~nF"

If you do that you'll also need to change the output from (in my example):
%%~nF\%%~nF-%%3d.jpg

to
C:\wherever\%%~nF\%%~nF-%%3d.jpg

Or if you want all frames in one folder. Replace the first %%~nF from the output with your preferred directory. Using my example, it would go from C:\wherever\%%~nF\%%~nF-%%3d.jpg to C:\wherever\frames\%%~nF-%%3d.jpg. You will also either want to edit the second line to point to the new location and stop it from creating a bunch of unnecessary directories, or take out the second line entirely. If you remove the second line, you'll have to create that "frames" folder yourself first.
EDIT - You might need to remove all spaces from file names before they can be processed. "Bulk rename utility" can save you a lot of time.

A: I like this method for extracting frames, it is very handy. But when I use the code you provide:
for %%F in (*.mp4) do (
If not Exist "%%~nF" MkDir "%%~nF"
ffmpeg -i %%F -r 1 -qscale:v 2 %%~nF\%%~nF-%%3d.jpg
)

I get two output folders:
One of the file name (which is where I want my images to go) and a test folder (which is where my images do go).
I know this is how the code is supposed to work, but perhaps changes over the past four years has changed something with how this code works now. But really, all in all, it's not TOO inconvenient.
I will also add, for those who want to make GIFs of higher quality, you can just change .jpg to .png.
Also, you can make this work with any video format (or more, at least, as I haven't tested this much) by changing the (.mp4) into (.mkv), which I know works.
I assume all other video formats would work also, such as (.avi), (.mpeg), (.ts), (.flv), etc. - though this is not tested.
But as I am the same as the OP in that I don't understand this code, only copy/paste what I find online and play around with it some, it is handy to just have the .bat files ready to go.
I would just like to know how to fix the "test" folder being created and have the screenshots instead go into the folder it already creates of the file name.
To show how I've altered the code to work with other video formats, I'll include a couple of examples:
The first example, which I know works, is for .mkv files instead of .mp4, making the screenshots into .png.
for %%F in (*.mkv) do (
If not Exist "%%~nF" MkDir "%%~nF"
ffmpeg -i %%F -r 1 -qscale:v 2 %%~nF\%%~nF-%%3d.png
)

The last example SHOULD work for .ts files making the screenshots into .png.
for %%F in (*.ts) do (
If not Exist "%%~nF" MkDir "%%~nF"
ffmpeg -i %%F -r 1 -qscale:v 2 %%~nF\%%~nF-%%3d.png
)


text:
Q: Copy files in same folder and replace year in its name How can I copy a lot of files in the same directory replacing the year in its name?
I have this (can be different filename and extensions):
filename1-2014.ext
filename2-2014.ext
filename3-2014.ext
...
filenamen-2014.ext

And I want this:
filename1-2014.ext
filename1-2015.ext
filename2-2014.ext
filename2-2015.ext
filename3-2014.ext
filename3-2015.ext
...
filenamen-2014.ext
filenamen-2015.ext

I can make a script to do it, but I'm wondering is there is an easy way of doing it?

A: *

*With find:
find . -type f -name '*2014*' -exec bash -c 'cp "$0" "${0/2014/2015}"' {} \;

*In the shell loop:
for file in *2014*; do
    cp "$file" "${file/2014/2015}"
done

A: for i in *-2014.ext; do
  cp "$i" "${i%2014.ext}2015.ext"
done

For each file remove the old suffix and add the new one.
If you have different extensions you can use the pattern substitution feature of bash:
for i in *-2014.*; do
  cp "$i" "${i/2014/2015}"
done


text:
Q: Как правильно получить CSV с данными из HTML таблицы? У меня стоит задача получить .csv с данными из HTML таблицы.
Я из всего не нужного HTML документа смог вытащить таблицу - код парсера:
from bs4 import BeautifulSoup
    from bs4.element import Tag
    def open_file():
        html = open('table.html','r' ,encoding='utf-8')
        html_sorted = open('html_sorted.html', 'w+',encoding='utf-8')
        soup = BeautifulSoup(html, 'lxml')
        title = soup.find('div', class_='row')
        table = soup.find('table', class_='table')
        table = str(table)
        title = str(title)
        html_sorted.write(title + table)
        html.close()
        html_sorted.close()
    open_file()

Каждое утро понедельника у меня будет такая таблица на выходе из которой мне нужно вытягивать данные за последнюю неделю...

...и помещать в .csv файл в таком виде.

Изначально на выходе 10 дат. Если даты идут последовательно, к примеру с 1(понедельник) по 7(воскресенье), то нужен срез за последние 7. На следующей неделе с 8 по 14. А если даты пропускаются, мне нужно в отчет вывести информацию по этим датам с цифрой 0. К примеру в таблице отсутствует 5 число, но в отчете оно нужно со всеми значениями справа в "0".
Мне нужно все данные из  где дата как-то сортировать, добавлять и не потерять привязку к полю с датой остальных полей справа с оценками.
Просто эти самые  с датой ни к какому классу или id не относятся.
Как и tr со всей строкой.

Прошу помочь подобрать нужные инструменты для решения. С чего начать?

A: Воспользуйтесь методом pandas.read_html():
import pandas as pd

all_tabs_in_page = pd.read_html(url_or_html)

Т.к. в общем случае в HTML документе может быть несколько таблиц, pd.read_html() всегда возвращает список найденных в документе таблиц, даже если в документе всего одна таблица.
Поэтому сначала следует вручную  проверить по какому индексу находиться интересуемая вас таблица. И после этого использовать в коде найденный индекс:
df = pd.read_html(url_or_html)[0]
df.to_csv(filename, index=False)

Используя таким образом модуль Pandas можно легко, быстро и элегантно решать подобные задачи.
То же решение в видн однострочника:
pd.read_html(url_or_html)[0].to_csv(filename, index=False)


text:
Q: touchmove event in Safari/iOS5/iPad disables contenteditable - any workaround? I have a serious problem in Safari on iPad. The new contenteditable features doesn't seem to work with touchmove event!
code:
 ...
 <script>
function doNothing(event) { return; }

function initIFrame() {
    var iframe=document.getElementById("iframeedit");
    iframe.contentWindow.document.designMode="on";
    iframe.contentWindow.document.addEventListener("touchmove", doNothing, true);
}
</script>
</head>
<body onload="initIFrame()">
<iframe style="width:500ppx;height:200px" src="content.html" id="iframeedit"></iframe>
...

By adding touchmove somewhere to the document the editable content can not be edited anymore after a touchmove (hold finger down to get the magnifier). The cursor can be set but typing by onscreen keyboard is not allowed anymore.
Test script (for iPad + iOS5):
http://flyingdog.biz/tests/ipad/test2.html
Another test script which is working:
http://flyingdog.biz/tests/ipad/test1.html
As you can see in that other script I put a few lines of text in front of iFrame - very strange! I am looking for another/better workaround or did I have done something wrong? Without the touchmove event it is working but I need this for a good editing experience.

A: I found a workaround for this bug: It seems that the iframe document looses the focus after a touch event, especially when the copy&paste menu appears. To workaround this bug add a keydown event handler to the iframe-document and reset the focus to the document:
var iframeDoc = $(iframe.contentWindow.document);
iframeDoc.keydown(function(event) {
    iframe.contentWindow.focus();
});

This fixes the bug mostly for me. Only if the user types very fast (e.g. on a connected bluetooth keyboard) it can happen that some keystrokes are lost, because the javascript keydown handler execution is a little bit delayed on the iPad.


text:
Q: PATCH method set NULL to values instead of the value How is it possible to insert multiple row in json via Postman ?
I tried this :
[{
    "name": "Choix 1",
    "question": "Question 1"
},
{
    "name": "Choix 3",
    "question": "Question 44"
}
]

EDIT.
I saw in the documentation that it is not possible like that.
I added a denormalization group in my API and now I can add several data at the same time thanks to the PATCH method. But now, the problem is that when I add a second time, it removes a part of the previous data.
Example : in "question_study" I have my "question_id" 156, 157, 160 which don't have any "study_ID" whereas they had some before I send him a new question (161) which has its id number .... And if I send him several at once they all have a study_id but if I re-try, the "study_id" disappear....

axios
        .patch('http://127.0.0.1:8000/api/studies/' + this.idStudy,
             data,
             { headers: { 'Content-Type': 'application/merge-patch+json' }})
        .then((result)=>{
          console.log(result)
        })
        .catch(error => {
          console.log("ERRRR:: ",error.result.data);
        });

In my console console.log(result) : the header content-type is "application/ld+json; charset=utf-8" while I put 'application/merge-patch+json' in my request.
And this is a piece of my db :

A:
How is it possible to insert multiple row in json via Postman [into ApiPlatform]?

It isn't.
At least, not using default generated routes from ApiPlatform for its resources. Docs here: https://api-platform.com/docs/core/operations/
Any generated POST route will only accept a single resource.
If you want to be able to do batch inserts, you will have to create a custom endpoint and probably a collection denormalizer.


text:
Q: Products.SQLAlchemyPAS works as foreground but not as service I have SQLAlchemyPAS with little customisation. product works fine with foreground mode but when I run as service it doesn't work.

A: Its was permission issue. sorted now. cfg file needed username and password for database connection string.


text:
Q: $T(X) = (\sum X_i, \sum X_i^2)$ is not complete for $\sigma$
Let $X = (X_1,X_2,\dots, X_n)$ be a sample from $N(\alpha\sigma, \sigma^2)$, where $\alpha$ is known real number. Show that the family of distributions of $T(X) = (\sum X_i, \sum X_i^2)$ is not complete for $\sigma$.

I am trying to show some counterexample for $g(X)$ such that $E(g(T))=0$ but $g$ is not $0$ a.e., but could not find any. Thanks for any help.


text:
Q: Mybatis configuration error: BuilderException I am learning spring boot + Mybatis + MySQL, and I just write a demo using xml as mybatis mapper but got error:
nested exception is org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML.
Cause: java.lang.IllegalArgumentException: Result Maps collection already contains value
for mappers.UserMapper.UserResultMap

My mapper xml is:
<!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="mappers.UserMapper">
    <resultMap id="UserResultMap" type="hello.User">
        <id column="id" property="id" />
        <result column="name" property="name" />
        <result column="email" property="email" />
    </resultMap>
    <select id="findAllUsers" resultMap="UserResultMap">
        select id, name, email from users
    </select>
    <select id="findUserById" resultMap="UserResultMap">
        select id, name, email from users WHERE id=#{id}
    </select>
    <insert id="insertUser" parameterType="hello.User" useGeneratedKeys="false" keyProperty="id">
        insert into users(name,email) values(#{name},#{email})
    </insert>
</mapper>

How can I fix it?

A: The error is the resultType id must be unique.
 <resultMap id="UserResultMap1" type="hello.User">
        <id column="id" property="id" />
        <result column="name" property="name" />
        <result column="email" property="email" />
    </resultMap>
 <resultMap id="UserResultMap2" type="hello.User">
        <id column="id" property="id" />
        <result column="name" property="name" />
        <result column="email" property="email" />
    </resultMap>

A: It is recommended to use resultType instead of resultMap.like this
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.example.oa.dao.Borrow_DeviceDao">
<insert id="addBorrow_Device"
    parameterType="com.example.oa.domain.Borrow_device">
    INSERT INTO
    borrow_device
    (borrow_device_deviceid,employeeid,borrow_device_date)
    VALUES
    (#{borrow_device_deviceid},#{employeeid},now())
</insert>
<update id="updateBorrow_Device"
    parameterType="com.example.oa.domain.Borrow_device">
    update
    borrow_device set
    borrow_device_deviceid=#{borrow_device_deviceid},employeeid=#{employeeid},borrow_device_date=now()
    where borrow_device_id=#{borrow_device_id}
</update>
<delete id="deleteBorrow_Device"
    parameterType="com.example.oa.domain.Borrow_device">
    delete from
    borrow_device where
    borrow_device_id=#{borrow_device_id}
</delete>
<select id="getallBorrowDeviceInfo"
    resultType="com.example.oa.domain.Borrow_device">
    select * from
    borrow_device
</select>


text:
Q: Only keep rows by group for which first is a certain value SAS I have sorted data as
ID value1 value2
1    A       1
1    A       2
1    A       1
2    A       2
2    B       1
3    A       1
3    B       1
3    B       1

I want to change this data to a new data set where I have only the data of ID's whose last value1 was B. I.e. it should look like this:
ID value1 value2
2    A       2
2    B       1
3    A       1
3    B       1
3    B       1

I have tried
data want;
set have;
by ID;
if last.value1 = 'B' then output;
run;

But that didn't work. Could someone help me out? Thanks in advance!

A: A technique known as DOW + sequential looping allows you to:

*

*Loop over a group in order to compute some state variables(s).  In this case the variable is for tracking the state is the value1 in the last row of the group = 'B' ?

*Utilize the state variable, while looping over the same group, according to your criteria.  In this case output the row if the group is wanted. This loop relies on the DO loop feature that limits are determined once at loop initialization.

The original data must be sorted by the group variables.
data want;
  do _n_ = 1 by 1 until (last.id);
    set have;
    by id;
  end;
  %* _n_ is group size at this point;

  _want_group = value1 = 'B';  %* state variable -- is B in last row?;

  do _n_ = 1 to _n_;   %* process the group again, using a different SET buffer;
    set have;          %* same data set as in the do/until;
                       %* no by required because loop limit _n_ is group size;
    if _want_group then
      OUTPUT;          %* output all rows of group as desired;
  end;

  drop _want_group;
run;

A: The easiest way to do this would be in multiple steps. The first step would be to create a dataset with all ID's that have 'B' as the last value.
data tmp;
set have;
by ID value1;
if last.ID and value1='B' then output;
run;

Now the dataset tmp has all of the ID's that you want so you can select those ID's from the original dataset.
proc sql;
create table want as
select *
from have
where id in (select distinct id from tmp);
quit;

If you want to do this problem in one data step, then you can sort the original table by value1 descending and run through the following data step.
proc sort data=have;
by id descending value1;
run;

data want(where=(keep_flag));
set have;
by id descending value1;
retain keep_flag;
if first.id and value1='B' then keep_flag=1;
else if first.id then keep_flag=0;
run;


text:
Q: SwiftUI MVVM logic for initializing view models with parallel paths Suppose I have two paths in my app:
X -> A -> B -> C and
X -> E -> F -> G.
Now let's imagine views, B and F both share view model Alpha, and there is an equal chance of the user navigating to either view first. Although this is a simplified demo, and using @EnvironmentObject when starting out in the root view would be my choice here, let's imagine a much more complex application with many views, and many view models where initializing and passing all view models into the environment at the entry point into the application would be computationally demanding.
Should I just used @ObservedObject for each view/view model in this case if/when the user navigates to the view, or is there a way I can add logically to pass the view model to the environment logically depending on which view is reached first. I want to make sure I am not creating any memory leaks and performing extra steps, so wondering what the most efficient way to do this would be for parallel views. Thanks

A: Usually just a single environmentObject that holds the arrays of model structs. Pass them down the View structs as lets for read access or @Binding vars for write access.


text:
Q: Any free Ajax poll script? Do you guys know any free PHP Ajax poll script with an admin panel? I can't find one and I have googled for ages.

A: Check out this simple AJAX poll script.
No it doesn't have admin panel.
I think it's rare to find one with an admin panel, maybe I should make one.
http://www.dhtmlgoodies.com/index.html?whichScript=ajax-poller


text:
Q: How to keep a CountDownTimer running even if the app is closed? I spent my summer learning how to code and building my first app (in android studio). Therefore I am not an expert coder. This week I encountered a problem. Basically, I am developing a quiz app and when the user gets the answer wrong he have to wait 5 min. The thing is  that when the countdowntimer starts and the user closes the app (by closing the app I mean destroy it and not just push the home button) the countdowntimer stops. I am wondering how I can manage to  keep the timer running even if the app is closed. Your help will be greatly appreciated and it would be fantastic if you guys give me a sample code.
Thanks in advance!

A: Download source code from here Android Countdown Timer Run In Background
activity_main.xml
<RelativeLayout android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/et_hours"
            android:hint="Hours"
            android:inputType="time"
            android:layout_marginRight="5dp"
            />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btn_timer"
        android:layout_above="@+id/btn_cancel"
        android:text="Start Timer"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:id="@+id/btn_cancel"
        android:text="cancel timer"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tv_timer"
        android:layout_centerInParent="true"
        android:textSize="25dp"
        android:textColor="#000000"
        android:text="00:00:00"/>

    </RelativeLayout>

MainActivity.java
package com.countdowntimerservice;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.text.SimpleDateFormat;
import java.util.Calendar;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button btn_start, btn_cancel;
    private TextView tv_timer;
    String date_time;
    Calendar calendar;
    SimpleDateFormat simpleDateFormat;
    EditText et_hours;

    SharedPreferences mpref;
    SharedPreferences.Editor mEditor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
        listener();

    }

    private void init() {
        btn_start = (Button) findViewById(R.id.btn_timer);
        tv_timer = (TextView) findViewById(R.id.tv_timer);
        et_hours = (EditText) findViewById(R.id.et_hours);
        btn_cancel = (Button) findViewById(R.id.btn_cancel);

        mpref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        mEditor = mpref.edit();

        try {
            String str_value = mpref.getString("data", "");
            if (str_value.matches("")) {
                et_hours.setEnabled(true);
                btn_start.setEnabled(true);
                tv_timer.setText("");

            } else {

                if (mpref.getBoolean("finish", false)) {
                    et_hours.setEnabled(true);
                    btn_start.setEnabled(true);
                    tv_timer.setText("");
                } else {

                    et_hours.setEnabled(false);
                    btn_start.setEnabled(false);
                    tv_timer.setText(str_value);
                }
            }
        } catch (Exception e) {

        }

    }

    private void listener() {
        btn_start.setOnClickListener(this);
        btn_cancel.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.btn_timer:

                if (et_hours.getText().toString().length() > 0) {

                    int int_hours = Integer.valueOf(et_hours.getText().toString());

                    if (int_hours<=24) {

                        et_hours.setEnabled(false);
                        btn_start.setEnabled(false);

                        calendar = Calendar.getInstance();
                        simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
                        date_time = simpleDateFormat.format(calendar.getTime());

                        mEditor.putString("data", date_time).commit();
                        mEditor.putString("hours", et_hours.getText().toString()).commit();

                        Intent intent_service = new Intent(getApplicationContext(), Timer_Service.class);
                        startService(intent_service);
                    }else {
                        Toast.makeText(getApplicationContext(),"Please select the value below 24 hours",Toast.LENGTH_SHORT).show();
                    }
/*
                    mTimer = new Timer();
                    mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 5, NOTIFY_INTERVAL);*/
                } else {
                    Toast.makeText(getApplicationContext(), "Please select value", Toast.LENGTH_SHORT).show();
                }
                break;

            case R.id.btn_cancel:

             Intent intent = new Intent(getApplicationContext(),Timer_Service.class);
             stopService(intent);

                mEditor.clear().commit();

                et_hours.setEnabled(true);
                btn_start.setEnabled(true);
                tv_timer.setText("");

                break;

        }

    }

    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String str_time = intent.getStringExtra("time");
            tv_timer.setText(str_time);

        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(broadcastReceiver,new IntentFilter(Timer_Service.str_receiver));

    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(broadcastReceiver);
    }
}

Timer_Service.java
package com.countdowntimerservice;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.util.Log;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

public class Timer_Service extends Service {

    public static String str_receiver = "com.countdowntimerservice.receiver";

    private Handler mHandler = new Handler();
    Calendar calendar;
    SimpleDateFormat simpleDateFormat;
    String strDate;
    Date date_current, date_diff;
    SharedPreferences mpref;
    SharedPreferences.Editor mEditor;

    private Timer mTimer = null;
    public static final long NOTIFY_INTERVAL = 1000;
    Intent intent;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        mpref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        mEditor = mpref.edit();
        calendar = Calendar.getInstance();
        simpleDateFormat = new SimpleDateFormat("HH:mm:ss");

        mTimer = new Timer();
        mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 5, NOTIFY_INTERVAL);
        intent = new Intent(str_receiver);
    }

    class TimeDisplayTimerTask extends TimerTask {

        @Override
        public void run() {
            mHandler.post(new Runnable() {

                @Override
                public void run() {

                    calendar = Calendar.getInstance();
                    simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
                    strDate = simpleDateFormat.format(calendar.getTime());
                    Log.e("strDate", strDate);
                    twoDatesBetweenTime();

                }

            });
        }

    }

    public String twoDatesBetweenTime() {

        try {
            date_current = simpleDateFormat.parse(strDate);
        } catch (Exception e) {

        }

        try {
            date_diff = simpleDateFormat.parse(mpref.getString("data", ""));
        } catch (Exception e) {

        }

        try {

            long diff = date_current.getTime() - date_diff.getTime();
            int int_hours = Integer.valueOf(mpref.getString("hours", ""));

            long int_timer = TimeUnit.HOURS.toMillis(int_hours);
            long long_hours = int_timer - diff;
            long diffSeconds2 = long_hours / 1000 % 60;
            long diffMinutes2 = long_hours / (60 * 1000) % 60;
            long diffHours2 = long_hours / (60 * 60 * 1000) % 24;

            if (long_hours > 0) {
                String str_testing = diffHours2 + ":" + diffMinutes2 + ":" + diffSeconds2;

                Log.e("TIME", str_testing);

                fn_update(str_testing);
            } else {
                mEditor.putBoolean("finish", true).commit();
                mTimer.cancel();
            }
        }catch (Exception e){
            mTimer.cancel();
            mTimer.purge();

        }

        return "";

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e("Service finish","Finish");
    }

    private void fn_update(String str_time){

        intent.putExtra("time",str_time);
        sendBroadcast(intent);
    }
}

Thanks!

A: To keep the timer running while the app is closed, you need to use a service.
import android.app.Service
import android.content.Intent
import android.os.CountDownTimer
import android.os.IBinder
import java.util.concurrent.TimeUnit

class TimerService : Service() {

    private val finishedIntent = Intent(ACTION_FINISHED)

    private val tickIntent = Intent(ACTION_TICK)

    private lateinit var timer: CountDownTimer

    override fun onCreate() {
        timer = createTimer()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        timer.start()
        return START_NOT_STICKY
    }

    override fun onBind(intent: Intent?): IBinder? = null

    override fun onDestroy() {
        timer.cancel()
    }

    private fun createTimer(): CountDownTimer =
        object : CountDownTimer(COUNTDOWN_LENGTH, COUNTDOWN_INTERVAL) {
            override fun onTick(millisUntilFinished: Long) {
                tickIntent.putExtra(TIME_LEFT_KEY, millisUntilFinished)
                sendBroadcast(tickIntent)
            }

            override fun onFinish() {
                sendBroadcast(finishedIntent)
                stopSelf() // Stop the service within itself NOT the activity
            }
        }

    companion object {

        const val ACTION_FINISHED: String = "your.pkg.name.ACTION_FINISHED"

        const val ACTION_TICK: String = "your.pkg.name.ACTION_TICK"

        const val TIME_LEFT_KEY: String = "timeLeft"

        private val COUNTDOWN_INTERVAL = TimeUnit.SECONDS.toMillis(1)

        private val COUNTDOWN_LENGTH = TimeUnit.MINUTES.toMillis(5)
    }
}

Add the service to the AndroidManifest.xml
<application ...>
    <service android:name=".TimerService"
             android:description="@string/timer_service_description"
             android:exported="false"/>
   ...
</application

Listen to the broadcast of the service in the activity.
class MainActivity : AppCompatActivity() {

    private val timerReceiver = TimerReceiver()

    override fun onCreate(savedInstanceState: Bundle?) {
        // ...
        val intent = Intent(this, TimerService::class.java)
        startService(intent) // This kicks off the timer when the activity is launched. Move to a click handler if needed.
    }

    override fun onResume() {
        super.onResume()
        registerReceiver(timerReceiver, IntentFilter(TimerService.ACTION_TICK))
        registerReceiver(timerReceiver, IntentFilter(TimerService.ACTION_FINISHED))
    }

    override fun onPause() {
        unregisterReceiver(timerReceiver)
        super.onPause()
    }

    private inner class TimerReceiver : BroadcastReceiver() {

        override fun onReceive(context: Context?, intent: Intent?) {
            if (intent == null) return

            when (intent.action) {
                TimerService.ACTION_TICK -> {
                    val timeLeft = intent.getLongExtra(TimerService.TIME_LEFT_KEY, 0)
                    updateUIForTick(timeLeft)
                }
                TimerService.ACTION_FINISHED -> updateUIForTimerFinished()
            }
        }
    }
}

See this SO answer to learn whether registering the receiver in onCreate, onStart, or onResume is right for you.

A: Run it in a service as such: use create a broadcast receiver in your activity and have the service send broadcasts.
package com.example.cdt;

import android.app.Service;
import android.content.Intent;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.util.Log;

public class BroadcastService extends Service {

    private final static String TAG = "BroadcastService";

    public static final String COUNTDOWN_BR = "your_package_name.countdown_br";
    Intent bi = new Intent(COUNTDOWN_BR);

    CountDownTimer cdt = null;

    @Override
        public void onCreate() {
            super.onCreate();

            Log.i(TAG, "Starting timer...");

            cdt = new CountDownTimer(30000, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {

                    Log.i(TAG, "Countdown seconds remaining: " + millisUntilFinished / 1000);
                    bi.putExtra("countdown", millisUntilFinished);
                    sendBroadcast(bi);
                }

                @Override
                public void onFinish() {
                    Log.i(TAG, "Timer finished");
                }
            };

            cdt.start();
        }

        @Override
        public void onDestroy() {

            cdt.cancel();
            Log.i(TAG, "Timer cancelled");
            super.onDestroy();
        }

        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            return super.onStartCommand(intent, flags, startId);
        }

        @Override
        public IBinder onBind(Intent arg0) {
            return null;
        }
}

From the main activity:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    startService(new Intent(this, BroadcastService.class));
    Log.i(TAG, "Started service");
}

private BroadcastReceiver br = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        updateGUI(intent); // or whatever method used to update your GUI fields
    }
};

@Override
public void onResume() {
    super.onResume();
    registerReceiver(br, new IntentFilter(BroadcastService.COUNTDOWN_BR));
    Log.i(TAG, "Registered broacast receiver");
    }

@Override
public void onPause() {
    super.onPause();
    unregisterReceiver(br);
    Log.i(TAG, "Unregistered broacast receiver");
}

@Override
public void onStop() {
    try {
        unregisterReceiver(br);
    } catch (Exception e) {
        // Receiver was probably already stopped in onPause()
    }
    super.onStop();
}
@Override
public void onDestroy() {
    stopService(new Intent(this, BroadcastService.class));
    Log.i(TAG, "Stopped service");
    super.onDestroy();
}

private void updateGUI(Intent intent) {
    if (intent.getExtras() != null) {
        long millisUntilFinished = intent.getLongExtra("countdown", 0);
        Log.i(TAG, "Countdown seconds remaining: " +  millisUntilFinished / 1000);
    }
}

Note I got this code from How to run CountDownTimer in a Service in Android?, which I modified for my own android countDownTimer.

A: The Best Way to use System.currentTimeMillis() and manage your CountDown. See the Below Code after searching everywhere this code work perfectly (this is Kotlin Solution)
TimerService : Service()
override fun onStartCommand(intent:Intent?, flags:Int, startId:Int):Int {
    val  mSharePref= getSharedPreferences("BillingActivity", MODE_PRIVATE)
    val day  = mSharePref.getLong("futureTime", 0)
    val curDateTime = System.currentTimeMillis()
    var diff = day - curDateTime
    if (diff < 0)diff = 0L
    Toast.makeText(this, "$diff", Toast.LENGTH_SHORT).show()
    countDown(diff)
    return START_STICKY
  }

private fun countDown(day: Long){
    cdt?.cancel()
    val  mSharePref= getSharedPreferences("BillingActivity", MODE_PRIVATE)
    cdt = object : CountDownTimer(day, 1000) {
        override fun onTick(millisUntilFinished: Long) {
            val mDays = millisUntilFinished / (24 * 60 * 60 * 1000)
            val mHours = millisUntilFinished / (60 * 60 * 1000) % 24
            val mMinutes = millisUntilFinished / (60 * 1000) % 60
            val mSeconds = millisUntilFinished / 1000 % 60
            val timeFormat = String.format(Locale.getDefault(), "Day: %02d, Time: %02d:%02d:%02d", mDays, mHours, mMinutes, mSeconds)
            bi.putExtra("time", timeFormat)
            bi.putExtra("milis", millisUntilFinished )
            sendBroadcast(bi)
        }

        override fun onFinish() {
            bi.putExtra("time", "Finish")
            sendBroadcast(bi)
        }
    }.start()
}

And in Main Activity
Main Activity
override fun onResume() {
    super.onResume()
    startService(Intent(this, TimerService::class.java))
}

Thanks you

A: There's another way to implement it without using a service. I used SharedPreference to handle the app close scenario.
This is my code:
override fun onResume() {
    super.onResume()

    binding.state = getReadingState()

    when (binding.state) {
        SessionState.NOT_STARTED -> {

        }
        SessionState.PAUSED -> {
            startService()
            val startTime = if (getSessionPauseTime() > 0)
                getSessionStartTime() + (Date().toMillis() - getSessionPauseTime())
            else getSessionStartTime()
            updateTimer(startTime)
        }
        SessionState.IN_PROGRESS -> updateTimer(getSessionStartTime())
        else -> Unit
    }
}

fun Context.getReadingState(): ReadingSessionState {
    return when {
        getSessionPauseTime() > 0 -> SessionState.PAUSED
        isReadingSessionRunning() -> SessionState.IN_PROGRESS
        else -> SessionState.NOT_STARTED
    }
}

fun onStartClicked(){
    setSessionPauseTime(0)
    setSessionStartTime(Date().toMillis())
    binding.state = SessionState.IN_PROGRESS
}

fun onStopClicked() {
    val lastPauseMillis = getSessionPauseTime()
    val lastStartMillis = getSessionStartTime()
    if (lastPauseMillis > 1000) {
        setSessionPauseTime(0)
        setSessionStartTime(lastStartMillis + (Date().toMillis() - lastPauseMillis))
    }
    onPauseClicked()
}

fun onPauseClicked() {
    setSessionPauseTime(Date().toMillis())
    binding.state = SessionState.PAUSED
}

override fun onResumeClicked() {
    val lastPauseMillis = getSessionPauseTime()
    val lastStartMillis = getSessionStartTime()
    setSessionPauseTime(0)
    if (lastPauseMillis > 1000)
        setSessionStartTime(lastStartMillis + (Date().toMillis() - lastPauseMillis))
    binding.state = SessionState.IN_PROGRESS
}


text:
Q: Legend Modification in Gnuplot 4.6 Hello fellow stackoverflow users,
I have been sitting for several days on the following problem with which I need your help.
I would like to create a plot for my thesis, which should resemble the embedded plot.

Line type, etc all pose no problem at all.
However, I would like to create a similar legend in my plot. I don't even know what keywords to search for. I have tried a few things from other stackoverflow posts i found, but nothing provides an adequate result.

A: Good question, and I don't know of a good way to produce the type of legend you ask for.
The lines and numbers (the "body" of the table, so to say) can be achieved rather easily with the maxrows option of set key.
But the real challenge are the column headers. In gnuplot, a key entry is always build from a sample of the plot style (line, point...) and a text string. I first tried to add the column headers via keyentry, however, this will not give any string at the place where the plot sample would be. I can only suggest a workaround: Build the table body as a key, and add the column headers with a manually placed label.
array numbers[4] = [0.60, 0.64, 0.68, 0.70]
set key t r maxrows 4 vertical width -5 at graph 0.95, 0.9
set label 1 '{/:Italic t}/ms Flamelet DNS  ' at graph 0.95,0.925 r
plot for [i=1:4] i*x w l lc i t sprintf('%.2f', numbers[i]), for [i=1:4] i w p lc i t ' '

Assuming that you use LaTeX for your thesis, you could of course replace the formatting in the label to LaTeX syntax: set label 1 '$t$/ms ....
Most probably the amount of spaces will need several iterations of finetuning before you are happy with the result.
But maybe someone else has a nicer, less "hacky" solution?
PS: arrays require gnuplot >= 5.2, in 4.6 you might instead use a string of numbers and split it with word(), however, this has no effect on the approach. Anyway, you might consider updating, the current stable release is 5.4.


text:
Q: how to show multiple fields in a single column editor in extjs grid We are building an application which is using the grid to show records. Now we cam across with a requirement to show 2 fields(1combo and 1 textfield) in a single cell editor. we have tried with 2columns with 2editors but the problem here is we need to enable the both cell editors at the same time.
this link http://blog.platinastudio.com/?attachment_id=2485 can be helpful for understanding the requirement clearly.
any help will be greatly appreciated!!
Thanks
Sanjeeva

A: If you are able to use two columns and 2 editors, then you should just need to do the wiring manually, and it should work okay.

*

*For each editor, listen for the beforeedit event

*In the handler, call startEdit on the other editor

You'll need to configure the editors to not reset on blur probably, and there may be additional configuration needed to get the interactions right, but in theory it should work out.

A: If you are trying to use two editors in the same cell, then you can mention xtype:'container' in the editor configuration of the column and add your fields in this container.
An example of this is given here


text:
Q: Add Values to a Range Based on Another Range's Row Number I am working on a way to generate a list based on the value of each row in a given column (G).  Currently the list can copy entire rows and works perfectly.  It pulls all rows if column G contains the required text ("Card") and puts them in a list on another spreadsheet with no gaps.
The problem is that I want the list to only contain information from a few columns in each row containing "Card", not the whole row.
Is there a way to make my macro pull the information only from columns "A", "G", and "ET"?
The code I am currently using is below:
'----Alonso Approved List Generator----'
Sub AlonsoApprovedList()
  Dim cell As Range
  Dim NewRange As Range
  Dim MyCount As Long
  Dim ExistCount As Long
  ExistCount = 0
  MyCount = 1
'----For every cell in row G on the ESI Project Data sheet----'
  For Each cell In Worksheets("ESI Project Data").Range("G6:G5000")
  If cell.Value = "Card" Then
      ExistCount = ExistCount + 1
      If MyCount = 1 Then Set NewRange = cell.Offset(0, -1)
      '----Sets up a new range to copy all data from the row if column G in that row contains the value in question----'
      Set NewRange = Application.Union(NewRange, cell.EntireRow)
      MyCount = MyCount + 1
  End If
  Next cell
  If ExistCount > 0 Then
      NewRange.Copy Destination:=Worksheets("Alonso Approved List").Range("A3")
  End If
End Sub

So in short I want to modify the code above to take data from one worksheet and generate a list in another given the row number from the "cell" range and specific columns.
Column G drop down data validation lists containing one of the following items:

Card Mortgage Auto Retail Commercial Investment Advisors Collections Operations Information Technology Community Affairs HR Marketing Property Executive Finance Risk Credit Sourcing Staff Admin RCC

Is that possible?
It would be really nice if I could use something like the match function to determine the columns to use by their title.
To clarify, this spreadsheet is updated regularly by multiple different users so the information is not static.  Rows are added and changed frequently and occasionally deleted.  As such I cannot just copy cell values from the original sheet to the new list.
Question responses:

*

*Column G drop down data validation lists containing one several items. A complete list is in a different worksheet. Users go in to each line item and select from a specific category.

*The other columns in question contain a line item's name, category (same as column G), a monetary value, and a date.

*I am hesitant to upload data because much of it is company information. My goal is to have a macro automatically copy multiple cells from the same row to another sheet. The looping and detection of correct rows is already there. Basically, is there a way to replace "cell.EntireRow" (copying the whole row) with a few select rows in that cell?

A: I wanted to come back and update this quesion with an answer.  It is a bit delayed but an answered question is better than a permanently open question...
Sub ApprovedList()

Dim cell As Range
Dim rngDest As Range
Dim i As Long
Dim arrColsToCopy

    arrColsToCopy = Array(1, 3, 4, 5)
    '----For every cell in row G on the ESI Project Data sheet----'
    Set rngDest = Worksheets("Alonso Approved List").Range("A3")

    Application.ScreenUpdating = False

    For Each cell In Worksheets("ESI Project Data").Range("G6:G5000").Cells

        If cell.Value = "Card" Then

            For i = LBound(arrColsToCopy) To UBound(arrColsToCopy)
                With cell.EntireRow
                    .Cells(arrColsToCopy(i)).Copy rngDest.Offset(0, i)
                End With
            Next i

            Set rngDest = rngDest.Offset(1, 0) 'next destination row

        End If

    Next cell

    Application.ScreenUpdating = True

End Sub


text:
Q: I'm unable to figure out how to prevent getting this CORS error in Node.js I'm trying to figure out how to create a real time chat application that uses Vue.js for the front-end, Node.js for the back-end and socket.io.
I've generated my back-end Node.js project with express-generator and the project is accessible at http://localhost:3000. In this project I have an app.js file that contains this:
var express = require('express');
var http = require('http').createServer(express);
var io = require('socket.io')(http);

io.on('connection', (socket) => {
    console.log('a user connected');
});

My front-end is a Vue.js project accessible from http://localhost:8080 and the component that is meant to connect to my back-end contains this:
<template>
    <div class="home">

    </div>
</template>

<script>
import socket from 'socket.io-client'

export default {
    mounted(){
        socket.connect('http://localhost:3000')
    }
}

</script>

Sadly the socket connection doesn't seem to go through. On the front-end console I get these errors -
localhost/:1 Access to XMLHttpRequest at 'http://localhost:3000/socket.io/?EIO=3&transport=polling&t=N6Kc6yn' from origin 'http://localhost:8080' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

And on the back-end console I get this error - GET /socket.io/?EIO=3&transport=polling&t=N6KcMan 404 3.089 ms - 975
I tried installing cors through npm install cors and added the required code but nothing really happened. It looks like this:
var express = require('express');
var cors = require('cors');
var app = express();
app.use(cors());

var http = require('http').createServer(express);
var io = require('socket.io')(http);

io.on('connection', (socket) => {
    console.log('A user has connected!');
});

I can't figure out why is this happening.

A: Try removing this -> app.use(cors()); if the problem persist you could have a bad path.


text:
Q: High Value at Each Granularity I have an table below which shows some data and I am trying to get the high value from each row.
Below is the data I have:
Table A

Once calculated it should looks like below in tableau
Table B

Notice that for Total, its not summing up from pers and bus instead its getting it highest value from total from table A and same concept is for Grand Total. Numbers which you see are balance.
I am able to get high value up to Total but its the grand total where I am struggling with. Below is my Calculation which I am using.
if
countd([Category]) = 1 then
sum({ FIXED [Group], [Category]: max(
{ FIXED [Group], [Category], [Date]: SUM([Balance])})})
ELSE
sum({ FIXED [Group]: max(
{ FIXED [Group], [Date]: SUM([Balance])})}
)
END

A: Step-1: For max of categories, use this calculation desired maximums
MAX({Fixed [MVRA Group], [Product Category], [Date Display]: ([Primary Measure])})

STEP-2: For max of subtotal, use desired sub-total maximum
MAX({Fixed [MVRA Group], [Date Display]: ([Primary Measure])})

https://drive.google.com/file/d/1zyjCDdG_QECrkFgY-UFm7WM2yN1xaHmZ/view?usp=sharing


text:
Q: Trouble with utf-8 encoding/decoding I am reading a .csv which is UTF-8 encoded.
I want to create an index and rewrite the csv.
The index is created as an ongoing number and the first letter of a word.
Python 2.7.10, Ubuntu Server
#!/usr/bin/env python
# -*- coding: utf-8 -*-
counter = 0
tempDict = {}
with open(modifiedFile, "wb") as newFile:
    with open(originalFile, "r") as file:
        for row in file:
            myList = row.split(",")
            toId = str(myList[0])

            if toId not in tempDict:
                tempDict[toId] = counter
                myId = str(toId[0]) + str(counter)
                myList.append(myId)
                counter += 1
            else:
                myId = str(toId[0]) + str(tempDict[toId])
                myList.append(myId)

            # and then I write everything into the csv
            for i, j in enumerate(myList):
                if i < 6:
                    newFile.write(str(j).strip())
                    newFile.write(",")

                else:
                    newFile.write(str(j).strip())
                    newFile.write("\n")

The problem is the following.
When a word starts with a fancy letter, such as

*

*Č

*É

*Ā

*...

The id I create starts with a ?, but not with the letter of the word.
The strange part is, that withing the csv I create, the words with the fancy letters are written correct. There are no ? or other symbols which indicate a wrong encoding.
Why is that?

A: By all means, you should not be learning Python 2 unless there is a specific legacy C extension that you need.
Python 3 makes major changes to the unicode/bytes handling that removes (most) implicit behavior and makes errors visible. It's still good practice to use open('filename', encoding='utf-8') since the default encoding is environment- and platform-dependent.
Indeed, running your program in Python 3 should fix it without any changes. But here's where your bug lies:
        toId = str(myList[0])

This is a no-op, since myList[0] is already a str.
            myId = str(toId[0]) + str(counter)

This is a bug: toId is a str (byte string) containing UTF-8 data. You never, ever want to do anything with UTF-8 data except process it one character at a time.
with open(originalFile, "r") as file:

This is a style error, since it masks the built-in function file.
There are two changes to make this run under Python 2.

*

*Change open(filename, mode) to io.open(filename, mode, encoding='utf-8').

*Stop calling str() on strings, since that actually attempts to encode them (in ASCII!).

But you really should switch to Python 3.
There are a few pieces new to 2.6 and 2.7 that are intended to bridge the gap to 3, and one of them is the io module, which behaves in all the nice new ways: Unicode files and universal newlines.
~$ python2.7 -c 'import io,sys;print(list(io.open(sys.argv[1],encoding="u8")))' <(printf $'\xc3\x84\r\n\xc3\xb9\r\n')
[u'\xc4\n', u'\xf9\n']
~$ python3 -c 'import sys;print(list(open(sys.argv[1],encoding="u8")))' <(printf $'\xc3\x84\r\n\xc3\xb9\r\n')
['Ä\n', 'ù\n']

This can be useful to write software for both 2 and 3. Again, the encoding argument is optional but on all platforms the default encoding is environment-dependent, so it's good to be specific.

A: In python 2.x strings are by default non-unicode - str() returns a non-unicode string. Use unicode() instead.
Besides, you must open the file using utf-8 encoding through codecs.open() rather than the built-in open().


text:
Q: BeautifulSoup Installed but for Python3 but I'm Unable to Find the bs4 Module I'm using a Jupyter notebook for this on the Google Cloud Platform.
This code previously worked fine so I'm not sure what to do.
I've tried uninstalling and reinstalling, restarting the kernals, doing a pip3 install.
Any ideas would be much appreciated. I've attached an image here.

A: use this:
!pip install beautifulsoup4

from bs4 import BeautifulSoup as bs

Before doing it do Runtime->Reset all runtimes

A: Try this:
import bs4

req= requests.get("https://url")
page = req.content
soup = bs4.BeautifulSoup(page)

h1 = ...

And not
from bs4 import BeautifulSoup


text:
Q: When subject-based analysis is better than answer-based (and vice versa)? In experimental psychology one of the generally accepted practices in data analysis is the aggregation on subject level. For example, several measurements of reaction time is gathered for each subject using different stimuli, then mean reaction time is computed for each subject. Those scores are further analyzed by ANOVA or other methods.
My questions are:

*

*When this procedure is more appropriate than a simple analysis of
raw data (i.e. the analysis without any aggregation)? And when analysis of raw data is more appropriate?

*Has anyone met the discussion of these question in literature?

UPD: To give an example, suppose I'm interested in the effect of a drug on a speed of face detection. So I for each participant I have the data for drug and placebo condition (within subject design). I can analyze a) answers for each face for each subject for each condition, b) answers for each subject aggregated by condition, and, perhaps c) answers for each face aggregated by condition. When (a) is better than (b) and when it is otherwise?

A: Both, by-item and by-participant analysis are flawed. This is also known as the language-as-fixed-effect-fallacy.  The generally promoted approach is to use mixed-modeling with crossed random effects for both subjects and items. The most recent article discussing this is:
Judd, C. M., Westfall, J., & Kenny, D. A. (2012). Treating stimuli as a random factor in social psychology: A new and comprehensive solution to a pervasive but largely ignored problem. Journal of Personality and Social Psychology, 103(1), 54–69. doi:10.1037/a0028347
More references can be found in my answer to this question.
Note that you need a certain number of replications for each stimulus-subject pair to run a decent mixed model.

A: What do you mean by "simple analysis of raw data"?
I would say, given what you've written, that item-based analysis is more appropriate when you want to know about items, and subject-based is more appropriate when you want to know about subjects.
E.g, item analysis is often used in psychometrics, when constructing a test. One wants to know such things as how hard the item is, whether the people who got it right also got other questions right, whether there are patterns in the wrong answers, whether it correlates with other items etc.


text:
Q: Let $f,g\in\mathbb{L}_{\infty}$ then is a pseudo norm. Let $f,g\in\mathbb{L}_{\infty}$ then:
i)$||f||_{\infty}\geq 0$
ii)$||f||_{\infty}=o$ if $f=0$ c.t.p
iii)$||kf||_{\infty}=|k|||f||$
iv)$||f+g||_{\infty}\leq||f||_{\infty}+||g||_{\infty}$
My attempt:
iii) Let $f\in\mathbb{L}_{\infty}$ and $k\in\mathbb{K}$ then by definition:
$$||kf||_{\infty}=\sup es|kf|=k\sup es|f|=k||f||_\infty$$
i)Let $f\in \mathbb{L}_{\infty}$ then $||f||_{\infty}=\sup es|f|\geq0$ then $||f||_\infty\geq 0$
iv)Let $f,g\in\mathbb{L}_\infty$, as $f\in\mathbb{L}_\infty$ and $g\in\mathbb{L}_\infty$ then $f+g\in\mathbb{L}_\infty$.
Moreover we know by definition: $|f|\leq||f||_\infty$ and $|g|\leq||g||_\infty$ this implies:

$$|(f+g)(x)|\leq|f(x)|+|g(x)|\leq||f||_{\infty}+||g||_{\infty}$$ $\tag1$

By (1) we have:
$$||f+g||_\infty=\sup es|f+g|\leq||f||_\infty+||g||_\infty$$
I have a doubt of this last step. Can someone clarify me this?
ii) I don't have a clear idea of how solve this.
I need help for this part, thanks!!

A: $\|f\|_{\infty}$ is the least number $M$ such that $|f| \leq M$ almost everywhere.
If $M_1=\|f\|_{\infty}$ and $M_2=\|g|_{\infty}$ then $|f| \leq M_1$ almost everywhere and $|g| \leq M_2$ almost everywhere which implies $|f+g| \leq M_1+M_2$ almost everywhere. [Because union of two sets of measure $0$ has measure $0$]. Hence $\|f+g\|_{\infty} \leq \|f\|_{\infty}+\|g\|_{\infty}$.
ii)  is immediate: $f=0$ almost everywhere implies $|f| \leq 0$ almost everywhere. so $\|f\|_{\infty}=0$.


text:
Q: matching number in PHP simpletest webtestcase assert I am writing a PHP simpletest webtestcase. The following assert does not work.
$this->assertPattern('"serverTime":\d+');

for the page response

Blah Bla "serverTime":1447147314 ,Bla Bla

However when I test the regex in an online tool it works. I need to assert that the response contains a string "serverTime":<10digitnumber>

A: The function syntax is assertPattern($regexp, $x).
That means: fail, unless the regex $regexp matches $x.
The regexp you are looking for is: #\"serverTime\":(\d+){10}#.
The whole function for SimpleTest:
    public function testPattern()
    {
        $string = 'Blah Bla "serverTime":1447147314 ,Bla Bla';

        $this->assertPattern('#\"serverTime\":(\d+){10}#', $string);
    }


text:
Q: Windows Test Driver Signing not working properly I'm developing a driver for Win7/8. Everything works fine and I've tried to get rid of the signature warning by following the How to Test-Sign a Driver Package Manual from Microsoft.
I've followed all these steps but the driver appears still as "Not Digitally Signed". During the installation process the "Do you really want to trust this driver... bla bla" pops up and in the device manager the driver appears as unsigned.
The popup during installation:

The driver appears as not digitally signed in the device manager:

The cat file of the driver is signed and valid:

And the certificate is installed in the machine store (mmc.exe):
(I've also tried to put the trusted certificate in all different stores)

Does anyone have a clue what's going wrong here? I've followed exactly the suggested procedure from Microsoft.

A: You need to sign the .sys file as well.


text:
Q: Beautifulsoup: can not select child I have the following HTML and I need to get the content of tag:a, i.e "Nature" in this case:

    Nature

First I try to select 'li' with 'tag' class.
soup.findAll("all", {"class": "tag"})

How can I get the content of tag:a?

A: You can use the css selectors you may be familiar with.
>>> soup.select_one("li.tag a:nth-of-type(2)").text
u'Nature'

A: If you do a findAll on the soup it will find no need of traversing.
soup.findAll("a", {"class": "classname"})

A: You want soup.findAll("li", {"class": "tag"})[0].a, which is:

A: Hope this helps!
lis = soup.find_all('li', class_='tag')
data_rows=lis.findAll('a')
data=[data_rows[i].getText() for i in range(len(data_rows))]

Don't forget to let us know if it solved your problem :)


text:
Q: Problems in _stprintf /stscanf Unicode functions I work in VS 2017 with UNICODE data
And I get very strange errors,
working  with  format instructions
_vstprintf,
_stprintf.
_stscanf
I get wrong results,
eg:
 In function
_stprintf(str,_T("%s\t%s"),txt,nver  );
str Contains 1st character 'V' only
 and so on
What I do wrong?
Please help me!
    ```C++
    `static void a_txtf ((_TCHAR  *str,
                       _TCHAR *fmt, ...)
    {
       _TCHAR     buf[256];

       va_list   marker;

       va_start (marker, fmt);
       _vstprintf  (buf, fmt, marker);

        // Data in buf are wrong!
        // Contains 1st character only

       va_end(marker);

       int l = _tcslen (buf);
      _stprintf(str, _T("%-*s\r\n"),
                l,buf);

       // str is wrong!
       // Contains 1st character only
    }

    void main ()
    {
         _TCHAR txt[] = _T("  VERSION ");
         _TCHAR nver[] = _T("  5.123 ");
         _TCHAR line[]=_T("ORDER1\t123");

         _TCHAR str[256], name[32];
         Int num;

    a_txtf(str,_T(" %s\t %s"),txt, nver);

    _stprintf(str,_T("%s\t%s"),txt,nver
                 );
         // str is wrong!
         // Contains 1st character only

        _stscanf(line,_T("%s%d"),name,num
    );

         // name is wrong!
         // Contains something like
         // Chinese
         //text in name
         // num is OK
    }`


text:
Q: Setting up Cron Jobs as Root I can run cron jobs manually like this
root@myhosting [~]# sync ; echo 0 > /proc/sys/vm/drop_caches

I can add it in to cPanel like this. This doesnt work because I need root access.
 * */4 * * * sync; echo 0 > /proc/sys/vm/drop_caches

So that leaves me to add the job using putty logged in as root. The above code doesn't work in putty. I get command not found

A: Run crontab -e. That will put you into an editor where you can add the cron line.
If you end up in an editor you don't know how to use, you can change it temporarily with
EDITOR=nano crontab -e

A: That is because this is not command line syntax. You'll need to get into the crontab editor in order to add your requested line. The most common way to do this is with the following line:
crontab -e

This will open your existing crontab. Add your proper crontab line to it, and then write/save.