text:
Q: awk or sed command to match regex at specific line, exit true if success, false otherwise I need to determine if a file contains a certain regex at a certain line and to return true (exit 0) if found, and otherwise false. Maybe I'm overthinking this, but my attempts proved a tad unwieldy. I have a solution, but I'm looking for maybe others that I hadn't thought of. I could use perl, but I'm hoping to keep this "lightweight" as possible as it runs during a puppet execution cycle.
The problem is common enough: in RHEL6, screen was packaged in a way that limited the terminal width to 80 characters, unless you un-comment the line at 132. This command checks to see if that line has already been fixed:
 awk 'NR==132 && /^#termcapinfo[[:space:]]*xterm Z0=/ {x=1;nextfile} END {exit 1-x}' /etc/screenrc

Note: if the file has fewer that 132 lines, it must exit with false.
I thought sed would be of help here, but apparently then you have to do weird tricks like null-substitutions and branches. Still, I'd like to see a sed solution just to learn. And maybe there is something else I overlooked.
EDIT 1: Added nextfile to my awk solution
EDIT 2: Benchmarks  EDIT 3: Different host (idle). EDIT 4: mistakenly used Gile's awk time for optimized-per's run. EDIT 5: new bench
Benchmarks
First, note: wc -l /etc/screenrc is 216.
50k iterations when line not present, measured in wall-time:

*

*Null-op: 0.545s

*My original awk solution: 58.417

*My edited awk solution (with nextfile): 58.364s

*Giles' awk solution: 57.578s

*Optimized perl solution 90.352s  Doh!

*Sed 132{p;q}|grep -q ... solution: 61.259s

*Cuonglm's tail | head | grep -q : 70.418s  Ouch!

*Don_chrissti's head -nX |head -n1|grep -q: 116.9s  Brrrrp!

*Terdon's double-grep solution: 65.127s

*John1024's sed solution: 45.764s
Thank you John and thank you sed! I am honestly surprised perl was on-par here. Perl loads in a bunch of shared libraries on startup, but as long as the OS is caching them all, it comes down to the parser and byte-coder. In the distant past (perl 5.2?) I found it was slower by 20%. Perl was slower as I originally expected but appeared to be better due to a copy/paste error on my part.
Benchmarks Part 2
The biggest configuration file which has practical value is /etc/services. So I've re-run these benches for this file and where the line to be changed is 2/3rds in the file. Total lines is 1100, so I picked 7220 and modified the regex accordingly (so that in one case it fails, in another it succeeds; for the bench it always fails).

*

*John's sed solution: 121.4s

*Chrissti's {head;head}|grep solution: 138.341s

*Counglm's tail|head|grep solution: 77.948s

*My awk solution: 175.5s

A: With POSIX toolchest:
tail -n +132 </etc/screenrc | head -n 1 | grep -q pattern

A: You can do it in more efficiently in awk: exit as soon as you've hit the relevant line.
awk 'NR==132 {if (/^#termcapinfo[[:space:]]*xterm Z0=/) found=1; exit}
     END {exit !found}' /etc/screenrc

Alternatively, you can use GNU sed (but portable sed doesn't let you specify the exit code).
Alternatively, you can use the Unix philosophy of combining tools together: extract the line you want with head and tail, and pass it to grep.
</etc/screenrc tail -n +132 | head -n 1 |
grep -q '^#termcapinfo[[:space:]]*xterm Z0='

Or you can use sed to extract the desired line:
</etc/screenrc sed -n '32 {p; q;}' |
grep -q '^#termcapinfo[[:space:]]*xterm Z0='

(Both of these rely on the fact that you want the same outcome for an empty line and for a file that's too short.)
For such a small file, the fastest approach is likely to be one that uses a single tool, as the overhead of launching multiple programs will be larger than the performance gain from using special-purpose tools such as head, tail and sed. If you wanted line 132000000, starting off with tail -n +132000000 would likely be faster than anything else.

A: Some alternatives with ed:
ed -s infile <<\IN
132s/^#termcapinfo[[:space:]]*xterm Z0=/&/
q
IN

or sed+grep:
sed '132!d;q' infile | grep -q '^#termcapinfo[[:space:]]*xterm Z0='

In both cases, if infile has less than 132 lines or if line 132 doesn't match the pattern, the exit code is 1. Both should be quite portable, ed will read the whole file in memory though...
If you're working with huge files then head may be faster then sed e.g.:
{ head -n 131 >/dev/null; head -n 1; } <infile | grep -q '^#termcapinfo[[:space:]]*xterm Z0='

A: With GNU sed:
sed -n '132 {/^#termcapinfo[[:space:]]*xterm Z0=/q}; $q1'

How it works

*

*132 {/^#termcapinfo[[:space:]]*xterm Z0=/q}
On line 132, check for the regex ^#termcapinfo[[:space:]]*xterm Z0=.  If found quit, q, with the default exit code of 0.   The rest of the file is skipped.

*$q1
If we reach the last line, $, then quit with exit code 1: q1.
Efficiency
Since it is not necessary to read past the 132nd line of the file, this version quits as soon as we reach the 132nd line or the end of the file, whichever occurs first:
sed -n '132 {/^#termcapinfo[[:space:]]*xterm Z0=/q; q1}; $q1'

Handling empty files
The version above will return true for empty files.  This is because, if the file empty, no commands are executed and the sed exits with the default exit code of 0.  To avoid this:
! sed -n '132 {/^#termcapinfo[[:space:]]*xterm Z0=/q1; q}'

Here, the sed command exits with code 0 unless the the desired string is found in which case it exits with code 1  The preceding ! tells the shell to invert this code to get back to the code we want.  The ! modifier is supported by all POSIX shells.  This version will work even for empty files.  (Hat tip: G-Man)

A: I know you said you didn't want to use perl. I think you're operating under a misconception about how 'lightweight' it is.
You could do this:
#!/usr/bin/env perl

use strict;
use warnings;

open ( my $input_fh, '<', "/etc/screenrc" ) or die $!;
while ( <$input_fh> ) {
   if ( $. == 132
   and m/^#termcapinfo[[:space:]]*xterm Z0=/ ) {
       exit 0;
   }
}

exit 1;

Which you can condense to a one liner:
perl -ne 'exit 0 if $. == 132 and  m/^#termcapinfo[[:space:]]*xterm Z0=/ END { exit 1 }'

A: You could always use a couple of greps:
grep -nm 1 "^#termcapinfo[[:space:]]*xterm Z0=" /etc/screenrc | grep -q '^132:'

The -n adds the line number to each matched line in grep's output. For example:
$ seq 11 15 | grep -n 5
5:15

The -m 1 (which, unlike the other two, is not defined by POSIX and might not be available in your grep implementation) makes grep exit after the first match.
So, the first grep looks for lines matching the regex and prints them along with the line number. The second grep will silently (-q) return true if an input line starts with 132:, so it will only be true if the regex matched line 132.

Here's another simple Perl approach:
perl -ne '$.==132 && !/^#termcapinfo\s*xterm Z0=/ && exit(1);'

The idea is to exit with a status of 1 only if line 132 doesn't match the regex. It will, therefore, exit with 0 otherwise. You could make it a bit more efficient (but more complex) by only checking the relevant line:
perl -ne '$.==132 && !/^#termcapinfo\s*xterm Z0=/ && exit(1); exit(1) if $.>132'

You could also simplify your original awk a little:
awk 'NR==132 && /^#termcapinfo[[:space:]]*xterm Z0=/{exit 0} NR>132{exit 1}'

A: A workaround with head, tail, wc, and grep. (if loop in bash syntax)
if [[ $(head -n 132 file | wc -l) -eq 123 &&\
    $( head -n 132 file | tail -n 1 |\
    grep '^#termcapinfo[[:space:]]*xterm Z0=') ]] ; then
  echo success
else
  echo fail
fi

A: For completeness' sake, the ruby solution:
 ruby -e 'while gets do;  if $.==132 ; exit(/^#termcapinfo[[:space:]]*xterm Z0=/?0:1); end; end; exit(1)' /etc/screenrc

I don't see a way of using ruby -n here without calling at_exit() in every iteration of the file-line read.
The MRI (Matz Ruby Interpreter, 1.8.7) takes insanely long clocking it at 139s.


text:
Q: Capitalize text input on Fabric JS I have an HTML5 canvas which I intend writing on. I am using FabricJS. However, I want the text input to be in uppercase without the user having to use "caps lock".
I have tried
textbox.hiddenTextarea.autoCapitalize = "on";
and
let textbox = new fabric.IText("", {
            textAlign: "center",
            autoCapitalize: "on",
}
I also even tried :
textbox.hiddenTextarea.onkeyup = (e) => {
            e.target.value = e.target.value.toUpperCase(); }
and nothing works. What is the proper way to do what I'm trying to achieve? Or is there any hack? Please point me in the right direction.

A: you can use this syntax.
Kindly get activeObject then.
activeObject.set('fontCharacterStyle', 'Caps');

A: I have created a subclass of IText to allow setting textTransformation to uppercase:
const TransformableText = fabric.util.createClass(fabric.IText, {
  _splitTextIntoLines: function() {
    const transformedText = this.textTransform === 'uppercase' ? this.text.toUpperCase() : this.text;

    return this.callSuper('_splitTextIntoLines', transformedText);
  },
});

Can be used as:
const textbox = new TransformableText("", { textTransform: "uppercase" });

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why is my Promise always hitting the catch() method? I'm using the JavaScript Promise object with a then(), catch().
The console.log in the catch() method always runs, regardless of the response from the API ("STATUS_SUCCESS" or "STATUS_FAILED").
Is this normal behaviour in promises or is there a way to only hit the catch() method if the response has failed?
Updated with live example:
sendAccountDataToBackend(response) {

    const { formData } = response;

    const requestObj = {
        url: 'http://localhost:3000/api/validate',
        data: {
            firstname: 'dummy_firstname',
            lastname: 'dummy_lastname',
            email: 'dummyemail'
        }
    };

    let p = new Promise((resolve, reject) => {
        account.Utils.globalAjaxRequest(requestObj, (success) => {
            if(success.status === 'STATUS_SUCCESS') {
                resolve();
                console.log('resolved: ', p)
            } else {
                reject();
                console.log('rejected: ', p);
            }
        });
    })

    p.then(() => {
        console.log('Then: ', response);
    }).catch(() => {
        console.log('catch:', response);
    })
}

A: You can find the exact cause of the thrown error by printing it.
Change your catch handler to look like this:
catch((e) => {
    console.log('Catch', e);
})

In addition to "Catch" you will see a description of the error in the console.

A: I figured out what was causing the catch to fire thanks to @pfcodes suggestion. I was calling a function within the then() block which was failing. Once removed, it stayed inside then(). Silly mistake that was over looked! Thanks for your suggestions.

A: Regarding the question:

Is this normal behaviour in promises or is there a way to only hit the catch() method if the response has failed?

It is easy to demonstrate that the catch is only entered when the reject call is made.

function testPromise(shouldReject)
{
  return  new Promise((resolve, reject) => {
       setTimeout(function(){
           if(shouldReject) reject();
           else resolve();
       },1000);
  });
}

function handlePromise(p, name){

  p.then(() => {
      console.log(name, 'Then');
  }).catch(() => {
      console.log(name, 'Catch');
  })
}

var rejectPromise = testPromise(true);
var resolvePromise = testPromise(false);
handlePromise(rejectPromise,"reject");
handlePromise(resolvePromise,"resolve");

So, what this means is that in your code, for whatever reason (probably badly handled asynchronous ajax call) you're entering the else block.

Regarding your update, I would say that success.status is returning something other than "STATUS_SUCCESS" for the reasons demonstrated by the code above.
Try adding console.log(success) inside the ajax callback.
account.Utils.globalAjaxRequest(requestObj, (success) => {
    console.log(success);
    ....


text:
Q: Fheatmap error message and data file I am starting with R trying to make a heatmap of 41,000 coordinate pairs.  They are arranged in simple text file which I imported into R as V1 and v2.
To begin exploring the fheatmap command and functions, I simply used
fheatmap(test)

where test is the name of my data.  I receive the following error.

Error in grid.Call.graphics(L_setviewport, vp, TRUE) :
    non-finite location and/or size for viewport
  In addition: Warning message:
  In max(unlist(length_npc(list_name = row_names, dim = "width", font_size = row_fontsize))) :
    no non-missing arguments to max; returning -Inf

If anyone has experience with this function I would appreciate some guidance.
Edit: The "heat" would be based on the frequency of XY points that occupy a common space. In addition to learning about R, my ultimate goal is to cross validate a heatmap produced by my own C# code with something else.
heatmap in my C# code

A: Please import following external libraries and then try using "fheatmap"
Imports: grid, RColorBrewer , gdata, ggplot2, reshape2, plots
Like the following
library(grid)
library(RColorBrewer)
library(gdata)
library(ggplot2)
library(plots)
library(reshape2)
If above libraries are not already installed , use following command install.packages("ggplot2") to install all the packages.


text:
Q: Selenium in Python not finding any elements I have written numerous scripts to scrape websites. I am looking to scrape games and odds from here
I am not able to find any elements at all. I have looked for almost all the div items, but tried root, and it didn't work.
The code:
from selenium import webdriver

from selenium.webdriver.common.keys import Keys

options = webdriver.ChromeOptions()
options.add_argument("--enable-javascript")
driver = webdriver.Chrome('C:\\Location\\chromedriver',options=options)

driver.get('https://sportsbook.fanduel.com/navigation/nba')
time.sleep(20)
events = driver.find_element_by_xpath('//div[id="root"]')

I am able to find the root item. But I am unable to find other elements:
For example, the games are contained in a div with the classes ae aj im s h i j ak l m al o am q an.
Added this line of code:
events = driver.find_elements_by_xpath('//div[@class="ae aj im s h i j ak l m al o am q an"]')

But the events variable is empty: []

A: You have to prefix attributes with @. So, the following should work
events = driver.find_element_by_xpath('//div[@id="root"]')


text:
Q: For what value of $h$ is the minima equal to $-5$ I have some questions regarding this exercise.

$f_h(x)=x^4-hx^2$
"For what value of $h$ is the minima equal to $-5$"

What I would have thought is correct:
$f_h'(x)=(4x^3-2hx)=0$
$=x(4x^2-2h)=0$
$x=0$ and $x=\pm\sqrt{\frac{h}{2}}$
Then, I would say okay, well if $h=10$ then this would satisfy the question. Meaning the answer is $h=10$. But for some reason, the answer sheet states the following steps instead:
Take $x=\pm\sqrt{\frac{h}{2}}$ and input into the function:
$f(-\sqrt{\frac{h}{2}})=f(\sqrt{\frac{h}{2}})$
=
${\frac{h^2}{2}}=5$ Therefore, $h=\sqrt{10}$.
I don't quite get how that way worked. They figured out the slope, put it into the original equation and equaled it to $-5$, how does that give them the required value.
Would appreciate some explanation, thanks in advance.

A: The minimum of the function should be $-5$ . It means if $f'(a) = 0$ then $f(a) = -5$ . Here we have $a = \pm \sqrt {h/2}$

A: you have combined things that should be written separately. For a chosen $h,$ the minimum value occurs when $x = \pm \sqrt {h/2}.$ Let's see, the original function was $f_h(x)=x^4 - h x^2.$ Alright
$$ f_h(  \sqrt {h/2} ) = \frac{h^2}{4} - \frac{h^2}{2} =  - \frac{h^2}{4} \; . $$
They want this to be $-5,$ so we need $$  - \frac{h^2}{4} = -5, $$
$$  h^2 = 20, $$
but $h$ must be positive so
$$ h = \sqrt{20} = 2 \sqrt 5$$
Always wise to check. We have $\frac{h}{2} = \sqrt 5,$ so that the $x$ value we are using is $5^{1/4}.$ Then the function value becomes
$$ 5 -   2 \sqrt 5 \sqrt 5 = 5 - 10 = -5  $$
Note that $\sqrt{20} \approx 4.47 \; , \;$ while $5^{1/4} \approx 1.49534878$ is pretty close to $\frac{3}{2}$

A:
$x=0$ and $x=\pm\sqrt{\frac h2}$
Then, I would say okay, well if $h=10$ then this would satisfy the question.

What?  Why?  I don't understand this at all.
....

I don't quite get how that way worked. They figured out the slope,

Not quite, this isn't a line so there is no single slope.  They figured out what the derivative was and this gives a formula for the slope (of the tangent line) at any given $x$.
What the actually figured out was the three points where the slope will be equal to $0$.  At $x = 0$ then the slope of the tangent line is $0$.  ANd $x= \sqrt{\frac h2}$ the slope of the tangent line is $0$ and at $x= -\sqrt{\frac h2}$ the slope of the tangent line is $0$.  At all other values of $x$ the slope of the tangent line is not $0$.

put it into the original equation

Not quite.  The slope at $x_0$ is $0$.  They did not put the slope into the original equation.  They put the value of $x$ where $f'(x) = 0$ back into the original equation.
So when $f'(x) = 0$ then $f(x)$ is at an extreme value.

and equaled it to −5.

Because we were told $f(x) = -5$ when $x$ is such that $f(x)$ is a minimum value.

how does that give them the required value.

It's a basic observation, that extrema points (max, mins, and saddles) of continuous functions can only and always appear when the slope of the tangent line is $0$.
So .... if $(x_0, f(x_0))$ is a local minimum, then $f'(x_0) = 0$.  And if $f'(x_0) =0$ then $x_0 = 0$ or $x_0 =\pm \sqrt{\frac h2}$.
So either $(0, f(0)) = (0, 0)$ is the minimum value $(0, -5)$  (which is impossible as $0 \ne -5$.
or $(\sqrt{\frac h2}, f(\sqrt{\frac h2})) = (\sqrt{\frac h2}, \frac {h^2}4 - h* \frac h2)= (\sqrt{\frac h2}, -\frac {h^2}4)$ is the minimum value of $(\sqrt{\frac h2}, -5)$
Or $(-\sqrt{\frac h2}, f(-\sqrt{\frac h2}) =  (-\sqrt{\frac h2}, \frac {h^2}4 - h* \frac h2)= (-\sqrt{\frac h2}, -\frac {h^2}4)$ is the minimum value of $(-\sqrt{\frac h2}, -5)$
As $f(0) = 0 > -5$ that is neither the minimum nor is it $-5$.
So $f(\pm \sqrt{\frac h2} = -\frac {h^2}4 = -5$ are the two local minima.
So what is the $h$ that will make this true?
So we solve for $-\frac {h^2}4  = -5$.
Which is $h=\pm \sqrt{20}$.  But for $x = \pm \sqrt {\frac h2}$ to be defined we must have $h\ge 0$ so $h = \sqrt{20}$.


text:
Q: Stocks sources of other website's showing on applying store switcher in admin Ours is the multi website store(UAE and Oman), and each website is assigned its own stock source under Stores > Stocks

But when I Go to product edit, and switch store to Oman website, user is able to see the Inventory source of other websites also

Our client wants that user should only be able to see the stock sources which are assigned to that website (Oman in this case if I select one of the Oman Stores in store switcher. But it is also showing UAE stock sources also)
I checked few 3rd party extensions but none of them provides such a feature. Any suggestion on how this can be achieved?


text:
Q: Go through with renaming "offensive" to "rude/abusive" About a year ago the offensive flag was subject to some renaming, which finally settled down on rude or abusive. This has the advantage of capturing non-offensive abuses of the site and thus clearly applies to some forms of trolling to which offensive did not clearly apply.
However, in several parts of the interface (probably everywhere except in the flag dialogue), these flags are still called offensive:

This leads to unnecessary confusion¹ and counteracts the new terminology being established. In particular some moderators almost only see those parts of the interface where offensive is still used and thus did not even notice the change.

¹ "Why did you flag that as offensive? It's not offensive." – "But it's abusive." – "Yes but the flag is called offensive." – "No, it isn't." – …

A: I've gone through the codebase and updated a bunch of places that had "offensive" to "rude or abusive" (or similar - I did what made sense according to context).
This has been deployed already.
Please let me know if you find any that I've missed.


text:
Q: Find an 8 digit stock number within a cell I am looking to create a formula that enables me to search a set of data for an 8 digit number. I have attached my testing sheet.
In column B is the stock numbers I need to find within a set of data.
In column E is the full list to be checked against, however, within any one cell, you can have several different 8 digit stock numbers.
In my test sheet, I have found that a vlookup only searches for the first stock number and not all the stock numbers within that cell. I have attempted an index match formula combined with a transpose split however none of these has enabled me to properly search my data set.
 =ARRAYFORMULA(VLOOKUP(B2:B,$E$2:$E,1,0))
then
 =INDEX($E$2:$E$1139,(MATCH(B2,TRANSPOSE(SPLIT($E$2:$E,";, ")))))
The data can be separated within the cell with either spaces or "," or ";"
You should be able to make a copy of my test sheet using this link:
https://docs.google.com/spreadsheets/d/1UckPZw6tWBw0H13p79N94IqV2EFyfhYNyEhmLecr3XM/copy#gid=55962883
Hope you can help.

A: try:
=FILTER(E:E, REGEXMATCH(E:E&"", TEXTJOIN("|", 1, B2:B)))

update:
to get true/false use:
=INDEX(REGEXMATCH(E2:E&"", TEXTJOIN("|", 1, B2:B)))

or if you want to return match or N/A use:
=INDEX(IF(REGEXMATCH(E2:E&"", TEXTJOIN("|", 1, B2:B)), E2:E, ISNA()))


text:
Q: Manually Enforce CRUD and FLS in trigger handler and Ajax to pass salesforce security review I want to pass salesforce security review in my app. I want to make sure that all the known issues fixed before submission. I have Enforced CRUD and FLS in to all the apex classes. But i am not sure about the following points:
1) Is it necessary to Enforce CRUD and FLS on VF page using the AJAX Toolkit:
sforce.connection.query("Select Id, Name From Account",callback);

2) Is it necessary to Enforce CRUD and FLS in trigger handler classes:
Trigger
trigger VAccountTrigger on Account(before update) {

    VAccountTriggerHandler vHandler = new VAccountTriggerHandler();

    if(Trigger.isUpdate && Trigger.isBefore){
        vHandler.beforeUpdate(Trigger.new);
    }
}

Class
public class VAccountTriggerHandler {

    public void beforeUpdate(List<Account> newList) {
    //--------------------------------------------------
    //----Do we need to Enforce CRUD and FLS here too---
    }
}

A: When rendering VisualForce pages, the platform will automatically enforce CRUD and FLS when the developer references SObjects and SObject fields directly in the VisualForce page. For example, if a user without FLS visibility to the Phone field of the Contact object was to view the below page, phone numbers would be automatically removed from the table.
<apex:page standardController="Account">
  <apex:pageBlock title="Contacts">
    <apex:dataTable value="{!account.Contacts}" var="contact" cellPadding="4" border="1">
      <apex:column>
        <apex:facet name="header">Name</apex:facet>
        {!contact.Name}
      </apex:column>
      <apex:column>
        <apex:facet name="header">Phone</apex:facet>
        {!contact.Phone}
      </apex:column>
    </apex:dataTable>
  </apex:pageBlock>
</apex:page>

When we refer fields indirectly then we need to check FLS by our self. For example using wrapper classes or in trigger helper classes.
public with sharing class RandomContactController {
    public String getGetRandomName() {
        // Check if the user has read access on the Contact.Name field
        if (!Schema.sObjectType.Contact.fields.Name.isAccessible()){
          return '';
        }

        Contact [] myList = [SELECT Name FROM Contact LIMIT 1000];
        // Pick a list entry at random
        Integer index = Math.mod(Math.abs(Crypto.getRandomInteger()),myList.size());
        Contact selected = myList.get(index);
        return selected.Name;
    }
}

For more details refer: https://developer.salesforce.com/page/Enforcing_CRUD_and_FLS

A: For your VAccountTriggerHandler class, yes, you'll need to enforce CRUD/FLS checks (as well as sanitation and other protective measures) manually for security review purposes.
Consider using WITH SECURITY_ENFORCED in your SOQL for a quick catch-all CRUD/FLS fix, or consider .stripInaccessible(), both of which are going GA soon.
See (and do) the Develop Secure Web Apps trail for all the different security measures to account for.


text:
Q: Lie Groups induce Lie Algebra homomorphisms I am having a difficult time showing that if $\phi: G \rightarrow H$ is a Lie group homomorphism, then $d\phi: \mathfrak{g} \rightarrow \mathfrak{h}$ satisfies the property that for any $X, Y \in \mathfrak{g},$ we have that $d\phi([X, Y]_\mathfrak{g}) = [d\phi(X), d\phi(Y)]_\mathfrak{h}$.
Any help is appreciated!!!!!!!!

A: Let $x \in G$. Since $\phi$ is a Lie group homomorphism, we have that
$$\phi(xyx^{-1}) = \phi(x) \phi(y) \phi(x)^{-1} \tag{$\ast$}$$
for all $y \in G$. Differentiating $(\ast)$ with respect to $y$ at $y = 1$ in the direction of $Y \in \mathfrak{g}$ gives us
$$d\phi(\mathrm{Ad}(x) Y) = \mathrm{Ad}(\phi(x)) d\phi(Y). \tag{$\ast\ast$}$$
Differentiating $(\ast\ast)$ with respect to $x$ at $x = 1$ in the direction of $X \in \mathfrak{g}$, we obtain
$$d\phi(\mathrm{ad}(X) Y) = \mathrm{ad}(d\phi(X)) d\phi(Y)$$
$$\implies d\phi([X, Y]_{\mathfrak{g}}) = [d\phi(X), d\phi(Y)]_{\mathfrak{h}}.$$


text:
Q: How to retrive differentiation results with Eigen::AutoDiffScalar I am learning to use this library.  Trying to differentitate a simple function, y = x^2, does not yield the expected results (dy/dx = 2x = 16 when x = 8).
#include <eigen3/Eigen/Core>
#include <eigen3/unsupported/Eigen/AutoDiff>
#include <iostream>

int main(int argc, char *argv[])
{
  Eigen::AutoDiffScalar<Eigen::Vector2d> x(8.0), y;

  y = x*x;

  std::cout << y.derivatives()[0];

  return 0;
}

A: The scalar you have declared is literally just that – a scalar, so you are finding the derivative of a scalar (8*8), which is 0.  To indicate that 8 is the value of the first variable, you need to set its first derivative to 1:
#include <eigen3/Eigen/Core>
#include <eigen3/unsupported/Eigen/AutoDiff>
#include <iostream>

int main(int argc, char *argv[])
{
  // Note different initialization
  Eigen::AutoDiffScalar<Eigen::Vector2d> x(8.0, Eigen::Vector2d(1,0)), y;

  y = x*x;

  std::cout << "x = " << x << "\n"
            << "y = " << y << "\n"
            << "y' = " << y.derivatives()[0] << "\n";

  return 0;
}

This outputs

x = 8
  y = 64
  y' = 16

I recommend naming the variable something other than x, because it can be easily confusing if you're expecting to take the derivative with respect to something that is usually called x as well.  So, let's call it a instead.

*

*If da/dx=0, then a is a constant.  Then, obviously, d/dx a² = 0 as well.

*if da/dx=1, then essentially a=x.  Then, d/dx a²  = d/dx x² = 2x.


text:
Q: Use CSS/Jquery calc function in React Js I have a situation where I need to give dynamic width to the div so I need to use this divStyle = {width: calc(100% - 276px)} in my React Js code. But doing so it gives an error that calc is not a function.
I know this can be achieved using Jquery but I dont want to introduce JQuery to my application. If there is any kind of workaround or hack that might solve this then please share.
code:
customFormat = 'hello-div'
divStyle = {width: calc(100% - 276px)}
return (

      Hello World

)

A: If you need some more specific CSS you need to put it into quotes - react inline styles doc

In your exact case
customFormat = 'hello-div'
divStyle = {width: 'calc(100% - 276px)'}
return (

      Hello World

)

In case you need to overwrite multiple widths (fallbacks) for browser compatibility
divStyle = {width: 'calc(100% - 276px)',
    fallbacks: [
        { width: '-moz-calc(100% - 276px)' },
        { width: '-webkit-calc(100% - 276px)' },
        { width: '-o-calc(100% - 276px)' }
]}


text:
Q: How to automatically update an entry daily in phpMyAdmin? I have a database called ARTICLES. Inside Articles, I have a table called Users. Inside Users, there is an entry called Renewal, which is an Integer.
Once Renewal is set, it should decrease by 1 every 24 hours. For example, let's say Renewal is 30. In 24 hours, Renewal should be 29. I do not wish to go inside the entry, and update this field every 24 hours. There will be hundreds of rows with different values for Renewal.
Is there a way to automatically update this entry every 24 hours, so that the entry decreases by 1?

A: You're taking the wrong approach. Instead of counting down in a complicated manner you can simply set an 'expire' date. 30 days from now? Then expire at 19 juli 2016 at 12:00. No need for automatic updates.

A: You can create scheduled events in MySQL - CREATE EVENT
I would check renewal values programatically in you PHP script based on your record timestamp instead of you approach.


text:
Q: How can I make a binary executable a command? I have a binary file as part of the software that I developed. How can I make it an actual command in the command line? For example, if my executable is called mysoftware, how can I let a user do mysoftware <arg1> <arg2> ... <argN> instead of ./mysoftware <arg1> <arg2> ... <argN> which is kind of clunky.

A: The executable will need to be in the user's PATH somewhere. /usr/bin and /bin are two common places, but there are others.
You can do $ echo $PATH to see what directories (for you) are in your PATH, then maybe add a command in your Makefile (common practice is make install) to have it copy the executable to that location.


text:
Q: Special characters (and MooTools) are ruining my life I'm working on localization for my toolkit.
My goal is that if you were a German web developer and you wanted to use a forEach loop, rather then type ['hey', 'there'].forEach(function () {}); they could type ['hey', 'there'].fürJeder(function () {});
I have all the words stored in an object at $.i18n.de.
In my JavaScript file I have
de: {
    extend: 'verlänger',
    forEach: 'fürJeder'
}

but when I go into the object to get the words they turn into verlänger and fürJeder.
I have no idea why.
Some details:

*

*I'm on a MacBook Pro running 10.6.7

*I'm using Kod as my editor.

*I'm using Google Chrome as my browser.

*I'm using Option + U + letter to type the ä and ü.

My question: How do I get the browser to handle these correctly?
I've tried using backslashes before them but it stays the same.
EDIT: Screw it. I just found out that the people who inspired me to do this did it as an April Fool's day joke. I really should've clicked on some of those links. It would've saved me 2 hours of trying to set up an API.

A: Turns out that this is a really bad idea to try and do.
Programming languages are almost exclusively written in English (JavaScript being one of those) which means that even if you write your program in a different language, keywords like return, var, function are still going to be in English and you're still going to have to use them which would get confusing when using functions, constants etc. that have non-English names.
The best solution is to just avoid using non-latin characters in variable names all together.
Even thought it works in most modern browsers, it makes your code harder to write and more confusing.
Leave the coding to the English speakers.

A: Although I don't get the point of that (especially for german people generally comfortable with english and sharing the same germanic linguistic origin), the simplest workaround to avoid encoding issues is to replace those special characters with their latin counterparts:
fürJeder -> fuerJeder
verlänger -> verlaenger
Uncommon spelling but still correct


text:
Q: WPF custom control and direct content support I am fairly new to WPF, and am a bit stuck, so any help would be appreciated.
I am trying to write WPF custom control that encapsulates several elements of functionality that I already having working (i.e sorting, filtering, standard menus, etc.), but in a nice neat package to avoid repetition.
Anyway I have created the custom control (based on control), and then have the following in the Generic.Xaml
<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:Controls.ListViewExtended">
    <Style TargetType="{x:Type local:ListViewExtended}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type local:ListViewExtended}">
                    <Border Background="{TemplateBinding Background}"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="{TemplateBinding BorderThickness}">
                        <ListView>
                            <ListView.View>
                                <GridView>
                                <!-- Content goes here -->
                                </GridView>
                            </ListView.View>
                        </ListView>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

When I try to add GridViewColumns (or any control really), as below ...
<elv:ListViewExtended>
   <GridView>
        <GridViewColumn Width="140" Header="Column 1" />
        <GridViewColumn Width="140" Header="Column 2" />
        <GridViewColumn Width="140" Header="Column 3" />
   </GridView>
</elv:ListViewExtended>

I get the "... does not support direct content" error.
I have created a dependancy property (again below) that allows the adding of GridView, but it still doesn't work.
public static DependencyProperty GridViewProperty;

public static string GridViewHeader(DependencyObject target)
{
    return (string)target.GetValue(GridViewProperty);
}
public static void GridViewHeader(DependencyObject target, string value)
{
    target.SetValue(GridViewProperty, value);
}

Thanks in advance

A: I use this simple solution in our projects to support direct content in custom controls:
Add a "CustomControl" to your project and derive this control from class "UserControl" instead of "Control":
public class MyCustomControl: UserControl
{
    static MyCustomControl()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(MyCustomControl),
            new FrameworkPropertyMetadata(typeof(MyCustomControl)));
    }
}

When you add a CustomControl to your project, Visual Studio (I am using 2012) automatically adds a folder "Themes" including a file named "Generic.xaml".
This file holds a ResourceDictionary to define the style (template) of your CustomControl.
You will find a basic template for your CustomControl, already used as DefaultStyle. For direct content support place a ContentPresenter somewhere inside this template with parent content binding:
<Style TargetType="{x:Type local:MyCustomControl}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:MyCustomControl}">
                <Border Background="{TemplateBinding Background}"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}">
                    <ContentPresenter Content="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Content}" />
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Now it's possible to add content to your CustomControl:
<Window x:Class="MyApplication.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:controls="clr-namespace:MyApplication"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <controls:MyCustomControl>
                <TextBlock>Hello</TextBlock>
        </controls:MyCustomControl>
    </Grid>
</Window>

Hope this helps!

A: Inherit your custom control from the ListView, not from the Control. This would definitely cause you to change the template, but I encourage you to read more documentation on how to do it (e.g. Sacha Barber's article: Creating and consuming a custom WPF control).
Good luck in your learning!

A: All You need is to specify ContentPropertyAttribute.
[ContentProperty("MainContent")]
public class GroupPanel : Control
{
    public GroupPanel()
    {
        DefaultStyleKey = typeof(GroupPanel);
    }

    public object MainContent
    {
        get { return GetValue(MainContentProperty); }
        set { SetValue(MainContentProperty, value); }
    }

    public static readonly DependencyProperty MainContentProperty =
        DependencyProperty.Register("MainContent", typeof(object), typeof(GroupPanel), null);
}

Reference: http://msdn.microsoft.com/en-us/library/system.windows.markup.contentpropertyattribute(v=vs.90).aspx

A: Don't use
{Binding MainContent ElementName=Self}

Use
Content="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=MainContent}" />

Could have saved me so much time with that.


text:
Q: Probability of winning after n games Say you and your friend play a coin toss game where the coin is fair and there is 1/2 chance of winning for each player. What your probability of winning the next game if you have won 5 games and your friend has won 7? What if you have won just 2 games and they have won 9? Note that the first person to win 10 games wins the set.
Please explain in simple terms (like to a five year-old) or to someone with a limited math background how you got your answer.

A: It's always $\frac{1}{2}$- winning a game is independent of winning a previous one.


text:
Q: Can I take a picture using the front camera on Samsung Galaxy Tab (Android 2.2) ? Can I take a picture from the front camera?
My application has an input form for inventory.
If an user sends a data,
the user's face pic is also sent to the server for authorization / validation.
I will put the app on Samsung Galaxy Tab (Android 2.2).
Is there any way to take a picture from the front camera?

A: For 2.2
    Camera cam = Camera.open();
    cam.setDisplayOrientation(90);
    cam.setPreviewDisplay(holder);

    Camera.Parameters para = cam.getParameters();
    para.set("camera-id", 2);
    cam.setParameters(p);

A: To solve the error:

"The method open() is undefined for the type Camera"

import android.hardware.Camera

This is instead of
import android.graphics.Camera

Both are given as options from eclipse only hardware one has open.


text:
Q: Filtering string with Replace & Substring in C# Optimisation I have created a function to 'filter' a string by removing various characters using the .Replace method, I am also removing anything at the end of the string that starts with '(' using the Substring method.
This all works fine, however I am wondering if there is a optimised better way of doing this as efficiency is important for me.
public static string filterHorseName(string horseName)
{
    horseName = horseName
      .Replace(" ", "")
      .Replace("`", "")
      .Replace("-", "")
      .Replace("'", "")
      .Replace("´", "")
      .Replace("'", "")
      .ToLower();

    int index = horseName.IndexOf("(");

    if (index > 0)
    {
        horseName = horseName.Substring(0, index);
    }

    return horseName;
}

Thank you.

A: I suggest building the final string with a help of StringBuilder:
    private static HashSet<char> charsToRemove = new HashSet<char>() {
      ' ', '`', '-', '\'', '´', '''
    };

    public static string filterHorseName(string horseName) {
      if (string.IsNullOrEmpty(horseName))
        return horseName;

      StringBuilder sb = new StringBuilder(horseName.Length);

      foreach (char c in horseName) {
        if (charsToRemove.Contains(c))
          continue;
        else if (c == '(')
          break;

        sb.Append(char.ToLower(c));
      }

      return sb.ToString();
    }


text:
Q: Prove a sum involving multinomial coefficients I need to prove that if n and m are positive integers, then
$$ \sum_{k_1+...+k_m}\binom{n}{k_1, ..., k_m}(-1)^{k_2+k_4+...+k_{2l}}$$
is equal to 0 if m =2l, and is equal to 1 if m = 2l + 1.

A: If $m$ is even, consider $$(\underbrace{1-1+1-1+\cdots+1-1}_{m/2 \,\,\,1's \text{ and } m/2 \,\,\, -1's})^n$$
If $m$ is odd, consider $$(\underbrace{1-1+1-1+\cdots+1-1+1}_{(m+1)/2 \,\,\,1's \text{ and } (m-1)/2 \,\,\, -1's})^n$$Look at the multinomial expansion and conclude the answer.


text:
Q: Java: String to BigInteger to Binary I have a problem where I want to turn my input string into a BigInteger, and the output should be a Binary String. I used this code, but all it can read is "0" and "1".
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
BigInteger big = new BigInteger(input, 2);
String binarystring = big.toString(2);
System.out.println(binarystring);

When I change it to: BigInteger big = new BigInteger(input, 16);
I can write in a hexadecimal number but with no space.
What I want is that I can write any string, and the program should give me its binary value in a string.

A: A string like "hey world" won't have any meaningful numeric representation in base 10, so I suggest to output an appropriate message instead.
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
try {
    BigInteger big = new BigInteger(input); // default constructor is base 10
    System.out.println(big.toString(2));
}
catch (NumberFormatException){
    System.out.println("Input was not a decimal number");
}


text:
Q: Java while loop doesn't want stop I'm learning Java programming and have a problem with this code. My issue is I can't stop the second while loop (while (done ==1){ .. })
If I do done = 2, the program resume...
int stopme3 = 1;
while (stopme3 == 1) {
    /* Appel de la méthode Afficher les propriétaires */
    AfficherProprio();
    int choix_proprio = ChoisirProprio();

    /* Appel de la méthode Afficher les Comptes du Propriétaire */
    AfficherComptesProprietaire(choix_proprio);

    /* Choix du compte à modifier */
    System.out.println("N° de compte:");
    int choixCompte = lectureClavier.nextInt();
    /* Test si comptes existants du proprio */
    if (choixCompte == tab_compte[choix_proprio]._num_compte) {
        int done = 1;
        while (done == 1) {
            /* Création d'une ligne comptable */
            tab_compte[choix_proprio].CreerLigneC();
            System.out.println("Ajouter une ligne comptable supplémentaire ?");
            System.out.println("1 - Oui");
            System.out.println("2 - Non");
            done = lectureClavier.nextInt();
        }
    } else {
        System.out.println("Compte sélectionné inexistant.");
    }
}

Help is much appreciated, thanks a lot.

A: int stopme3 = 1;
            while (stopme3 == 1) { // This loop will keep running till condition is true

int done = 1;
    while (done == 1) {// This loop will keep running till condition is true

Hence this will run infinitely. Hence you might want to do this way
  int stopme3 = 1;
  while (stopme3 == 1) {

   if(some condition is met){
           stopme3  =2;
       }

}


text:
Q: scikit-learn AgglomerativeClustering and connectivity I am trying to use AgglomerativeClustering from scikit-learn to cluster points on a place. Points are defined by coordinates (X,Y) stored in _XY.
Cluster are limited to a few neighbours through the connectivity matrix defined by
C = kneighbors_graph(_XY, n_neighbors = 20).
I want some points not be part of the same cluster, even if they are neighbours, so I modified the connectivity matrix to put 0 between these points.
The algorithm runs smoothly but, at the end, some clusters contain points that should not be together, i.e. some couple for which I imposed _C = 0.
From the children, I can see that the problem arises when a cluster of two points (i, j) is already formed and that k joins (i,j) even if _C[i,k]=0.
So I was wondering how the connectivity constraint is propagated when the size of some clusters is larger than 2, _C being not defined in that case.
Thanks !

A: So what seems to be happening in your case is that despite your active disconnection of point you do not want to have in one cluster, these points are still part of the same connected component and the data associated to them still imply that they should be connected to the same cluster from a certain level up.
In general, AgglomerativeClustering works as follows: At the beginning, all data points are separate clusters. Then, at each iteration, two adjacent clusters are merged, such that the overall increase in discrepancy with the original data is minimal if we compare the original data with cluster means in L2 distance.
Hence, although you sever the direct link between two nodes, they can be clustered together one level higher by an intermediate node.


text:
Q: Best way to display Content and then return to calling Activity I want to grab the Name and PhoneNumber vals from the Contacts Content Provider and display them to the user so that s/he can select 1..N of those Contacts. I would like this "Activity" to pop up out of the Activity which invokes it.
Is an AlertDialog the best way to tackle this? Alternatively, I could make it a separate
Activity that returns to the Activity that invoked it once the user has finished making
the selections...

A: Both of the methods you've proposed would work. Which is best depends on many other things about your application.


text:
Q: Flutter in app purchase check purchase sucessfully donr or not I am trying to implement in-app purchase in my flutter app all is working fine just one thing I am stuck is when user payment is done (success or error) it will just print so ill proceed with my next steps to save data on the server but i can't find where I can get paid is successfully done or not. I just copy-paste code from the plugin and it's 99% the same but I am stuck on which line or function it's showing the successful hint.
Code
const List<String> _kProductIds = <String>[
  'subscription_gold',
];

class paymentScreen extends StatefulWidget {
  @override
  _paymentScreenState createState() => _paymentScreenState();
}

class _paymentScreenState extends State<paymentScreen> {
  final _formKey = GlobalKey<FormState>();
  final TextEditingController userLink = new TextEditingController();
  String accestoken = accessTokenGlobal;

  final InAppPurchase _inAppPurchase = InAppPurchase.instance;
  late StreamSubscription<List<PurchaseDetails>> _subscription;
  List<String> _notFoundIds = [];
  List<ProductDetails> _products = [];
  List<PurchaseDetails> _purchases = [];
  List<String> _consumables = [];
  bool _isAvailable = false;
  bool _purchasePending = false;
  bool _loading = true;
  String? _queryProductError;

  @override
  void initState() {
    final Stream<List<PurchaseDetails>> purchaseUpdated =
        _inAppPurchase.purchaseStream;
    _subscription = purchaseUpdated.listen((purchaseDetailsList) {
      _listenToPurchaseUpdated(purchaseDetailsList);
    }, onDone: () {
      _subscription.cancel();
    }, onError: (error) {
      // handle error here.
    });
    initStoreInfo();
    super.initState();
  }

  Future<void> initStoreInfo() async {
    final bool isAvailable = await _inAppPurchase.isAvailable();
    if (!isAvailable) {
      setState(() {
        _isAvailable = isAvailable;
        _products = [];
        _purchases = [];
        _notFoundIds = [];
        _consumables = [];
        _purchasePending = false;
        _loading = false;
      });
      return;
    }

    if (Platform.isIOS) {
      var iosPlatformAddition = _inAppPurchase
          .getPlatformAddition<InAppPurchaseIosPlatformAddition>();
      await iosPlatformAddition.setDelegate(ExamplePaymentQueueDelegate());
    }

    ProductDetailsResponse productDetailResponse =
        await _inAppPurchase.queryProductDetails(_kProductIds.toSet());
    if (productDetailResponse.error != null) {
      setState(() {
        _queryProductError = productDetailResponse.error!.message;
        _isAvailable = isAvailable;
        _products = productDetailResponse.productDetails;
        _purchases = [];
        _notFoundIds = productDetailResponse.notFoundIDs;
        _consumables = [];
        _purchasePending = false;
        _loading = false;
      });
      return;
    }

    if (productDetailResponse.productDetails.isEmpty) {
      setState(() {
        _queryProductError = null;
        _isAvailable = isAvailable;
        _products = productDetailResponse.productDetails;
        _purchases = [];
        _notFoundIds = productDetailResponse.notFoundIDs;
        _consumables = [];
        _purchasePending = false;
        _loading = false;
      });
      return;
    }

    List<String> consumables = await ConsumableStore.load();
    setState(() {
      _isAvailable = isAvailable;
      _products = productDetailResponse.productDetails;
      _notFoundIds = productDetailResponse.notFoundIDs;
      _consumables = consumables;
      _purchasePending = false;
      _loading = false;
    });
  }

  @override
  void dispose() {
    if (Platform.isIOS) {
      var iosPlatformAddition = _inAppPurchase
          .getPlatformAddition<InAppPurchaseIosPlatformAddition>();
      iosPlatformAddition.setDelegate(null);
    }
    _subscription.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    double Width = MediaQuery.of(context).size.width;
    double Height = MediaQuery.of(context).size.height;
    double Status = MediaQuery.of(context).padding.top;

    return Scaffold(
      bottomNavigationBar: Padding(
        padding: const EdgeInsets.all(8.0),
        child: GestureDetector(
          onTap: () {
            print(_products);

            showModalBottomSheet(
                context: context,
                builder: (context) {
                  return StatefulBuilder(builder: (BuildContext context,
                      StateSetter setState /*You can rename this!*/) {
                    return Container(
                        height: 200,
                        child: ListView(
                          children: [
                            _buildProductList(),
                          ],
                        ));
                  });
                });
          },
          child: Container(
            width: Width * 0.9,
            height: Height * 0.06,
            decoration: BoxDecoration(
                color: kPrimaryColor, borderRadius: BorderRadius.circular(5)),
            child: Center(
              child: Text(
                'Subscribe Now',
                style: TextStyle(
                    color: Colors.white, fontSize: 16, fontFamily: 'SegoeUI'),
              ),
            ),
          ),
        ),
      ),
    );
  }

  Card _buildProductList() {
    if (_loading) {
      return Card(
          child: (ListTile(
              leading: CircularProgressIndicator(),
              title: Text('Fetching products...'))));
    }
    if (!_isAvailable) {
      return Card();
    }
    final ListTile productHeader = ListTile(title: Text('Subscriptions'));
    List<ListTile> productList = <ListTile>[];
    if (_notFoundIds.isNotEmpty) {
      productList.add(ListTile(
          title: Text('[${_notFoundIds.join(", ")}] not found',
              style: TextStyle(color: ThemeData.light().errorColor)),
          subtitle: Text(
              'This app needs special configuration to run. Please see example/README.md for instructions.')));
    }

    // This loading previous purchases code is just a demo. Please do not use this as it is.
    // In your app you should always verify the purchase data using the `verificationData` inside the [PurchaseDetails] object before trusting it.
    // We recommend that you use your own server to verify the purchase data.
    Map<String, PurchaseDetails> purchases =
        Map.fromEntries(_purchases.map((PurchaseDetails purchase) {
      if (purchase.pendingCompletePurchase) {
        _inAppPurchase.completePurchase(purchase);
      }
      return MapEntry<String, PurchaseDetails>(purchase.productID, purchase);
    }));
    productList.addAll(_products.map(
      (ProductDetails productDetails) {
        PurchaseDetails? previousPurchase = purchases[productDetails.id];
        var date = DateTime.now().toString();

        var dateParse = DateTime.parse(date);

        var formattedDate =
            "${dateParse.day}-${dateParse.month}-${dateParse.year + 1}";

        return ListTile(
            title: Text(
              'Yearly',
            ),
            subtitle: Text(
              'Your subscription will expire on ${formattedDate}',
            ),
            trailing: previousPurchase != null
                ? IconButton(
                    onPressed: () => confirmPriceChange(context),
                    icon: Icon(Icons.upgrade))
                : TextButton(
                    child: Text(productDetails.price),
                    style: TextButton.styleFrom(
                      backgroundColor: kPrimaryColor,
                      primary: Colors.white,
                    ),
                    onPressed: () {
                      late PurchaseParam purchaseParam;

                      if (Platform.isAndroid) {
                        // NOTE: If you are making a subscription purchase/upgrade/downgrade, we recommend you to
                        // verify the latest status of you your subscription by using server side receipt validation
                        // and update the UI accordingly. The subscription purchase status shown
                        // inside the app may not be accurate.
                        final oldSubscription =
                            _getOldSubscription(productDetails, purchases);

                        purchaseParam = GooglePlayPurchaseParam(
                            productDetails: productDetails,
                            applicationUserName: null,
                            changeSubscriptionParam: (oldSubscription != null)
                                ? ChangeSubscriptionParam(
                                    oldPurchaseDetails: oldSubscription,
                                    prorationMode: ProrationMode
                                        .immediateWithTimeProration,
                                  )
                                : null);
                      } else {
                        purchaseParam = PurchaseParam(
                          productDetails: productDetails,
                          applicationUserName: null,
                        );
                      }

                      if (productDetails.id == _kConsumableId) {
                        _inAppPurchase.buyConsumable(
                            purchaseParam: purchaseParam,
                            autoConsume: _kAutoConsume || Platform.isIOS);
                      } else {
                        _inAppPurchase.buyNonConsumable(
                            purchaseParam: purchaseParam);
                      }
                    },
                  ));
      },
    ));

    return Card(
        child: Column(
            children: <Widget>[
                  Container(
                    color: Color(0xfff5f6fb),
                    child: Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Center(
                          child: Text(
                        'You can cancel subscription from playstore.',
                        style: TextStyle(
                            fontFamily: 'PoppinsRegular',
                            fontSize: 15,
                            color: Color(0xff8f9ba8)),
                      )),
                    ),
                  ),
                  SizedBox(
                    height: MediaQuery.of(context).size.height * 0.01,
                  ),
                ] +
                productList));
  }

  void showPendingUI() {
    setState(() {
      _purchasePending = true;
    });
  }

  void deliverProduct(PurchaseDetails purchaseDetails) async {
    // IMPORTANT!! Always verify purchase details before delivering the product.
    if (purchaseDetails.productID == _kConsumableId) {
      await ConsumableStore.save(purchaseDetails.purchaseID!);
      List<String> consumables = await ConsumableStore.load();
      setState(() {
        _purchasePending = false;
        _consumables = consumables;
      });
    } else {
      setState(() {
        _purchases.add(purchaseDetails);
        _purchasePending = false;
      });
    }
  }

  void handleError(IAPError error) {
    setState(() {
      _purchasePending = false;
    });
  }

  Future<bool> _verifyPurchase(PurchaseDetails purchaseDetails) {
    // IMPORTANT!! Always verify a purchase before delivering the product.
    // For the purpose of an example, we directly return true.
    return Future<bool>.value(true);
  }

  void _handleInvalidPurchase(PurchaseDetails purchaseDetails) {
    // handle invalid purchase here if  _verifyPurchase` failed.
  }

  void _listenToPurchaseUpdated(List<PurchaseDetails> purchaseDetailsList) {
    purchaseDetailsList.forEach((PurchaseDetails purchaseDetails) async {
      if (purchaseDetails.status == PurchaseStatus.pending) {
        showPendingUI();
      } else {
        if (purchaseDetails.status == PurchaseStatus.error) {
          handleError(purchaseDetails.error!);
        } else if (purchaseDetails.status == PurchaseStatus.purchased ||
            purchaseDetails.status == PurchaseStatus.restored) {
          bool valid = await _verifyPurchase(purchaseDetails);
          if (valid) {
            deliverProduct(purchaseDetails);
          } else {
            _handleInvalidPurchase(purchaseDetails);
            return;
          }
        }
        if (Platform.isAndroid) {
          if (!_kAutoConsume && purchaseDetails.productID == _kConsumableId) {
            final InAppPurchaseAndroidPlatformAddition androidAddition =
                _inAppPurchase.getPlatformAddition<
                    InAppPurchaseAndroidPlatformAddition>();
            await androidAddition.consumePurchase(purchaseDetails);
          }
        }
        if (purchaseDetails.pendingCompletePurchase) {
          await _inAppPurchase.completePurchase(purchaseDetails);
        }
      }
    });
  }

  Future<void> confirmPriceChange(BuildContext context) async {
    if (Platform.isAndroid) {
      final InAppPurchaseAndroidPlatformAddition androidAddition =
          _inAppPurchase
              .getPlatformAddition<InAppPurchaseAndroidPlatformAddition>();
      var priceChangeConfirmationResult =
          await androidAddition.launchPriceChangeConfirmationFlow(
        sku: 'purchaseId',
      );
      if (priceChangeConfirmationResult.responseCode == BillingResponse.ok) {
        ScaffoldMessenger.of(context).showSnackBar(SnackBar(
          content: Text('Price change accepted'),
        ));
      } else {
        ScaffoldMessenger.of(context).showSnackBar(SnackBar(
          content: Text(
            priceChangeConfirmationResult.debugMessage ??
                "Price change failed with code ${priceChangeConfirmationResult.responseCode}",
          ),
        ));
      }
    }
    if (Platform.isIOS) {
      var iapIosPlatformAddition = _inAppPurchase
          .getPlatformAddition<InAppPurchaseIosPlatformAddition>();
      await iapIosPlatformAddition.showPriceConsentIfNeeded();
    }
  }

  GooglePlayPurchaseDetails? _getOldSubscription(
      ProductDetails productDetails, Map<String, PurchaseDetails> purchases) {
    GooglePlayPurchaseDetails? oldSubscription;
    if (productDetails.id == _kSilverSubscriptionId &&
        purchases[_kGoldSubscriptionId] != null) {
      oldSubscription =
          purchases[_kGoldSubscriptionId] as GooglePlayPurchaseDetails;
    } else if (productDetails.id == _kGoldSubscriptionId &&
        purchases[_kSilverSubscriptionId] != null) {
      oldSubscription =
          purchases[_kSilverSubscriptionId] as GooglePlayPurchaseDetails;
    }
    return oldSubscription;
  }
}

/// Example implementation of the
/// [`SKPaymentQueueDelegate`](https://developer.apple.com/documentation/storekit/skpaymentqueuedelegate?language=objc).
///
/// The payment queue delegate can be implementated to provide information
/// needed to complete transactions.
class ExamplePaymentQueueDelegate implements SKPaymentQueueDelegateWrapper {
  @override
  bool shouldContinueTransaction(
      SKPaymentTransactionWrapper transaction, SKStorefrontWrapper storefront) {
    return true;
  }

  @override
  bool shouldShowPriceConsent() {
    return false;
  }
}

class ConsumableStore {
  static const String _kPrefKey = 'consumables';
  static Future<void> _writes = Future.value();

  /// Adds a consumable with ID `id` to the store.
  ///
  /// The consumable is only added after the returned Future is complete.
  static Future<void> save(String id) {
    _writes = _writes.then((void _) => _doSave(id));
    return _writes;
  }

  /// Consumes a consumable with ID `id` from the store.
  ///
  /// The consumable was only consumed after the returned Future is complete.
  static Future<void> consume(String id) {
    _writes = _writes.then((void _) => _doConsume(id));
    return _writes;
  }

  /// Returns the list of consumables from the store.
  static Future<List<String>> load() async {
    return (await SharedPreferences.getInstance()).getStringList(_kPrefKey) ??
        [];
  }

  static Future<void> _doSave(String id) async {
    List<String> cached = await load();
    SharedPreferences prefs = await SharedPreferences.getInstance();
    cached.add(id);
    await prefs.setStringList(_kPrefKey, cached);
  }

  static Future<void> _doConsume(String id) async {
    List<String> cached = await load();
    SharedPreferences prefs = await SharedPreferences.getInstance();
    cached.remove(id);
    await prefs.setStringList(_kPrefKey, cached);
  }
}

A: In your _listenToPurchaseUpdated function you can check if the item has been purchased or not through this:
if (purchaseDetails.status == PurchaseStatus.purchased) { // your code goes here .. }

I suggest to create one singleton class to handle IAP, that will give you more reliability and code reusability


text:
Q: Avoid command events blocking a kill focus event in wxPython I'm writing a class to generate a frame on left click of a taskbar icon. The desired behaviour is for this frame to disappear on loss of focus, so I have bound a wx.EVT_KILL_FOCUS event to the panel in my LeftClickFrame() object.
This works fine if I only have a wx.StaticText widget in the frame, but if I add a wx.HyperlinkCtrl the wx.EVT_KILL_FOCUS event no longer fires. I get the same blocking behaviour with wx.RadioButton widgets, but not with wx.StaticBitmap.
I believe this is something to do with the fact that wx.HyperlinkCtrl and wx.RadioButton widgets are both controls and emit command events, but I'm not clear on what I have to do to rearrange my class so the wx.EVT_KILL_FOCUS event is still processed when one or both of these controls are present.
I have the following code:
class LeftClickFrame(wx.Frame):

    def __init__(self, frame):
        super(LeftClickFrame, self).__init__(frame,
                                             style=wx.FRAME_NO_TASKBAR|
                                                   wx.CAPTION)
        self.tbicon = frame.taskbar_icon
        self.tbicon.options_window = self
        self.InitUI()

    def InitUI(self):
        self.panel = wx.Panel(self, wx.ID_ANY)
        self.panel.Bind(wx.EVT_KILL_FOCUS, self.Close)

        self.main_vbox = wx.BoxSizer(wx.VERTICAL)
        statuses_hbox = self.GetStatusesVBox()
        self.main_vbox.Add(statuses_hbox)
        self.main_vbox.Add((-1, 10))
        links_vbox = self.GetLinksVBox()
        self.main_vbox.Add(links_vbox, flag=wx.TOP|wx.CENTER, border=20)
        self.panel.SetSizer(self.main_vbox)

    def GetStatusesVBox(self, statuses):
        statuses_vbox = wx.BoxSizer(wx.VERTICAL)
        for status in statuses:
            battery_statuses_txt = wx.StaticText(self.panel,
                                                 wx.ID_ANY, status)
            statuses_vbox.Add(battery_statuses_txt,
                              flag=wx.TOP|wx.LEFT, border=10)
        return statuses_vbox

    def GetLinksVBox(self):
        links_vbox = wx.BoxSizer(wx.VERTICAL)
        link1 = wx.HyperlinkCtrl(self.panel, wx.ID_ANY, 'Adjust screen brightness')
        link1.Bind(wx.EVT_HYPERLINK, self.tbicon.LaunchPowerOptions)
        links_vbox.Add(link1, flag=wx.CENTER|wx.TOP, border=5)
        return links_vbox

    def Close(self):
        self.tbicon.options_window.Destroy()
        self.Destroy()

A: You can try EVT_ACTIVATE instead of EVT_KILL_FOCUS since it does not work in your case.
And you can use event.GetActive() to check if this frame is in focus.
def InitUI(self):
    self.panel = wx.Panel(self, wx.ID_ANY)
    self.Bind(wx.EVT_ACTIVATE, self.Close)  #bind it to Frame

def Close(self, evt):
    if evt.GetActive() != True:
        #do window close


text:
Q: Cannot refresh content in browser using http-server with Aurelia I'm using Aurelia with http-server, as it is described in Aurelia getting started docs. I'm unable to see changes, because any browser seems to cache entire page at first load. When I use F5, ctrl+F5 or ctrl+r, page refreshes but nothing changes, none of my modifications are visible. Then I can use another browser and at first visit changes are visible, but any subsequent visit shows always the first one. It occurs in every browser I use (Chrome and Firefox, ever in private mode). I'm certain that it is not bug in Aurelia itself.
I tried to change port and use http-server with -c parameter. Nothing changed. Any ideas?

A: If you want to force your Aurelia app to be constantly refreshed after you modify it, you can have a look at the following thread:
https://github.com/aurelia/framework/issues/94
Aaike commented on 8 May 2015:

change your index.html to add the extension right before you import
  the aurelia-bootstrapper

<script>
      var systemLocate = System.locate;
      System.locate = function(load) {
        var System = this;
        return Promise.resolve(systemLocate.call(this, load)).then(function(address) {
          if(address.lastIndexOf("html.js") > -1) return address;
          if(address.lastIndexOf("css.js") > -1) return address;
          return address + System.cacheBust;
        });
      };
      System.cacheBust = '?bust=' + Date.now();

      System.import('aurelia-bootstrapper');
</script>

A: This is a caching issue that pops up sometimes with http-server.  I don't know exactly what causes it but I believe the -c modifier changes the length of cache-control so I would set that as 0 or 1 instead of assigning a port that way.


text:
Q: Do "service ntpd restart" and "ntpdate " do the same work? I often get large offsets when checking ntpd using ntpq -p, I generally restart the ntp daemon and it fixes the issue. I wanted to know if i can try the ntpdate <ntp-server-name> instead of restarting ntpd. Since this is a production box wanted to be sure before implementing it.

A: ntpdate and ntpd are different tools, but one of them helps another.
ntpdate is used to synchronize the system clock at once immediately. It takes time from a ntpd server, which has synchronized status (stratum 1 - 4).
ntpd service sets system clock softly. It can spend several hours to eliminate the lag of system clock for several minutes. All this time it has synchronized status stratum 16 - it means the system clock isn't synchronized. The service restart command service ntpd restart is used only to apply changes in its configuration file.
ntpdate is usually used to synchronize the system clock of personal computer at startup. ntpd service is usually used to synchronize the system clock of  server all-time.

A: No. Citing man ntpdate:

ntpdate  will  decline  to set the date if an NTP server daemon (e.g., ntpd) is running on the same host. When
         running ntpdate on a regular basis from cron as an alternative to running a daemon, doing so once  every  hour
         or two will result in precise enough timekeeping to avoid stepping the clock.

A: On various commonly-used Linux distributions (including CentOS, Debian, and Ubuntu), ntpd is started with the -g flag by default, which means it will perform a large clock step on the first adjustment if needed.  So for the majority of cases, ntpdate shouldn't be needed, and restarting ntpd would be preferred.
But, as Sven commented, if ntpd has been running for a while and you still end up with a large offset, then something's wrong with your NTP setup or your network (or both).
So rather than restarting ntpd or running ntpdate, try diagnosing why you end up in this situation in the first place.
Some common issues:

*

*Not including enough peers - you should have at least 4.  Read through the whole BCP draft if you have the time.

*Using the server with the public NTP pool instead of the newer pool directive - you should use the latter if your ntpd supports it.

*Using peers which are too far away or poorly connected - try to select close-by, reliable peers.  Even better, augment your external peers with a local reference clock for your network.  (A BeagleBone, Raspberry Pi, or LeoNTP with a GPS receiver might be a good choice, depending on your environment.)

*There might be other reasons why your server is struggling to keep good time, such as a kernel bug or poor hardware clock.  Enabling loopstats, peerstats, and sysstats in your ntp.conf should help to track this down.

Post your configuration and the output from ntpq -np and hopefully we should be able to help you work this out.


text:
Q: Error - Using "requireCordovaModule" to load non-cordova module "path" is not supported I am getting below error after upgrading cordova 8.0.0 to 9.0.0 in my ionic 3 application
Using "requireCordovaModule" to load non-cordova module "path" is not supported. Instead, add this module to your dependencies and use regular "require" to load it.

I wanted to install cordova-plugin-firebase-analytics plugin which requires cordova version 9.0.0
I tried npm cache clear --force command and building it again but it didn't work.
I also updated all the plugins to the latest version, removed the platform and added it again, still getting the same error.
I read all the related posts and tried them but the solutions given there are not working in my case.
Kindly help me with this error.


text:
Q: Exceptions from Service to webcontroller layer in Spring application I am building a web application (which has both webcontrollers which move to another page, as well as restcontrollers, which give a REST-ful result), and something isn't very clear to me, based on the documentation.
What is the recommended strategy regarding throwing exceptions from the service layer (or just your business logic implemented in @Service's or @Component's) when they're being called from an @Controller? Do the @Controllers have a try- catch logic for all possible exceptions that the Service might throw? What about unchecked exceptions?

A: There would be multiple options. This blog post at spring.io seems to have explained it very well.


text:
Q: Repository signature for asp.net core 2.1 controller action return types I'm trying to modify my Asp.net Core 2.1 project to use the new controller action return types (https://learn.microsoft.com/en-us/aspnet/core/web-api/action-return-types?view=aspnetcore-2.1#actionresultt-type)
The controller example they give is:
[HttpGet("{id}")]
[ProducesResponseType(200)]
[ProducesResponseType(404)]
public ActionResult<Product> GetById(int id)
{
    if (!_repository.TryGetProduct(id, out var product))
    {
        return NotFound();
    }

    return product;
}

However what does the repository signature for this method look like?
if I try:
public async Task<Product> TryGetProduct(int id)

then I get an error that there is no repository method that takes 2 arguments.
But if I try:
public async Task<Product> TryGetProduct(int id, out var product)

then I get:
Async methods cannot have ref or out parameters

A: The signature would be
public interface IRepository
{
    bool TryGetProduct(int id, out Product product);
}

And in the implementation, If your database has a record for the Id value, you will set that to the Product object and return true, else false.
Something like this (not tested)
public class Repository: IRepository
{
    YourDbContext yourDbContext;
    // to do : Initialize yourDbContext via constructor injection

    public bool TryGetProduct(int id, out Product product)
    {
        var p = yourDbContext.Products.FirstOrDefault(a => a.Id == id);
        if (p != null)
        {
            product = p;
            return true;
        }
        product = null;
        return false;
    }
}

A: To keep the async task functionality you can do this.
public interface IRepository
{
    Task<bool> TryGetProduct(int id, out Product product);
}

public class Repository : IRepository
{
    public Task<bool> TryGetProduct(int id, out Product product)
    {
        product = _db.Products.SingleOrDefault(x => x.Id == id);

        return Task.FromResult(product != null);
    }
}

Then in the controller.
[HttpGet("{id}")]
[ProducesResponseType(200)]
[ProducesResponseType(404)]
public async Task<ActionResult<Product>> GetById(int id)
{
    // await
    if (!await _repository.TryGetProduct(id, out var product))
    {
        return NotFound();
    }

    return Ok(product);
}


text:
Q: The Blackguards' powers in Wolverine: Weapon X? In Wolverine: Weapon X, Wolverine encounters a set of humans "improved" by nanites that given them a lot of the powers that Wolverine himself has, including improved healing and claws.  I ended up with two questions about their powers:

*

*All their eyes glow green, and I was wondering whether this was a power of some kind.

*Their claws also glow green, but that's stated that they are "lasers".  Why do their claws terminate if they are lasers?

Their laser claws are mentioned and green eyes shown in the below panels (apologies for the low resolution):

Their claws are shown on this cover:

A: The Blackguard or Strikeforce X are an attempt to create human soldiers with the physical capabilities of Wolverine, using technology to replicate to varying degrees Wolverine's physical capabilities. They have adamantium-laced skeletons from the Weapon X project and they appear to have substituted enhanced sight instead of olifactory senses. They also appear to have skimped on the adamantium-claw upgrade, substituting a metallic/laser-enhanced hybrid. (As you suggested, lasers don't terminate.)
The Blackguard are non-mutant humans who have been technologically enhanced using drugs, techno-organic nanites (for an enhanced healing factor to counter the adamantium-process used to give them damage-resistance) and other bionic implants (energy claws and possibly eyes).
Likely it was easier to give them enhanced visual capacity than olifactory senses. So I suspect they have the same capacity as cats for absorbing and capturing more light from their surroundings. These would be the equivalent of starlight lenses, something these soldiers would be familiar with, requiring less training.
As far as their claws, they are not lasers but a high grade metal enhanced with some sort of laser system to improve their cutting and damage dealing capacity. The glowing eyes and claws are also likely invoking the TVtropes concept The Rule of Cool. Fans were quite taken with the glowing claws. Though I question why they didn't just get the full adamantium upgrade? Cost limitation? Unavailability of secondary adamantium?
They are also highly skilled with various firearms and often use specialized ammunition.


text:
Q: How we solve iterated integrals such as this one? Here is the problem

$(\textbf{20}\text{ points})$ Calculate the following iterated
intergals:
$$\text{a. } \int_0^2\mathrm dx
 \int_{-1}^1\big(3x^2-(x+y)e^y+xy^3\big)\ \mathrm dy,$$

I can do the next if you explain how to solve this.
Thanks!

A: I personally dislike this notation, and think it's easier to see it written as:
$$
\int_0^2\int_{-1}^1(3x^2-xe^y-ye^y+xy^3)\mathop{dy}\mathop{dx}
$$
Evaluate the $y$ integral first, considering $x$ as a constant:
\begin{align*}
\int_{-1}^1(3x^2-xe^y-ye^y+xy^3) \mathop{dy}&=\left.\left[3x^2y-xe^y-(y-1)e^y+xy^4/4\right]\right|_{y=-1}^{y=1}\\
&=6x^2-\left(e-\frac1e\right)x-\frac2e
\end{align*}
Then evaluate the outer integral:
\begin{align*}
\int_0^2\left(6x^2-\left(e-\frac1e\right)x-\frac2e\right) \mathop{dx}
\end{align*}


text:
Q: How to Decompress nested GZip (TGZ) files in C# I am receiving a TGZ file that will contain one plain text file along with possibly one or more nested TGZ files.  I have figured out how to decompress the main TGZ file and read the plain text file contained in it, but I have not been able to figure out how to recognize and decompress the nested TGZ files.  Has anyone come across this problem before?
Also, I do not have control over the file I am receiving, so I cannot change the format of a TGZ file containing nested TGZ files.  One other caveat (even though I don't think it matters) is that these files are being compressed and tarred in a Unix or Linux environment.
Thanks in advance for any help.

A: Try the SharpZipLib (http://www.icsharpcode.net/OpenSource/SharpZipLib/Download.aspx) free library.
It lets you work with TGZ and has methods to test files before trying to inflate them; so you can either rely on the file extensions being correct, or test them individually to see if you can read them as compressed files - then inflate them once the main file has been decompressed.

A: To read and write .tar and .tgz (or .tar.gz ) files from .NET, you can use this one-file tar class:
http://cheesoexamples.codeplex.com/SourceControl/changeset/view/97756#1868643
Very simple usage. To create an archive:
string[] filenames = { ... };
Ionic.Tar.CreateArchive("archive.tar", filenames);

Create a compressed (gzip'd) tar archive:
string[] filenames = { ... };
Ionic.Tar.CreateArchive("archive.tgz", filenames, TarOptions.Compress);

Read a tar archive:
var entries = Ionic.Tar.List("archive.tar");  // also handles .tgz files

Extract all entries in a tar archive:
var entries = Ionic.Tar.Extract("archive.tar");  // also handles .tgz files

A: Take a look at DotNetZip on CodePlex.

"If all you want is a better
  DeflateStream or GZipStream class to
  replace the one that is built-into the
  .NET BCL, that is here, too.
  DotNetZip's DeflateStream and
  GZipStream are available in a
  standalone assembly, based on a .NET
  port of Zlib. These streams support
  compression levels and deliver much
  better performance that the built-in
  classes. There is also a ZlibStream to
  complete the set (RFC 1950, 1951,
  1952)."

It appears that you can iterate through the compressed file and pull the individual files out of the archive.  You can then test the files you uncompressed and see if any of them are themselves GZip files.
Here is a snippit from their Examples Page
using (ZipFile zip = ZipFile.Read(ExistingZipFile))
{
  foreach (ZipEntry e in zip)
  {
    e.Extract(OutputStream);
  }
}

Keith


text:
Q: Delete starting with fa- and ending with [ in Notepad++ My strings like this:  fa-adjust [],  fa-adn [],  fa-align-center [],  fa-align-justify [],  fa-align-left [],  fa-align-right [],  fa-ambulance [],  fa-anchor []
I want to delete strings between fa- and [characters by using Notepad++. I tried to delete it just like this pattern : \[ fa^ []+\], (?< fa-).*(? [), (fa-)\d+( [) and .* fa-(\d+) [. But it did not work.

A: search
   (?<=fa\-).*?(?=\[)

replace with nothing
I think this should do it

A: Another option:
Search for fa-.*?\[ in Regular expression mode. Replace with an empty string.

If you'd like to keep everything between the '-' and the '[':
Search for fa-(.*?)\[. Replace with \1[. This will keep everything inside the parentheses.


text:
Q: Advanced Python Regex: how to evaluate and extract nested lists and numbers from a multiline string? I was trying to separate the elements from a multiline string:
lines = '''c0 c1 c2 c3 c4 c5
0   10 100.5 [1.5, 2]     [[10, 10.4], [c, 10, eee]]  [[a , bg], [5.5, ddd, edd]] 100.5
1   20 200.5 [2.5, 2]     [[20, 20.4], [d, 20, eee]]  [[a , bg], [7.5, udd, edd]] 200.5'''

My aim is to get a list lst such that:
# first value is index
lst[0] = ['c0', 'c1', 'c2', 'c3', 'c4','c5']
lst[1] = [0, 10, 100.5, [1.5, 2], [[10, 10.4], ['c', 10, 'eee']], [['a' , 'bg'], [5.5, 'ddd', 'edd']], 100.5 ]
lst[2] = [1, 20, 200.5, [2.5, 2], [[20, 20.4], ['d', 20, 'eee']], [['a' , 'bg'], [7.5, 'udd', 'edd']], 200.5 ]

My attempt so far is this:
import re

lines = '''c0 c1 c2 c3 c4 c5
0   10 100.5 [1.5, 2]     [[10, 10.4], [c, 10, eee]]  [[a , bg], [5.5, ddd, edd]] 100.5
1   20 200.5 [2.5, 2]     [[20, 20.4], [d, 20, eee]]  [[a , bg], [7.5, udd, edd]] 200.5'''

# get n elements for n lines and remove empty lines
lines = lines.split('\n')
lines = list(filter(None,lines))

lst = []
lst.append(lines[0].split())

for i in range(1,len(lines)):
  change = re.sub('([a-zA-Z]+)', r"'\1'", lines[i])
  lst.append(change)

for i in lst[1]:
  print(i)

How to fix the regex?
Update
Test datasets
data = """
    orig  shifted  not_equal  cumsum  lst
0     10      NaN       True       1  [[10, 10.4], [c, 10, eee]]
1     10     10.0      False       1  [[10, 10.4], [c, 10, eee]]
2     23     10.0       True       2  [[10, 10.4], [c, 10, eee]]
"""

# Gives: ValueError: malformed node or string:

data = """
    Name Result Value
0   Name1   5   2
1   Name1   5   3
2   Name2   11  1
"""
# gives same error

data = """
product  value
0       A     25
1       B     45
2       C     15
3       C     14
4       C     13
5       B     22
"""
# gives same error

data = '''
    c0 c1
0   10 100.5
1   20 200.5
'''
# works perfect

A: As noted in the comments, this task is impossible to do with regex. Regex is fundamentally unable to handle nested constructs. What you need is a parser.
One of the ways to create a parser is PEG, which lets you set up a list of tokens and their relations to each other in a declarative language. This parser definition is then turned into an actual parser that can handle the described input. When parsing succeeds, you will get back a tree structure with all the items properly nested.
For demonstration purposes, I've used the JavaScript implementation peg.js, which has an online demo page where you can live-test parsers against some input. This parser definition:
{
    // [value, [[delimiter, value], ...]] => [value, value, ...]
    const list = values => [values[0]].concat(values[1].map(i => i[1]));
}
document
    = line*
line "line"
    = value:(item (whitespace item)*) whitespace? eol { return list(value) }
item "item"
    = number / string / group
group "group"
    = "[" value:(item (comma item)*) whitespace? "]" { return list(value) }
comma "comma"
    = whitespace? "," whitespace?
number "number"
    = value:$[0-9.]+ { return +value }
string "string"
    = $([^ 0-9\[\]\r\n,] [^ \[\]\r\n,]*)
whitespace "whitespace"
    = $" "+
eol "eol"
    = [\r]? [\n] / eof
eof "eof"
    = !.

can understand this kind of input:

c0 c1 c2 c3 c4 c5
0   10 100.5 [1.5, 2]     [[10, 10.4], [c, 10, eee]]  [[a , bg], [5.5, ddd, edd]]
1   20 200.5 [2.5, 2]     [[20, 20.4], [d, 20, eee]]  [[a , bg], [7.5, udd, edd1]]

and produces this object tree (JSON notation):
[
    ["c0", "c1", "c2", "c3", "c4", "c5"],
    [0, 10, 100.5, [1.5, 2], [[10, 10.4], ["c", 10, "eee"]], [["a", "bg"], [5.5, "ddd", "edd"]]],
    [1, 20, 200.5, [2.5, 2], [[20, 20.4], ["d", 20, "eee"]], [["a", "bg"], [7.5, "udd", "edd1"]]]
]

i.e.

*

*an array of lines,

*each of which is an array of values,

*each of which can be either a number, or a string, or another array of values

This tree structure can then be handled by your program.
The above would work for example with node.js to turn your input into JSON. The following minimal JS program accepts data from STDIN and writes the parsed result to STDOUT:
// reference the parser.js file, e.g. downloaded from https://pegjs.org/online
const parser = require('./parser');

var chunks = [];

// handle STDIN events to slurp up all the input into one big string
process.stdin.on('data', buffer => chunks.push(buffer.toString()));
process.stdin.on('end', function () {
    var text = chunks.join('');
    var data = parser.parse(text);
    var json = JSON.stringify(data, null, 4);
    process.stdout.write(json);
});

// start reading from STDIN
process.stdin.resume();

Save it as text2json.js or something like that and redirect (or pipe) some text into it:
# input redirection (this works on Windows, too)
node text2json.js < input.txt > output.json

# common alternative, but I'd recommend input redirection over this
cat input.txt | node text2json.js > output.json

There are PEG parser generators for Python as well, for example https://github.com/erikrose/parsimonious. The parser creation language differs between implementations, so the above can only be used for peg.js, but the principle is exactly the same.

EDIT I've dug into Parsimonious and recreated the above solution in Python code. The approach is the same, the parser grammar is the same, with a few tiny syntactical changes.
from parsimonious.grammar import Grammar
from parsimonious.nodes import NodeVisitor

grammar = Grammar(
    r"""
    document   = line*
    line       = whitespace? item (whitespace item)* whitespace? eol
    item       = group / number / boolean / string
    group      = "[" item (comma item)* whitespace? "]"
    comma      = whitespace? "," whitespace?
    number     = "NaN" / ~"[0-9.]+"
    boolean    = "True" / "False"
    string     = ~"[^ 0-9\[\]\r\n,][^ \[\]\r\n,]*"
    whitespace = ~" +"
    eol        = ~"\r?\n" / eof
    eof        = ~"$"
    """)

class DataExtractor(NodeVisitor):
    @staticmethod
    def concat_items(first_item, remaining_items):
        """ helper to concat the values of delimited items (lines or goups) """
        return first_item + list(map(lambda i: i[1][0], remaining_items))

    def generic_visit(self, node, processed_children):
        """ in general we just want to see the processed children of any node """
        return processed_children

    def visit_line(self, node, processed_children):
        """ line nodes return an array of their processed_children """
        _, first_item, remaining_items, _, _ = processed_children
        return self.concat_items(first_item, remaining_items)

    def visit_group(self, node, processed_children):
        """ group nodes return an array of their processed_children """
        _, first_item, remaining_items, _, _ = processed_children
        return self.concat_items(first_item, remaining_items)

    def visit_number(self, node, processed_children):
        """ number nodes return floats (nan is a special value of floats) """
        return float(node.text)

    def visit_boolean(self, node, processed_children):
        """ boolean nodes return return True or False """
        return node.text == "True"

    def visit_string(self, node, processed_children):
        """ string nodes just return their own text """
        return node.text

The DataExtractor is responsible for traversing the tree and pulling out data from the nodes, returning lists of strings, numbers, booleans, or NaN.
The concat_items() function performs the same task as the list() function in the Javascript code above, the other functions also have their equivalents in the peg.js approach, except that peg.js integrates them directly into the parser definition and Parsimonious expects definitions in a separate class, so it's a bit wordier in comparison, but not too bad.
Usage, assuming an input file called "data.txt", also mirrors the JS code:
de = DataExtractor()

with open("data.txt", encoding="utf8") as f:
    text = f.read()

tree = grammar.parse(text)
data = de.visit(tree)
print(data)

Input:

orig shifted not_equal cumsum lst
0 10 NaN True 1 [[10, 10.4], [c, 10, eee]]
1 10 10.0 False 1 [[10, 10.4], [c, 10, eee]]
2 23 10.0 True 2 [[10, 10.4], [c, 10, eee]]

Output:

[
    ['orig', 'shifted', 'not_equal', 'cumsum', 'lst'],
    [0.0, 10.0, nan, True, 1.0, [[10.0, 10.4], ['c', 10.0, 'eee']]],
    [1.0, 10.0, 10.0, False, 1.0, [[10.0, 10.4], ['c', 10.0, 'eee']]],
    [2.0, 23.0, 10.0, True, 2.0, [[10.0, 10.4], ['c', 10.0, 'eee']]]
]

In the long run, I would expect this approach to be more maintainable and flexible than regex hackery. Adding explicit support for NaN and for booleans (which the peg.js-Solution above does not have - there they are parsed as strings) for example was easy.

A: I honestly disagree that it is impossible to do with a regular expression. One might state more precisely that it is not possible with regular expressions alone.
See the following code which yields what you want and read the explanation further down.
Code
import regex as re
from ast import literal_eval

data = """
c0 c1 c2 c3 c4 c5
0   10 100.5 [1.5, 2]     [[10, 10.4], [c, 10, eee]]  [[a , bg], [5.5, ddd, edd]] 100.5
1   20 200.5 [2.5, 2]     [[20, 20.4], [d, 20, eee]]  [[a , bg], [7.5, udd, edd]] 200.5
"""

# regex definition
rx = re.compile(r'''
    (?(DEFINE)
        (?<item>[.\w]+)
        (?<list>\[(?:[^][\n]*|(?R))+\])
    )
    (?&list)|(?&item)
    ''', re.X)

# unquoted item
item_rx = re.compile(r"(?<!')\b([a-z][.\w]*)\b(?!')")

# afterwork party
def afterwork(match):
    match = item_rx.sub(r"'\1'", match)
    return literal_eval(match)

matrix = [
    [afterwork(item.group(0)) for item in rx.finditer(line)]
    for line in data.split("\n")
    if line
]

print(matrix)

This yields
[['c0', 'c1', 'c2', 'c3', 'c4', 'c5'], [0, 10, 100.5, [1.5, 2], [[10, 10.4], ['c', 10, 'eee']], [['a', 'bg'], [5.5, 'ddd', 'edd']], 100.5], [1, 20, 200.5, [2.5, 2], [[20, 20.4], ['d', 20, 'eee']], [['a', 'bg'], [7.5, 'udd', 'edd']], 200.5]]

Explanation
First, we import the newer regex module and the function literal_eval from the ast module which will be needed to transform the found matches in actual code. The newer regex module has far more power than the re module and provides recursive functionality and the powerful (yet not very well known) DEFINE construct for subroutines.
We define two types of elements, the first being a "simple" item, the latter being a "list item", see the demo on regex101.com.
In a second step we add quotes for those element who needs them (that is, unquoted elements starting with a character). Everything is fed into literal_eval and then saved within the list comprehension.


text:
Q: Exported Sql code gives error when runing I have a sql function code which i exported from other db. But when i run it gives error

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 4

My sql code is
CREATE DEFINER=`root`@`localhost` FUNCTION `getCOGS`(pItemId BIGINT) RETURNS float
    DETERMINISTIC
BEGIN
  declare vRet FLOAT;
  SET vRet = 0.00;
   SELECT SUM(d.quantity*d.unitPrice) / SUM(d.quantity) INTO vRet
    FROM transaction_detail d
    INNER JOIN transaction t ON (t.componentId = d.transactionId AND t.`type` = 'PURCHASE')
    WHERE d.itemId = pItemId AND d.`type` = 1 AND d.accountId = 12;
  RETURN vRet;
END

A: You have to change the delimiter.
Try this
DELIMITER |

CREATE DEFINER=`root`@`localhost` FUNCTION `getCOGS`(pItemId BIGINT) RETURNS float
    DETERMINISTIC
BEGIN
  declare vRet FLOAT;
  SET vRet = 0.00;
   SELECT SUM(d.quantity*d.unitPrice) / SUM(d.quantity) INTO vRet
    FROM transaction_detail d
    INNER JOIN transaction t ON (t.componentId = d.transactionId AND t.`type` = 'PURCHASE')
    WHERE d.itemId = pItemId AND d.`type` = 1 AND d.accountId = 12;
  RETURN vRet;
END
|
DELIMITER ;

The DELIMITER statement changes the standard delimiter which is semicolon ( ;) to another ( here |).
After your query, you can set it back to ;


text:
Q: Express Session use leads to a requires a middleware function I am attempting to implement sessions and passport.js on a small test website to see how to use user authentication.
var express = require("express");
var expressSession = require("express-sessions");
var mongoose = require("mongoose");
var passport = require("passport");
var bodyParser = require("body-parser");
var LocalStrategy = require("passport-local");
var passportLocalMongoose = require("passport-local-mongoose");
var User = require("./models/user");
var app = express();

mongoose.connect("mongodb://localhost/authDemoApp");
app.use(bodyParser.urlencoded({
extended: true}));
app.set("view engine", "ejs");

app.use(expressSession({
secret: "This is one hell of a secret",
resave: false,
saveUninitialized: false
}));

app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

app.listen(3000, function () {
console.log("Its running!!!");
});

The error that I get i:
throw new TypeError('app.use() requires a middleware function')
^
TypeError: app.use() requires a middleware function

I added call back function to app.use(expressSession...) making it:
app.use(function(err){
if (err){
console.log(err);
}else {
expressSession(...
}
});

The err value came back with:
IncomingMessage {
 _readableState:
ReadableState {
objectMode: false,
highWaterMark: 16384,
buffer: BufferList { head: null, tail: null, length: 0 },
length: 0,
pipes: null,
pipesCount: 0,

etc...
My question is middleware function and how do I add it to the app.use(expressSession etc... ?

A: The module is express-session, but your require statement is loading express-sessions.
Correcting this, the program runs.
var express = require("express");
var expressSession = require("express-session");
var mongoose = require("mongoose");
var passport = require("passport");
var bodyParser = require("body-parser");
var app = express();

mongoose.connect("mongodb://localhost/authDemoApp");
app.use(bodyParser.urlencoded({
  extended: true
}));
app.set("view engine", "ejs");

app.use(expressSession({
  secret: "This is one hell of a secret",
  resave: false,
  saveUninitialized: false
}));

app.use(passport.initialize());
app.use(passport.session());

app.listen(3000, function () {
  console.log("Its running!!!");
});

There is even a Github issue for it. #446 app.use() requires middleware functions