text:
Q: git bash on windows vs. WSL I downloaded git on my windows, and some other stuffs, including git bash, came along.
Although I didn't know why bash terminal has been included in the "git",
it supported not only the functions for git, but other functions like mkdir, cp, mv, just like a real linux bash terminal.
Recently I came to know the WSL (Windows Subsystem for Linux), which makes bash terminal available in windows.
Is the git bash quite inferior to WSL in terms of functionality?
Does it contain some constraints that WSL doesn't have?

A: WSL does not trigger file handlers when the file is changed in Windows tools - https://blogs.msdn.microsoft.com/commandline/2016/11/17/do-not-change-linux-files-using-windows-apps-and-tools/
So, you cannot run a dev server in WSL, as code changes made a Windows editor will not be reflected in the dev server.

A: Git for Windows is using the  mingw-w64 project (as illustrated here) and msys2.
See more in "How are msys, msys2, and msysgit related to each other?".
That is vastly different from WSL, which emulates an actual Linux distribution.

Does it contain some constraints that WSL doesn't have?

The Git for Windows is based on a POSIX compatibility layer, which has limitations: POSIX support is deprecated since Windows 8.

Note: WSL will soon be replaced by WSL2, which uses an entirely new architecture that uses a real Linux kernel.

If your program depends on Git bash (and not WSL/WSL2 bash), make sure to put said Git for Windows first in your PATH, as Jon Skeet described in "USING "GIT BASH" FROM APPVEYOR", in an AppVeyor CI environment.
# Make sure we get the bash that comes with git, not WSL bash
  - ps: $env:Path = "C:\Program Files\Git\bin;$env:Path"


text:
Q: How to display my search to my table in VueJs? I just want to ask, I want to display the searched value in my table?
Below code displays Memb_ID in div.
div>

      <input type="text" v-model="search" placeholder="Search title..">
      Search title:

{{ cust.Memb_ID }}

          Member ID
          First Name
          Middle Name
          Last Name
          Address

          {{result.Memb_ID}}
          {{result.First_Name}}
          {{result.Middle_Name}}
          {{result.Last_Name}}
          {{result.Address}}

This is the output of my code.
I want something like this
I got the code from this question but couldn't implement on my own. Thanks for help!

A: So I thought I solved my problem by looping in the table body.
There's a bug in here. Every time I reload the page it doesn't load the vue file lol. I thought it was okay after refreshing the page it didn't display the table.
I don't know the bug

    <input type="text" v-model="search" placeholder="Search title..">

          Member ID
          First Name
          Middle Name
          Last Name
          Address

          {{result.Memb_ID}}
          {{result.First_Name}}
          {{result.Middle_Name}}
          {{result.Last_Name}}
          {{result.Address}}

and in script
computed: {
filteredList() {
  return this.results.filter(customer => {
    customer.Memb_ID.toLowerCase().includes(this.search.toLowerCase());
  });
}

},

redpajama_set_name: RedPajamaStackExchange


text:
Q: Integrating my program with a web2.0 website I'm creating an ELIZA-like chatterbot, and I'd like to calibrate it with Omegle, using what the other person type as the input.
If it was a regular HTML page, I could parse it and send back the response to some script, but checking the source code, I've noticed that the entire page is created using Javascript, but obfuscates the entire thing.
Any idea on how to do that?
Thanks!

A: Well you should ask the people that made Omegle about an API. From what I've seen, it doesn't have an open API, but maybe they can give you some extra info.
You can also try Firebug. It lets you see all the requests that are made and their target. The site is AJAX driven, that's why you can't see the desination scripts directly in the page.
You can (1) build a program that sends post requests to the targets show in the Firebug net panel and passes the data to the chat-bot or (2) build a browser plugin that does that (it's pretty easy to do in Firefox). You may need the browser plugin because of cross-domain request limitations and because you may not see the received messages from an external program/web-app - it's not very clear to me how they implemented that, i guess it's something Comet-like.
Hope this helps :).


text:
Q: Visual Studio 2015 NodeJS/Typescript overwriting node startup file I keep getting the following error:
Error Code: TS5055
Cannot write file C:/project/dir/server.js' because it would overwrite input file.
Project: TypeScript/JavaScript Virtual Projects

I even tried changing my entry filename to nodeserver.js and after a while I get the same error:
Error Code: TS5055
Cannot write file C:/project/dir/nodeserver.js' because it would overwrite input file.
Project: TypeScript/JavaScript Virtual Projects

How can I find out what component is trying to overwrite it?
I did notice the file has the BuildAction set to Compile and 'Publish' to true. Could this be the cause? What is the implication of turning off Compile for a .js file? Will I not get any error checking?
Config Files
My tsconfig.json
{
  "compileOnSave": true,
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "moduleResolution": "node",
    "isolatedModules": false,
    "jsx": "react"
  },
  "exclude": [
    "node_modules",
    "public",
    "server.js",
    "Scripts/typings/main",
    "Scripts/typings/main.d.ts"
  ],
  "filesGlob": [
    "./src/**/*.ts",
    "./src/**/*.tsx"
  ]
}

My package.json
{
  "name": "contract-vs-paye-calc-type-script",
  "version": "0.0.0",
  "description": "ContractVsPayeCalcTypeScript",
  "scripts": {
    "start": "node nodeserver.js",
    "lint": "eslint src"
  },
  "main": "/src/App.js",
  "author": {
    "name": "MC",
    "email": "admin@admin.com"
  },
  "dependencies": {
    "babel-core": "^6.7.7",
    "babel-loader": "^6.2.4",
    "express": "3.4.4",
    "jade": "*",
    "react": "^15.0.1",
    "react-dom": "^15.0.1",
    "react-hot-loader": "^1.3.0",
    "stylus": "*",
    "webpack": "^1.13.0",
    "webpack-dev-server": "^1.14.1"
  },
  "module": {
    "loaders": [
      {
        "test": "/\\.ts(x?)$/",
        "loader": "babel-loader!ts-loader"
      }
    ]
  }
}

A: It seems that typescript compiler tries to transpile everything, including files that are already javascript. The solution is to add a new field outDir, to the compilerOptions, so it looks like this:
{
    ...
    "compilerOptions": {
        ...
        "outDir": "generated"
    }
    ...
}


text:
Q: knockout js prevents existing html observable from updating I'm just starting learning knockout.js and am a bit stuck on managing observables and updating them correctly. See the jsfiddle for the code.
 self.addItem = function(item, event){
    ptitle = $(event.currentTarget).prev('h3').text();

    self.items.push({
      productQty: self.productQty(),
      productClip: self.productClip(),
      productTitle: ptitle
    });
  }

http://jsfiddle.net/L61qhrc1/
What I have is a list of existing html elements. I want to create another list from that list with some input fields that can be set. It's mostly working but I cannot figure out from the examples around the net I've been looking at.
when one field updates all the fields in the list update but I only want the field I'm currently updating to be updated not the whole list.
Can any kind person point me in the right direction?
Cheers.

A: As I said in my comment, your user interface has to be a logical consequence of your data and viewmodel. Your viewmodel must never be concerned with the details of the view.
Also, your fiddle looks pretty over-engineered to me.
The following is what I have gathered from your sample, but in a less byzantine way.

*

*Make separate self-contained viewmodels. Ideally make them so that they can bootstrap themselves from the data you pass to the constructor.

*Working with templates keeps the HTML of the view clean and improves modularity and reusability.

*For more complex data, consider the the mapping plugin to bootstrap your models.

*Consult Unique ids in knockout.js templates for a way to create working <input> /  pairs.

function ListItem(data, parent) {
    var self = this;
    data = data || {};

    self.productQty = ko.observable(data.productQty);
    self.productClip = ko.observable(!!data.productClip);
}

function Product(data) {
    var self = this;
    data = data || {};

    self.title = ko.observable(data.title);
    self.id = ko.observable(data.id);
    self.items = ko.observableArray();
    self.newItem = new ListItem();

    self.addItem = function () {
        self.items.push(new ListItem(ko.toJS(self.newItem), self));
    };
    self.removeItem = function (item) {
        self.items.remove(item);
    };
}

function ProductList(data) {
    var self = this;
    data = data || {};

    self.products = ko.observableArray(ko.utils.arrayMap(data.products, function (p) {
        return new Product(p);
    }));
}

var vm = new ProductList({
    products: [
        {title: "ProductName 1", id: "ProductId 1"},
        {title: "ProductName 2", id: "ProductId 2"}
    ]
});

ko.applyBindings(vm);
ul {
    list-style-type: none;
    padding: 5px;
}


text:
Q: REST APIs atomic? I would like to know the importance of ensuring atomicity in rest api's.
Say suppose there exists a REST API
   insertItems(List<String> items)

Should we design API such that all items are inserted or none ? (atomic)
Example : Sa¥ suppose we tried to insert 10 items, and received error while inserting 5th item, we revoke all the 4 items inserted. (To make sure as if none were inserted) and return back to caller that API call failed.
OR
Return the items which were inserted successfully such that client can handle with failed items ?
Example : SaY suppose we tried to insert 10 items, and received error while inserting 5th item, we return list of 4 items that were inserted successfully to caller. This leads caller to process the returned list and analyze what items were failed or etc. This involves burden on client side to deal with analysis.
Do you guys have any strong opinion on either cases ? What is ideal to use and under what circumstances ?


text:
Q: Problema obteniendo valor mas parecido a otro
Hola buenas, tengo que hacer una función que me devuelva el valor más parecido a un parámetro dado.
El valor mas parecido se obtiene cuando la distancia entre los valores es más pequeña.
Además, se pide que cumpla dos condiciones.
Esta es mi función distancia

def distancia(v1,v2):
    fecha1 = v2.fecha_construccion - v1.fecha_construccion
    fecha2 = v1.fecha_construccion - v2.fecha_construccion
    distancia1 = fecha1.days
    distancia2 = fecha2.days
    distancia3 = sqrt((v1.precio-v2.precio)**2 + (v1.superficie - v2.superficie)**2 + (v1.habitaciones - v2.habitaciones)**2 + (v1.baños-v2.baños)**2)
    if fecha1>fecha2:
        distancia = distancia1 + distancia3
    else:
        distancia = distancia2 + distancia3
    return(distancia)```

>y esta es la función que he hecho :
 ```def vivienda_mas_parecida(viviendas, vivienda):
    resultado = None
    dist = 10 **10000 #numero grande para referencia
    for v in viviendas:
        if ((v.vendido == False) and (v.localidad != vivienda.localidad)):
            d = distancia(v, vivienda)
            if  d<dist :
                resultado = v
                dist = d

    return resultado```

>el problema esque me da este error y nose como solucionarlo.

```line 147, in distancia
    distancia3 = sqrt((v1.precio-v2.precio)**2 + (v1.superficie - v2.superficie)**2 + (v1.habitaciones - v2.habitaciones)**2 + (v1.baños-v2.baños)**2)
TypeError: unsupported operand type(s) for -: 'int' and 'str'```
**TODOS LOS DATOS QUE ESTAN RESTANDO SON TIPOS INT**


text:
Q: Ms Access Query: Concatenating Rows through a query Suppose I have table in Ms Access with following information:
ColumnA ColumnB
1       abc
1       pqr
1       xyz
2       efg
2       hij
3       asd

My question is, how can I concatenate the values in the second column to a row value based on the first column. The query results that I want is as follows:
ColumnA ColumnB
1       abc, pqr, xyz
2       efg, hij
3       asd

I want to achieve this through a query. Can someone help me attain this?

A: Here's an outstanding link re: how to do this from within SQL by calling a function. The instructions are exceptionally clear & the function is written for you so you can just copy, paste & go. Even someone with no knowledge of VB can easily implement it:
Concatenate values from related records

A: this can be very difficult to obtain. If you MUST do it in a query and not a function, the problem that you will run into is the limit of the number of rows you can concatenate into one column.  So far the only way that i have found to achieve this is via iif statements.
SELECT
test1.ColumnA AS ColumnA,
First([test1].[ColumnB]) & IIf(Count([test1].[ColumnB])>1,"," & Last([test1].[ColumnB])) AS ColumnB
FROM test1
GROUP BY test1.ColumnA;

returns:
ColumnA  ColumnB
1      abc,xyz
2      efg,hij
3      asd

This will return the first and the last only, but I'm sure with a little work you could work out the Choose function, but like I said you would have to add more iif statements for each additional item you want to add, hence the limitation.

A: You need a function to do the concatenation.
Microsoft Access condense multiple lines in a table
Example using your data:
Select T.ColumnA
  , GetList("Select ColumnB From Table1 As T1 Where T1.ColumnA = " & [T].[ColumnA],"",", ") AS ColumnBItems
From Table1 AS T
Group By T.ColumnA;

A: The table could have a sequence column, which gives it a unique primary key of ColumnA-sequence:
table: t1
ColumnA sequence ColumnB
1       1        abc
1       2        pqr
1       3        xyz
2       1        efg
2       2        hij
3       1        asd

And a Crosstab could be created:
query: x1
TRANSFORM Min([columnB] & ", ") AS Expr1
SELECT t1.columnA
FROM t1
GROUP BY t1.columnA
PIVOT t1.sequence;

columnA 1    2    3
1       abc, pqr, xyz,
2       efg, hij,
3       asd,

Then a final query can combine the columns and remove the last comma:
SELECT x1.columnA, Left([1] & [2] & [3],Len([1] & [2] & [3])-2) AS columnB FROM x1;

columnA columnB
1       abc, pqr, xyz
2       efg, hij
3       asd

To automate filling in the sequence, the following VBA code can be used:
Sub fill_sequence_t1()
  Dim i: i = 1
  Do While DCount("*", "t1", "sequence IS NULL") > 0
    DoCmd.RunSQL "SELECT t1.columnA, Min(t1.columnB) AS columnB_min INTO t2" & _
                 " FROM t1 WHERE t1.sequence IS NULL GROUP BY t1.columnA;"
    DoCmd.RunSQL "UPDATE t1 INNER JOIN t2 ON (t1.columnA = t2.columnA)" & _
                 " AND (t1.columnB = t2.columnB_min) SET t1.sequence=" & i
    CurrentDb.TableDefs.Delete "t2"
    i = i + 1
  Loop
End Sub


text:
Q: javax.mail.internet.ParseException: In Content-Type string , expected '/', got null I know this question was answered somewhere else but that didn't work for me so here i am.
Basically my code will login to your e-mail and send messages to multiple people.
of course its not done, i know that, but it has enough code to work because i based it off one of my command line programs that does the same thing.
anyways here is some code.
sender class :
public class Sender {

public static void send(JTextArea listRecepients, JTextField textSubject, JTextArea textBody, JTextField txtSMTP,
        JTextField txtEmail, JPasswordField txtPassword, JCheckBox boxHtml, JSpinner ammountSpin, JSpinner timeSpin, JProgressBar progressBar) {

    String subject = textSubject.getText();

    String message = textBody.getText();

    for (String line : listRecepients.getText().split("\\n")) setEmails(line, subject, message, txtSMTP, txtEmail, txtPassword, boxHtml, ammountSpin, timeSpin, progressBar);
}

private static void setEmails(String line, String subject, String message, JTextField txtSMTP,
        JTextField txtEmail, JTextField txtPassword, JCheckBox boxHtml, JSpinner ammountSpin, JSpinner timeSpin, JProgressBar progressBar) {

    List<String> emails = new ArrayList<String>(Arrays.asList(line));
    sendEmail(subject, emails, message, txtSMTP, txtEmail, txtPassword, boxHtml, ammountSpin, timeSpin, progressBar);
}

public static void sendEmail(final String subject, final List<String> emailToAddresses,
            final String emailBodyText, JTextField txtSMTP, JTextField txtEmail, JTextField txtPassword, JCheckBox boxHtml, JSpinner ammountSpin, JSpinner timeSpin, JProgressBar progressBar) {

    final String username = txtEmail.getText();

    final String password = txtPassword.getText();

    final String smtpHost = txtSMTP.getText();

    Properties props = new Properties();

    // do not change - start
    props.put("mail.smtp.user", "username");
    props.put("mail.smtp.host", smtpHost);
    // props.put("mail.debug", "true");
    props.put("mail.smtp.auth", "true");
    // do not change - end

    Session session = Session.getInstance(props,
            new javax.mail.Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            });
    String emails = null;
    int ammount, time;

    try {
        ammountSpin.commitEdit();
    } catch (ParseException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    ammount = (int) ammountSpin.getValue();

    try {
        timeSpin.commitEdit();
    } catch (ParseException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    time = (int) timeSpin.getValue();
    time = time*1000;
    try {

        Message message = new MimeMessage(session);

        message.setFrom(new InternetAddress(username));

        message.setSubject(subject);

        if (boxHtml.isSelected() == true){
            String content = "\n\n";
            content += emailBodyText + "\n";
            content += "\n";
            content += "\n";
            message.setContent(content, "html");
        }else{
            String content = emailBodyText;
            message.setContent(content, "text");
        }

        StringBuilder sb = new StringBuilder();
        int i = 0;
        for (String email : emailToAddresses) {
            sb.append(email);
            i++;
            if (emailToAddresses.size() > i) {
                sb.append(", ");
            }
        }

        emails = sb.toString();

        message.setRecipients(Message.RecipientType.BCC,
                InternetAddress.parse(sb.toString()));

        System.out.println("Sending Email to " + emails + " from "
                + username + " with Subject - " + subject);

        for (int x = 0; x < ammount; x++){
            Transport.send(message);
            try {
                Thread.sleep(time);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println("Email successfully sent to " + emails);

    } catch (MessagingException e) {
        System.out.println("Email sending failed to " + emails);
        failed(e);
    }
}
public static void failed (MessagingException e){
    JFrame frame = new JFrame("Failed to send");
    JOptionPane.showMessageDialog(frame, "The Process has failed with exception code : "+ e, "Warning", JOptionPane.WARNING_MESSAGE);
}

}
and yes i know there are more efficient ways of doing this insted of sending the required fields through multiple methods but im lazy. thats why i came here :p
thanks for your help and lmk if you want the other 3 classes. but the error should be in this one.

A: Change : message.setContent(content, "html")
To : message.setContent(content, "text/html")
The error message is looking for "/", witch is the / in text/html

A: Replace message.setContent(content, "html") with message.setText(content, null, "html").  Replace message.setContent(content, "text") with message.setText(content).

A: Bill's answer seem to cover it however it appears you are still stuck.  One issue is that message.setContent(content, "text"); is going to set the content type to text/text when you want text/plain.  Here is an example:
public class GMTCZ {
    public static void main(String[] args) throws Exception, Exception {
        MimeMessage mime = new MimeMessage((Session) null);

        mime.setText("That was 1 arg setText");
        print(mime);

        String charset = MimeUtility.mimeCharset(MimeUtility.getDefaultJavaCharset());
        mime.setText("<title>This is 3 arg setText</title>", charset, "html");
        print(mime);

        mime.setText("That was 3 arg setText.", charset, "plain");
        print(mime);

        //OR

        Message msg = new MimeMessage((Session) null);
        msg.setContent("<title>That was 2 arg setContent</title>", "text/html");
        print(msg);

        msg.setContent("That was 2 arg setContent.", "text/plain");
        print(msg);

        msg.setContent("<title>That was 2 arg setContent.</title>", "text/html");
        print(msg);
    }

    private static void print(Message msg) throws Exception {
        msg.saveChanges();
        msg.writeTo(System.out);
        System.out.println();
        System.out.println("====");
    }
}

A: I figured it out, basically i changes the props.put values to this :
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", smtpHost);
props.put("mail.smtp.user", username);
props.put("mail.smtp.password", password);
props.put("mail.smtp.port", smtpPort);
props.put("mail.smtp.auth", "true");

and it worked. all i did was add the port. and i also made my gmail accout access untrusted apps.


text:
Q: How to call columns without using Group By clause I am new to sql, i had one  doubt
    select  t1.PayeeCode,t1.PayeeName,t1.PayeeIFSCCode,t1.grossAmount as ga,t2.Deduction
      as da,(t1.grossAmount-t2.Deduction) as SubAmount from (
     (select PayeeCode,PayeeName,PayeeIFSCCode,PayeeBankAcNo,sum(PayeeAmount) as
    grossAmount from tblPayees where AccountType='g' group by payeeCode, PayeeName,PayeeIFSCCode,PayeeBankAcNo) t1

        inner join

     (select PayeeCode,sum(PayeeAmount) as deduction from tblPayees where
       AccountType='d' group by payeeCode) t2

 on t1.PayeeCode=t2.PayeeCode
 )

curent  result

PayeeCode    payeename   payeeifsccode   ga   da   subamount  type
--------------------------------------------------------------
p1              x        123         1300   1400  100         g
p1              z        34             450    550  100         g
p1              y        35            150    150  0          d
p2              z        45            150   100   50         d

expected result:

PayeeCode   payeename   payeeifsccode   ga   da   subamount  type
--------------------------------------------------------------
p1              x        123         1750    1950  200        g
p1              y         35        300     250   50        d

Here this is the Column 'tblPayees.PayeeName' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
I know here why eeror is occured but , i dont want to group by payeeName, i wnat only payeecode.How to do that?
   help me please

A: The problem is that you either need to include the column in group by  clause or use an aggregate in select list like MIN, MAX, etc. otherwise the database engine doesn't know what to do with it i.e. what value from the group to select.
Now are you sure you cannot group on both columns? Can you have different PayeeName for the same PayeeCode? If not, you can include it in group by:
select PayeeCode, PayeeName from tblPayees group by PayeeCode, PayeeName

If PayeeName can vary for the same PayeeCode then you need to tell the database engine which value you want to select by means of aggregate function:
select PayeeCode, Max(PayeeName) as PayeeName from tblPayees group by PayeeCode

It is even possible to concatenate the PayeeName values in a comma-separated list, but this is out of scope of this question I guess.


text:
Q: Failed attempts at natural sort in MySQL I'm trying to achieve natural/alphanumeric sorting in MySQL and having no luck. I have read several Stack articles and various articles on the topic I found in google searches. Here is the basic query I began with:
select VideoTitle, VideoID
from Filters
where VideoSource = 'Netflix'
and IMDBSeries = 'tt0367279'
and PublishDate is not null
ORDER BY VideoTitle

That query yields this result set:

Arrested Development Season 1: Ep. 1 Pilot
Arrested Development Season 1: Ep. 10 Pier Pressure
Arrested Development Season 1: Ep. 2 Top Banana
Arrested Development Season 1: Ep. 3 Bringing Up Buster
Arrested Development Season 1: Ep. 4 Key Decisions
Arrested Development Season 1: Ep. 5 Charity Drive
Arrested Development Season 1: Ep. 6 Visiting Ours
Arrested Development Season 1: Ep. 7 In God We Trust
Arrested Development Season 1: Ep. 8 My Mother, the Car
Arrested Development Season 1: Ep. 9 Storming the Castle

Notice this row is out of order from a natural sorting perspective:

Arrested Development Season 1: Ep. 10 Pier Pressure

Based on the posts/articles I read, I have also tried these approaches, with their accompanying result sets:
select VideoTitle
from Filters
where VideoSource = 'Netflix'
and IMDBSeries = 'tt0367279'
and PublishDate is not null
ORDER BY CAST(VideoTitle AS UNSIGNED), VideoTitle

Arrested Development Season 1: Ep. 1 Pilot
Arrested Development Season 1: Ep. 10 Pier Pressure
Arrested Development Season 1: Ep. 2 Top Banana
Arrested Development Season 1: Ep. 3 Bringing Up Buster
Arrested Development Season 1: Ep. 4 Key Decisions
Arrested Development Season 1: Ep. 5 Charity Drive
Arrested Development Season 1: Ep. 6 Visiting Ours
Arrested Development Season 1: Ep. 7 In God We Trust
Arrested Development Season 1: Ep. 8 My Mother, the Car
Arrested Development Season 1: Ep. 9 Storming the Castle

select VideoTitle
from Filters
where VideoSource = 'Netflix'
and IMDBSeries = 'tt0367279'
and PublishDate is not null
ORDER BY LENGTH(VideoTitle), VideoTitle

Arrested Development Season 1: Ep. 1 Pilot
Arrested Development Season 1: Ep. 2 Top Banana
Arrested Development Season 1: Ep. 4 Key Decisions
Arrested Development Season 1: Ep. 5 Charity Drive
Arrested Development Season 1: Ep. 6 Visiting Ours
Arrested Development Season 1: Ep. 10 Pier Pressure
Arrested Development Season 1: Ep. 7 In God We Trust
Arrested Development Season 1: Ep. 3 Bringing Up Buster
Arrested Development Season 1: Ep. 8 My Mother, the Car
Arrested Development Season 1: Ep. 9 Storming the Castle

select VideoTitle
from Filters
where VideoSource = 'Netflix'
and IMDBSeries = 'tt0367279'
and PublishDate is not null
ORDER BY VideoTitle + 0 ASC

Arrested Development Season 1: Ep. 1 Pilot
Arrested Development Season 1: Ep. 9 Storming the Castle
Arrested Development Season 1: Ep. 8 My Mother, the Car
Arrested Development Season 1: Ep. 7 In God We Trust
Arrested Development Season 1: Ep. 6 Visiting Ours
Arrested Development Season 1: Ep. 5 Charity Drive
Arrested Development Season 1: Ep. 4 Key Decisions
Arrested Development Season 1: Ep. 3 Bringing Up Buster
Arrested Development Season 1: Ep. 2 Top Banana
Arrested Development Season 1: Ep. 10 Pier Pressure

Any ideas?

A: The best solution would be to store the show title, the season, the episode number, and the episode title in separate columns.
In this case, you might be able to do some string manipulation to get what you need.
ORDER BY SUBSTRING_INDEX(SUBSTRING_INDEX(SUBSTRING_INDEX(VideoTitle, ': ', -1), ' ', 2), ' ', -1)+0

This is such a fragile solution, though.

A: If you really want, you can sort this by piece:
order by substring_index(VideoTitle, ' Season ', 1),
         substring_index(VideoTitle, ' Season ', -1) + 0,
         substring_index(VideoTitle, ': Ep. ', -1) + 0

This assumes that the string ' Season ' an : Ep. only occur once in each title.
The following version should also be pretty close, assuming seasons have only one digit:
order by substring_index(VideoTitle, ': Ep. ', 1),
         substring_index(VideoTitle, ': Ep. ', -1) + 0

A: If creating new columns for making your model better searchable I would go with a more elegant solution than having to break down the string by pieces.
select VideoTitle
  from (select VideoTitle,
               VideoTitle REGEXP '.+Ep\\. [0-9]{2}.+' vd2dig
          from videos
       ) sub
 order by vd2dig, VideoTitle;

This will essentially make VideoTitle when having two digits to 1 and when it has one digit it will be 0 so I order by this column first then the natural order on VideoTitle
See it working here: http://sqlfiddle.com/#!9/6abde/1


text:
Q: Non-dimensionalise this ODE I have the ODE:
\begin{equation}
    \frac{dx}{dt} = ax - \frac{b}{b + x} x
\end{equation}
where $a$ has units $[1/t]$ and $b$ has units $[x/t]$. $x$, in this example, is a resource, and the last term describes consumption rate, which cannot go above $x$.
I would like to non-dimensionalize the equation, but I'm running into problems with the consumption term. Here's my working:
Define the dimensionless variables:
\begin{equation}
    \hat{t} = \frac{t}{t^{*}}, \quad
    \hat{x} = \frac{x}{x^{*}}
\end{equation}
Rewrite the ODE:
\begin{equation}
    \frac{d\hat{x}x^{*}}{d\hat{t}{t^{*}}} = a \hat{x}x^{*} - \frac{b}{b + \hat{x}x^{*}}\hat{x}x^{*}
\end{equation}
\begin{equation}
    \frac{d\hat{x}}{d\hat{t}} = a t^{*} \hat{x} - t^{*} \frac{b}{b + \hat{x}x^{*}}\hat{x}
\end{equation}
Define $t^{*} = a$ and $x^{*} = b/a$, then:
\begin{equation}
     \frac{d\hat{x}}{d\hat{t}} = a \hat{x} - \frac{1}{a} \frac{b}{b + \hat{x} \frac{b}{a}}\hat{x}
\end{equation}
\begin{equation}
     \frac{d\hat{x}}{d\hat{t}} = a \hat{x} - \frac{1}{a} \frac{1}{1 + \hat{x} \frac{1}{a}}\hat{x}
\end{equation}
\begin{equation}
     \frac{d\hat{x}}{d\hat{t}} = a \hat{x} - \frac{1}{a} \frac{1}{ \frac{a + \hat{x}}{a}}\hat{x}
\end{equation}
\begin{equation}
     \frac{d\hat{x}}{d\hat{t}} = a \hat{x} - \frac{1}{a} \frac{a}{a + \hat{x}}\hat{x}
\end{equation}
which gives us
\begin{equation}
     \frac{d\hat{x}}{d\hat{t}} = a \hat{x} - \frac{1}{a + \hat{x}}\hat{x}
\end{equation}
However, the consumption term is not non-dimensionalized as it still has units of time.
I'd appreciate any advice.


text:
Q: AWS Amplify TypeError: S3 is not a constructor when bundling with Parcel I am using the AWS Amplify Storage module to store and retrieve user files using the JavaScript API. When I serve or build with Parcel, the following error message is printed to the console:
TypeError: S3 is not a constructor
    at AWSS3Provider._createS3 (AWSS3Provider.ts:501)
    at AWSS3Provider.<anonymous> (AWSS3Provider.ts:130)
    at step (AWSS3Provider.ts:19)
    at Object.next (AWSS3Provider.ts:19)
    at fulfilled (AWSS3Provider.ts:19)

The error occurs with Parcel v1.12.4 and AWS Amplify v2.2.4.
Minimal steps to reproduce
An appropriately configured Cognito identity pool and S3 bucket per the AWS Amplify Storage documentation are needed.
The following files should all be in the same directory.
A package.json with dependencies.
{
  "main": "index.js",
  "dependencies": {
    "aws-amplify": "^2.2.4",
    "lodash": "^4.17.15"
  }
}

An aws-exports.js that specifies the identity pool and S3 bucket:
export const awsconfig = {
  Auth: {
    identityPoolId: "xx-xxxx-x:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
    region: "xx-xxxx-x"
  },
  Storage: {
    AWSS3: {
      bucket: "a-bucket-name",
      region: "xx-xxxx-x"
    }
  }
};

An index.html:
<!DOCTYPE html>
<html lang="en">
  <body>
    <main></main>
    <script src="./index.js"></script>
  </body>
</html>

An index.js:
import Amplify, { Storage } from "aws-amplify";
import { awsconfig } from "./aws-exports";
Amplify.configure(awsconfig);

// not required, but helps to confirm everything else worked
window.LOG_LEVEL = "DEBUG";

Storage.get("test.txt")
  .then(result => console.log(result))
  .catch(err => console.log(err));

Run the following
npm install
parcel index.html

then view the page and error message in the console.
Note that replacing the call to Storage.get() with Storage.configure() does not produce an error.
I have tried bundling the same with a default webpack configuration, and I do not observe the error. This makes me suspect that I may need to override some parcel configuration.

A: I encountered this when deploying Lambdas using @aws-cdk/aws-lambda-nodejs.
I worked around this by using the aws-sdk available in the Lambda runtime environment instead of bundling my own copy in each Lambda's assets. It should equally apply to other assets that end up running in Lambda.
npm install --save-dev parcel-plugin-externals

Add to package.json:
"externals": [
    "aws-sdk"
]

Instantiate S3 client using
import * as AWS from 'aws-sdk';
const s3 = new AWS.S3();

instead of
import * as S3 from 'aws-sdk/clients/s3';
const s3 = new S3();

References:

*

*https://github.com/aws/aws-cdk/issues/7685


text:
Q: using jquery serialize in ajax operation for plugin I am writing a plugin with dynamic no. of input fields in form. To submit form via ajax, I have used jquery serialize() function.
$(".submit").submit(function( event ) {
        event.preventDefault();
        var data = {
            action: 'wpaie_ajax_action',
            operation: 'import',
            importData: $(this).serialize()
//do some operation
        };
        $.post(ajaxurl, data, function(response) {

        });
    });

Ajax is working fine and data is also serialized but I am not able understand how to read the form input fields.
If I am using echo $_POST["importData"], it is showing me serialized data but what should
be the correct way to read that serialized data.

A: Provided that your server receives data in the form of a string which it should if you're using the jQuery serialize() function.
It will be something like:
name1=value&name2=value&name3=value
You just need to parse the string into an array as follows:
$parameters = array();
parse_str($_GET, $parameters);

See the following for more information: http://www.php.net/manual/en/function.parse-str.php


text:
Q: Refresh list of items after changes in MySql database MVC - live changes on page I am building an ASP.NET MVC Web Application. I am using MySql Database as data storage. On one of the Views, I show the list of matches dragged from the DB. Of course, the user who comes to ../Matches/Index will see only the matches from the moment when he clicked the button to go to the page.
Is it possible to refresh the page for the user when the displayed data(in this case it's a list of models [Match] with few properties)
changes in any way = new item added / item deleted ?

I suppose there is a way of just doing an Ajax request in some interval, but it's resource consuming. But maybe keeping the constant bond between the server and the client puts even more load than this?

A: You could use SignalR which implements web sockets (constant connection with server; server will send message/response if there are any, even if there is no concurrent request as long as the web socket is established).
The response can be retrieved on the client side (JS) so you could modify anything on the current page. It's a popular C# library so you'll find a lot of tutorials here and there.


text:
Q: Correct way to use Ionic's social-sharing plugin? I am trying to implement Ionic's social sharing plugin into my app, but I'm having issues.
This is the error I get:

Here is my component.ts
import {SocialSharing} from '@ionic-native/social-sharing/ngx';

export class SettingsPage implements OnInit {
  code: string = null;

  constructor(
    private socialSharing: SocialSharing
  ) {}

  ngOnInit() {}

  shareCode(code) {
    this.socialSharing.canShareViaEmail().then(() => {
      // this.socialSharing
      //   .share(`Here is your code: ${code}`)
      //   .then(() => {
      //     log.debug('code has been shared?');
      //   });
    });
  }

}

Here is my package.json
{
  "dependencies": {
    "@angular/common": "^8.2.14",
    "@angular/core": "^8.2.14",
    "@angular/forms": "^8.2.14",
    "@angular/http": "^7.2.16",
    "@angular/platform-browser": "^8.2.14",
    "@angular/platform-browser-dynamic": "^8.2.14",
    "@angular/pwa": "^0.803.25",
    "@angular/router": "^8.2.14",
    "@angular/service-worker": "^8.2.14",
    "@biesbjerg/ngx-translate-extract-marker": "^1.0.0",
    "@fullcalendar/core": "^4.4.0",
    "@fullcalendar/daygrid": "^4.4.0",
    "@fullcalendar/interaction": "^4.4.0",
    "@fullcalendar/resource-common": "^4.4.0",
    "@fullcalendar/timegrid": "^4.4.0",
    "@ionic-native/core": "^5.22.0",
    "@ionic-native/in-app-browser": "^5.22.0",
    "@ionic-native/social-sharing": "^5.22.0",
    "@ionic-native/splash-screen": "^5.22.0",
    "@ionic-native/status-bar": "^5.22.0",
    "@ionic/angular": "^4.11.10",
    "@ionic/pro": "2.0.4",
    "@ionic/storage": "^2.2.0",
    "@ngx-translate/core": "^12.1.2",
    "@sentry/browser": "^4.6.6",
    "angular2-counto": "^1.2.5",
    "angularfire2": "^5.4.2",
    "cordova": "^9.0.0",
    "cordova-android": "^8.1.0",
    "cordova-plugin-browsertab": "0.2.0",
    "cordova-plugin-compat": "1.2.0",
    "cordova-plugin-device": "^2.0.3",
    "cordova-plugin-inappbrowser": "3.1.0",
    "cordova-plugin-ionic-keyboard": "^2.2.0",
    "cordova-plugin-ionic-webview": "^3.1.2",
    "cordova-plugin-splashscreen": "^5.0.3",
    "cordova-plugin-statusbar": "^2.4.3",
    "cordova-plugin-whitelist": "^1.3.4",
    "cordova-plugin-x-socialsharing": "^5.4.0",
    "cordova-universal-links-plugin": "^1.2.1",
    "cordova-universal-links-plugin-fix": "1.2.1",
    "core-js": "^2.6.10",
    "es6-promise-plugin": "^4.2.2",
    "firebase": "^5.11.1",
    "ionic": "^5.4.16",
    "jam-icons": "^2.0.0",
    "lodash": "^4.17.15",
    "messageformat": "^2.3.0",
    "moment": "^2.24.0",
    "ngx-toastr": "^9.1.2",
    "ngx-translate-messageformat-compiler": "^4.6.0",
    "ngx-ui-loader": "^7.2.2",
    "rxjs": "^6.5.4",
    "uuid": "^3.4.0",
    "web": "0.0.2",
    "zone.js": "~0.9.1"
  },
  "devDependencies": {
    "@angular-devkit/architect": "^0.803.25",
    "@angular-devkit/build-angular": "^0.803.25",
    "@angular-devkit/core": "^8.3.25",
    "@angular-devkit/schematics": "^8.3.25",
    "@angular/cli": "^8.3.25",
    "@angular/compiler": "^8.2.14",
    "@angular/compiler-cli": "^8.2.14",
    "@angular/language-service": "^8.2.14",
    "@biesbjerg/ngx-translate-extract": "^4.2.0",
    "@ionic/angular-toolkit": "^2.2.0",
    "@ionic/app-scripts": "^3.2.4",
    "@types/jasmine": "~2.8.8",
    "@types/jasminewd2": "^2.0.8",
    "@types/moment": "^2.13.0",
    "@types/node": "^10.17.17",
    "codelyzer": "~4.5.0",
    "cypress": "^3.8.3",
    "jasmine-core": "~2.99.1",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~3.1.4",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "^2.1.1",
    "karma-jasmine": "~1.1.2",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "^5.4.3",
    "ts-node": "^8.6.2",
    "tslint": "~5.12.0",
    "typescript": "3.5.3"
  },
  "description": "An Ionic project",
  "cordova": {
    "plugins": {
      "cordova-plugin-whitelist": {},
      "cordova-plugin-statusbar": {},
      "cordova-plugin-device": {},
      "cordova-plugin-splashscreen": {},
      "cordova-plugin-ionic-webview": {
        "ANDROID_SUPPORT_ANNOTATIONS_VERSION": "27.+"
      },
      "cordova-plugin-ionic-keyboard": {},
      "cordova-universal-links-plugin": {},
      "cordova-plugin-browsertab": {},
      "cordova-plugin-inappbrowser": {},
      "cordova-plugin-x-socialsharing": {
        "ANDROID_SUPPORT_V4_VERSION": "24.1.1+"
      }
    },
    "platforms": [
      "android"
    ]
  }
}

I've been trying different for several hours but I just don't know what I'm missing. Is there a special module to include or something?

A: Add Social Sharing to app.module.ts under providers.
import { SocialSharing } from '@ionic-native/social-sharing/ngx';

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [],
  providers: [
    ...
    SocialSharing,
    ...
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

A: VERY IMPORTANT! Update for an issue in Android resolved by me ie: @dipesious
You will get an array of different packages as a .catch(error)
This means you did not add QUERY_ALL_PACKAGES permission to your manifest. Add this to your Android manifest file:

congratulations BUG RESOLVED...


text:
Q: Transition from nested job to "main job" I have 2 job xmls
1.Main_job.xml
<batch:job id="main_job">
      <batch:step id="dummyTask1">
        <batch:tasklet ref="dummyTask" />
        <batch:next on="FORWARD" to="dummyTask2"/>
      </batch:step>
      <batch:step id="dummyTask2">
        <batch:job ref="nested_job" />  <!--Forking a nested job -->
        <batch:next on="BACKWARD" to="dummyTask1"/>
        <batch:next on="FORWARD" to="dummyTask3"/>
      </batch:step>
      <batch:step id="dummyTask3">
        <batch:tasklet ref="dummyTask" />
        <batch:next on="BACKWARD" to="dummyTask2"/>
        <batch:next on="FORWARD" to="endTask"/>
      </batch:step>
      <batch:step id="endTask">
        <batch:tasklet ref="endTask" />
      </batch:step>
</batch:job>

2.nested_job.xml
<batch:job id="nested_job">
      <batch:step id="dummyTask10">
        <batch:tasklet ref="dummyTask" />
        <batch:next on="FORWARD" to="dummyTask11"/>
      </batch:step>
      <batch:step id="dummyTask11">
        <batch:tasklet ref="dummyTask" />
        <batch:next on="BACKWARD" to="dummyTask10"/>
        <batch:next on="FORWARD" to="dummyTask12"/>
      </batch:step>
      <batch:step id="dummyTask12">
        <batch:tasklet ref="dummyTask" />
        <batch:next on="BACKWARD" to="dummyTask11"/>
        <batch:next on="FORWARD" to="endTask"/>
      </batch:step>
      <batch:step id="endTask">
        <batch:tasklet ref="endTask" />
      </batch:step>
</batch:job>

You can see that, all the steps have 2 paths.

*

*FORWARD

*BACKWARD

And these paths gets chosen depending on some dynamic boolean condition. Let us say, first, all the Exit codes for the step gets evaluated to FORWARD. So these are the sequence of steps, which gets executed
1. dummyTask1
2. dummyTask2
 [Nested_job] 3.dummyTask10
 [Nested_job] 4.dummyTask11
 [Nested_job] 5.dummyTask12

Let us say when the execution point is on dummyTask12, the Exit codes starts to get evaluated to BACKWARD. So following are the step executions for the same
[Nested_job] 5.dummyTask12
[Nested_job] 4.dummyTask11
[Nested_job] 5.dummyTask10

Now for dummyTask10, when the exit code comes as BACKWARD, SpringBatch throws error saying that flow doesn't exist, which is true (dummyTask10 doesn't have the flow defined for code BACKWARDS). What I want to achieve is, incase of BACKWARD, the flow should go back to main_job (or any Main job which has triggered this nested job (dynamically))
Is this possible? Is it possible to have a flow definition like this, which will take the execution point to the main job, which forked this nested job?
<batch:next on="BACKWARD" to="#{mainJob}"/> <!-- Or something -->

[I know this is a little more to ask for, But I am sure SpringBatch experts will find a way to achieve this]
Please let me know if you need more clarity.
EDIT:
From a nested job (nested_job), can I write a flow like below within a step, which will make transition to main job?
<batch:next on="BACKWARD" to="main_job.dummyTask1"/>

A: The way I'd approach this is as follows:

*

*Create a JobExecutionListener for the nested_job that sets the job's ExitStatus to be either 'BACKWARD' or 'FORWARD' at the end of the job.

*Create a StepExecutionListener to get the ExitStatus from the nested_job and return it as the main_job.dummyTask2's ExitStatus.

The above flow would allow the results of the nested job to indicate where the parent job should go.
You can read more about the StepExecutionListener in the documentation here: http://docs.spring.io/spring-batch/apidocs/org/springframework/batch/core/StepExecutionListener.html
You can read more about the JobExecutionListener in the documentation here: http://docs.spring.io/spring-batch/apidocs/org/springframework/batch/core/JobExecutionListener.html


text:
Q: Intuitively Finding Rank of a Matrix Let M be a square matrix, where $M[i,j] = (i-j)^2$.
I am told to find its rank.
The solution says that it is easy to see that the Columns of M are spanned by $\{ [1, 1, 1, 1,\dots, 1]^T , [1, 2,\dots, n]^T, [1, 2^2,\dots, n^2]^T \}$ .`
So, $rank(M) = 3$.
Well Rank = max. no of linearly independent columns. Why is the first column of $[1, 1,\dots, 1]$ required?

A: A random column of $M$ looks like $(i-j)^2$, where $j$ is fixed. Note that $(i-j)^2 = i^2 + j^2 - 2ij$.
We want to express $C_j$, the $j$th column of $M$, as the linear combination of $ A= [1,...,1]^T ,$ $ B = [1,...,n]^T $ and $D = [1,4,...,n^2]^T$. From the above relation of $(i,j)$, we have that $C_j = D -2jB + j^2A$. This is because $A_i = 1, B_i = i,D_i = i^2$, so we see that $C_{ij} = i^2 - 2ij + j^2$, which is true.
Hence, the rank of such a matrix must be $3$.


text:
Q: 70s movie where implants would make people peaceful This is a movie I saw as a child, toward the end of the 70s.
It had a similar vibe to Invasion of the Body Snatchers.
The story is about some guy that invents some implant that looks like a small metal tube. If I remember correctly, it was inserted on the side of the head, by the temple. The recipients of the implants would become very civil and peaceful people. He becomes convinced that this was the way to be and soon more people have the implant. But then people with the implant start to force others to have the implant, etc.
The main guy is afflicted with some disease that makes him age quickly. At the end, the main characters are with him in a building and can see the plaza below where one of their non-implanted friend goes (to make some point I forget about) and the implant guys all converge to him to convert him.
The rest of the protagonists know that the only safe place is in the tower, with the guy that started everything and has now passed of old age due to his condition.
I don't remember the rest of the movie, but I would really like to find what it was.

A: It's not a movie but a 1978 French mini-series titled Le Mutant, although I guess it could have been edited into a movie for foreign broadcast.
I previously identified it for:

*

*70's sci-fi dystopian mini-series: conspiracy to insert chips in brains to decrease violence

*70s TV miniseries: antagonist gets followers to his pacifist ideology through mind control devices
The forum I linked to (though the link is now dead) had these relevant recollections (translated):

The story follows a reporter investigating people behaving weirdly. She meets an odd guy who will only eat tiny green cubes of an unknown food. And he takes control of people by putting a weird thing in their necks. At the end, he tells the journalist he enslaved the whole world through a TV recording, because he died prematurely, and she ends up being the only "normal" person, watching the mind-controlled people on the screens... [...]
A fascinating, horrifying sci-fi series where an organization attempts to uncover who is Saül Masson, son of the rich Professor Masson. A strange blond teenager who only eats an equally strange green cube, all while from the top of his tower, an old man (whom we will only see the scrawny hand of, laying on his armchair) spends his time watching TV screens, seemingly monitoring everything...

All six episodes are on YouTube (in French, though); the sixth episode has the following "reveal" line at 48'58:

Professor Masson: His cells were ageing ten times faster than anyone else's. And I couldn't do anything about it. Over time, the process sped up. Look at him. He's ten years old. He's only ten.

as well as the "implant guys converging to the main character" bit you remember, which is the very end of the series:


text:
Q: How to determine if an irrational expression is a perfect square? Let $a,c\in\Bbb R$ and $b,d \in \Bbb N$. Is there a way to determine if
$$a\sqrt b+c\sqrt d$$
can be written as
$$(e+f)^2,$$
with $e,f\in\Bbb R$? If so, is there a way to find what $e$ and $f$, given $a, b,c, $ and $d$?
For example, in my math textbook, it says that $$32-16\sqrt 3=(2\sqrt 6-2\sqrt 2)^2,$$ but they didn't explain how they got there. If someone can explain, that would be great. Thanks!

A: The question is, what form are $e$ and $f$ to take? Otherwise, the problem is trivially solved since we can write any positive real number $r$ as $(\sqrt r)^2=(1+s)^2$ for some suitable $s,$ for example.
If we take a cue from the example given in your text, then you probably want $e,\,f$ to be the square roots of rationals, so that the question reduces to finding out when a binomial quadratic surd is the square root of another. That is, we want to find conditions on rational $p,\,q$ such that $$\sqrt{\sqrt p\pm\sqrt q}=\sqrt m\pm\sqrt n,$$ for some rational $m,\,n,$ which is standard fare. Square both sides to obtain $$\sqrt p\pm\sqrt q=m+n\pm2\sqrt{mn}.$$ Then we must have one of $\sqrt p$ or $\sqrt q$ to be rational, clearly, and this must be equal to $m+n.$ Secondly we must have $\pm2\sqrt{mn}$ equal to the other summand on LHS. You may examine these conditions further to deduce finer restraints.

A: First, $x\sqrt y=\sqrt{x^2y}$ so we can simplify general case to $(\sqrt{a}+\sqrt{b})^2=c+2d$. Now we can obtain two equations to find $a$ and $b$: $a+b=c$  and $ab=d$. This system is easy to solve using substitution $a=c-b$ which leads to a quadratic equation $(c-b)b=d$. The system may or may not have a solution.

A: Let me show a method for finding some such roots, which should apply to your example.  I'll instead apply the method to find $\sqrt{3+\sqrt{5}}$.
So, suppose $x = \sqrt{3 + \sqrt{5}}$.  Then $x^2 = 3 + \sqrt{5}$; $x^2 - 3 = \sqrt{5}$; and so $(x^2 - 3)^2 = 5$.  Expanding, we get:
$$x^4 - 6x^2 + 4 = 0.$$
Now, let us observe that $(x^2 + 2)^2 = x^4 + 4x^2 + 4$ which is close to matching the left hand side.  So, using the difference of squares formula, this is equivalent to $$(x^2 + 2)^2 - 10x^2 = (x^2 + 2)^2 - (x\sqrt{10})^2 = (x^2 + x\sqrt{10} + 2) (x^2 - x\sqrt{10} - 2) = 0.$$
However, by the quadratic formula, the roots of $x^2 + x \sqrt{10} + 2 = 0$ are $x = \frac{-\sqrt{10} \pm \sqrt{2}}{2}$, and the roots of $x^2 - x\sqrt{10} + 2 = 0$ are $x = \frac{\sqrt{10} \pm \sqrt{2}}{2}$.  Thus, overall we have $x = \frac{\pm\sqrt{10} \pm\sqrt{2}}{2}$.  It only remains to check which of these expressions actually is positive, and also gives $3 + \sqrt{5}$ when squared.

A: Well, in the reals there no point in talking about "perfect" squares as for any $x \ge 0$ then will be a $y$ so that $y^2 = x$ and $y = \sqrt x$.
So if you want $(e+f)^2 = a\sqrt{b}+ c\sqrt {d}>0$ then just let $y= \sqrt {a\sqrt b + c\sqrt d}$ and let $e= $ anything and $f= y-e$.  That's it.
As to how the book got $32-16\sqrt 3=(2\sqrt 6-2\sqrt 2)^2$ that is very specific to those integers.  (I'm more curious as to why rather than how) but:
Going from $2\sqrt 6 - 2\sqrt 2$ to noting that $(2\sqrt 6 - 2\sqrt 2)^2 = (2\sqrt 6)^2 - 2(2\sqrt 62\sqrt 2) + (2\sqrt 2)^2 = 4*6 - 8\sqrt {12} + 4*2=32 - 4\sqrt {4*3} = 32 - 16\sqrt 3$ is straightforward.
As for going from $32-16\sqrt 3$... well:
$\sqrt{32 - 16\sqrt 3}= 4(\sqrt {2 -\sqrt 3})$
.... so I guess the question is... how do you go from $\sqrt{a \pm \sqrt b}$ to $\sqrt x \pm \sqrt y$.
Okay.... if $\sqrt x \pm \sqrt y = \sqrt{2-\sqrt 3}$ then
$x + y \pm2\sqrt{xy}=x+y\pm \sqrt{4xy}= 2- \sqrt 3$.
So we need $x+y= 2$ and $4xy= 3$ or $xy = \frac 34$.  And as we are subtracting we need $x > y$.
If we assume rational values so that $x =\frac ab$ and $y=\frac cd$ and so $\frac{ad+ cb}{bd}  = 2$ and $\frac {ac}{bd}=\frac 34$ and as we need.
Trial and error but if $b=d =2$ then we need $ac = 3$ and $2a + 2c= 8$ or $a+c = 4$ and $a > c$.  so $a =3$ and $c = 1$ and
$\sqrt{2 -\sqrt 3} = \sqrt {\frac 32} - \sqrt{\frac 12}$.
$\sqrt{32-16\sqrt 3} = 4(\sqrt {\frac 32} - \sqrt{\frac 12})=$
$2(\sqrt {\frac {4*3}2} - \sqrt{\frac {4}2})= 2(\sqrt 3- \sqrt {2})=$
$2\sqrt 6 - 2\sqrt 2$


text:
Q: How does a constructor create and initialize member variables? Consider the following class with member initializer list:
class A {
public:
    A() : a {b} {
       // do something
    }
private:
    int a {1};
    int b {2};
};

The compiler issues a warning that b is used uninitialized in the member initalizer list. This would mean, the member b has been already created but not initialized yet?
Thus, can we assume the following order of execution?

*

*call constructor A()

*int a; (create memory for a)

*int b; (create memory for b)

*a = b; (compiler warning)

*b = 2; (assign default 2 to b)

*execute constructor's block

This would mean, we actually do not initialize but assign values in step 4 and 5?
EDIT:
If so, what is the advantage of an initializer list, when assignments can also be done in the block after the members have been created prior entering the block?

A: The sequence you describe is not completely correct. The sequence goes basically as follows:

*

*The memory for the object is allocated; (e.g. using operator new) Note that the memory is not allocated separately. The memory for the object is continuous, possibly with padding in between a and b.

*Initializations of members are done where initializers are provided in the initializer list of the constructor or directly at the member declaration. in this case a is declared first then b which is why b has not been initialized at the time you try to read it to initialize a.

*The constructor body is executed.

Note that the fields are initialized, not assigned which in case of ints doesn't make a difference, but if the member types would provide assignment operators and constructors there would be a difference between the 2; if you use the initializer list or initialize the member variable when declaring it the constructor is always used.


text:
Q: Jmeter close connection before my test finish I use jmeter HTTP Sampler to test a sequence of HTTP requests and choosed "Use KeepAlive". But a few threads Jmeter closed connection with TCP FIN before all
requests send out.

As the picture shown, 172.19.0.101 is Jmeter,172.19.0.111 is the server. The rest of requests can be only send in a new connection and they are out of session.

A: It can be of two reasons:
First reason - timeout
whether timeout is reached (default value is 60 seconds, and configurable. If not configured, it uses the connectionTimeout parameter value in tomcat server).

the default connection timeout of Apache httpd 1.3 and 2.0 is as
  little as 15 seconds and just 5 seconds for Apache httpd 2.2 and
  above

I observed that the request got the response after 10 seconds (15 -> 29 seconds) before sending FIN signal to terminate the connection.
References:

*

*https://tools.ietf.org/id/draft-thomson-hybi-http-timeout-01.html#p-timeout

*https://en.wikipedia.org/wiki/HTTP_persistent_connection

*https://tomcat.apache.org/tomcat-7.0-doc/config/http.html
Second reason -  'max' Parameter
May be it reached the number of requests that can be sent on a single Persistent Connetion.

*

*https://tools.ietf.org/id/draft-thomson-hybi-http-timeout-01.html#p-max
Set Implementation in HTTP Samplers to HTTPClient4 and try.
From JMeter HTTP Sampler documentation.

JMeter sets the Connection: keep-alive header. This does not work properly with the default HTTP implementation, as connection re-use is not under user-control. It does work with the Apache HttpComponents HttpClient implementations.

A: Find the jmeter.properties file in jmeter5.4.1, which describes the parameters during iteration:
# Reset HTTP State when starting a new Thread Group iteration which means:
# true means next iteration is associated to a new user
# false means next iteration is associated to same user
# true involves:
# - Closing opened connection
# - resetting SSL State
#httpclient.reset_state_on_thread_group_iteration=true

set
httpclient.reset_state_on_thread_group_iteration=false


text:
Q: hive data gets reset when app is restarted I have stored data in Hive box but whenever i restart the app or kills the app during offline mode i.e when internet conmnection is not there, Data gets resets & shows null error.
  await Hive.initFlutter();
  Hive.registerAdapter<ProgressList>(ProgressListAdapter());
  Hive.registerAdapter<VideoList>(VideoListAdapter());
  Hive.registerAdapter<DashBoard>(DashBoardAdapter());
  Hive.registerAdapter<CourseDetails>(CourseDetailsAdapter());
  Hive.registerAdapter<AnnouncementsListData>(AnnouncementsListDataAdapter());
  Hive.registerAdapter<VideoAssignments>(VideoAssignmentsAdapter());
  Hive.registerAdapter<LessonDetail>(LessonDetailAdapter());
  Hive.registerAdapter<CourseQuestions>(CourseQuestionsAdapter());
  await Hive.openBox<ProgressList>("box");
  await Hive.openBox<VideoList>("video_box");
  await Hive.openBox<DashBoard>("dashboard_box");
  await Hive.openBox<CourseDetails>("course_box");
  await Hive.openBox<AnnouncementsListData>("announcement_box");
  await Hive.openBox<VideoAssignments>("vfs_feedback_box");
  await Hive.openBox<LessonDetail>("lesson_box");
  await Hive.openBox<CourseQuestions>("questions_box");
  await Hive.openBox("video_record_box");

A: If you're facing this in debug mode, then you probably don't notice the difference between debugging an app and using it in release mode.
Your app may be running fine, if you debug your app on an Android emulator as an example, make sure that whenever you close the emulator, and you want to open it again, make sure that the emulator doesn't clear all phone data whenever you open it again, so it looks like the Hive didn't save your data, but actually the emulator set that it will clean all phone data whenever it's launched.
How this is related to Hive:
The Hive package is a key-value database, which saves its data inside files inside your device, so clearing all phone data will normally clear those files.
You need to try your app in a real device for making sure that your data is saved, and I would recommend to test if first in a release mode version.


text:
Q: The order of TCP message? I'm developing C++ application server and client which use TCP. I have three messages on server: A, B and C. They are sent sequentially: A -> B -> C. And clients responses acknowledge messages:rA, rB, rC.
Do client receive A, B and C in order A->B-C? Do server receive rA->rB->rC?

A: TCP guarantees that the order the packets are received (on a single connection) is the same as the order they were sent. No such guarantee if you've got multiple TCP connections, though - TCP preserves ordering only for the packets within a given TCP connection.
See the Wikipedia article on TCP for more overview.

One of the functions of TCP is to prevent the out-of-order delivery of data, either by reassembling packets into order or forcing retries of out-of-order packets.


text:
Q: Transformation Pentaho Kettle getting Stuck I was created my transformation using pentaho data integration to read data from Cassandra then copy data to other database. Then I created bat script to call my transformation using kitchen and the script was called by windows scheduler every 5 minutes. The script was fine and running smoothly, but after few hours(7 hours) got problem, the transformation stuck and couldn't finish the job. I was checked the log, the last step was "Dispatching started for transformation". The transformation can't start again until I killed the OSGI Service listened port.
Is it some problem with PDI or because of cassandra database it self? How to resolve my problem?


text:
Q: Convert jfloatarray to float* I've this function in JNI, a wrapper that call WebRtcNs_Process. WebRtcNs_Process receive float*, so how i can convert jfloatArray to float* ?
 JNIEXPORT jint JNICALL
 nativeNsProcess
 (JNIEnv *env, jclass jclazz, jint nsHandler, const jfloatArray input_frame, jfloatArray out) {

//get handle
NsHandle* NS_instance = (NsHandle*) nsHandler;

if (NS_instance == NULL)
    return -1;
int ret;

if (input_frame == NULL || out == NULL)
    return -1;

//create native floats from java floats
jfloat* native_input_frame = (*env)->GetFloatArrayElements(env, input_frame,
        NULL);

jfloat* native_output_frame = (*env)->GetFloatArrayElements(env, out, NULL);

//noise suppression
ret = WebRtcNs_Process(NS_instance, native_input_frame, NULL,
        native_output_frame, NULL);

//cleanup and return
(*env)->ReleaseFloatArrayElements(env, input_frame, native_input_frame, 0);

(*env)->ReleaseFloatArrayElements(env, out, native_output_frame, 0);

return ret;

}


text:
Q: Ranking Elements of multiple Lists by their count in Python I want to rank multiple lists according to their elements how often they appear in each list. Example:
list1 = 1,2,3,4
list2 = 4,5,6,7
list3 = 4,1,8,9
result = 4,1,2,3,4,5,6,7,8 (4 is counted three times, 1 two times and the rest once)
I've tried the following but i need something more intelligent and something i can do with any ammount of lists.

 l = []
 l.append([ 1, 2, 3, 4, 5])
 l.append([ 1, 9, 3, 4, 5])
 l.append([ 1, 10, 8, 4, 5])
 l.append([ 1, 12, 13, 7, 5])
 l.append([ 1, 14, 13, 13, 6])

 x1 = set(l[0]) & set(l[1]) & set(l[2]) & set(l[3])
 x2 = set(l[0]) & set(l[1]) & set(l[2]) & set(l[4])
 x3 = set(l[0]) & set(l[1]) & set(l[3]) & set(l[4])
 x4 = set(l[0]) & set(l[2]) & set(l[3]) & set(l[4])
 x5 = set(l[1]) & set(l[2]) & set(l[3]) & set(l[4])
 set1 = set(x1) | set(x2) | set(x3) | set(x4) | set(x5)

 a1 = list(set(l[0]) & set(l[1]) & set(l[2]) & set(l[3]) & set(l[4]))
 a2 = getDifference(list(set1),a1)
 print a1
 print a2

Now here is the problem... i can do it again and again with a3,a4 and a5 but its too complex then, i need a function for this... But i don't know how... my math got stuck ;)
SOLVED: thanks alot for the discussion. As a newbee i like this system somehow: fast+informative. You helped me all out! Ty

A: import collections

data = [
  [1, 2, 3, 4, 5],
  [1, 9, 3, 4, 5],
  [1, 10, 8, 4, 5],
  [1, 12, 13, 7, 5],
  [1, 14, 13, 13, 6],
]

def sorted_by_count(lists):
  counts = collections.defaultdict(int)
  for L in lists:
    for n in L:
      counts[n] += 1

  return [num for num, count in
          sorted(counts.items(),
                 key=lambda k_v: (k_v[1], k_v[0]),
                 reverse=True)]

print sorted_by_count(data)

Now let's generalize it (to take any iterable, loosen hashable requirement), allow key and reverse parameters (to match sorted), and rename to freq_sorted:
def freq_sorted(iterable, key=None, reverse=False, include_freq=False):
  """Return a list of items from iterable sorted by frequency.

  If include_freq, (item, freq) is returned instead of item.

  key(item) must be hashable, but items need not be.

  *Higher* frequencies are returned first.  Within the same frequency group,
  items are ordered according to key(item).
  """
  if key is None:
    key = lambda x: x

  key_counts = collections.defaultdict(int)
  items = {}
  for n in iterable:
    k = key(n)
    key_counts[k] += 1
    items.setdefault(k, n)

  if include_freq:
    def get_item(k, c):
      return items[k], c
  else:
    def get_item(k, c):
      return items[k]

  return [get_item(k, c) for k, c in
          sorted(key_counts.items(),
                 key=lambda kc: (-kc[1], kc[0]),
                 reverse=reverse)]

Example:
>>> import itertools
>>> print freq_sorted(itertools.chain.from_iterable(data))
[1, 5, 4, 13, 3, 2, 6, 7, 8, 9, 10, 12, 14]
>>> print freq_sorted(itertools.chain.from_iterable(data), include_freq=True)
# (slightly reformatted)
[(1, 5),
 (5, 4),
 (4, 3), (13, 3),
 (3, 2),
 (2, 1), (6, 1), (7, 1), (8, 1), (9, 1), (10, 1), (12, 1), (14, 1)]

A: Combining a couple of ideas already posted:
from itertools import chain
from collections import defaultdict

def frequency(*lists):
    counter = defaultdict(int)
    for x in chain(*lists):
        counter[x] += 1
    return [key for (key, value) in
        sorted(counter.items(), key=lambda kv: (kv[1], kv[0]), reverse=True)]

Notes:

*

*In Python 2.7, you can use Counter instead of defaultdict(int).

*This version takes any number of lists as its argument; the leading asterisk means they'll all be packed into a tuple.  If you want to pass in a single list containing all of your lists, omit that leading asterisk.

*This breaks if your lists contain an unhashable type.

A: def items_ordered_by_frequency(*lists):

    # get a flat list with all the values
    biglist = []
    for x in lists:
        biglist += x

    # sort it in reverse order by frequency
    return sorted(set(biglist),
                  key=lambda x: biglist.count(x),
                  reverse=True)

A: Try this one:
def rank(*lists):
    d = dict()
    for lst in lists:
        for e in lst:
            if e in d: d[e] += 1
            else: d[e] = 1
    return [j[1] for j in sorted([(d[i],i) for i in d], reverse=True)]

Usage example:
a = [1,2,3,4]
b = [4,5,6,7]
c = [4,1,8,9]

print rank(a,b,c)

You can use any number of lists as input

A: You can count the number of appearances of each element (a histogram), then sort by it:
def histogram(enumerable):
  result = {}
  for x in enumerable:
    result.setdefault(x, 0)
    result[x] += 1
  return result

lists = [ [1,2,3,4], [4,5,6,7], ... ]

from itertools import chain

h = histogram(chain(*lists))
ranked = sorted(set(chain(*lists)), key = lambda x : h[x], reverse = True)

A: Try this code:
def elementFreq(myList):
    #myList is the list of lists
    from collections import Counter
    tmp = []
    for i in myList: tmp += i
    return(Counter(tmp))

Note: Your lists should be hashable type


text:
Q: How to get the smallest (earliest) possible Date value I am trying to get the smallest possible value for date (ie, the earliest date). If I were using Java, I would do something like this:
new Date(Long.MIN_VALUE)

source
I could do something like this, but that seems like a lot of extra work. I could also just hard code the value like this: datetime.newInstance(-99999999999L);, because I think that is the smallest Long value possible... But that is not the nicest thing.
Any better ideas?

A: I question the validity of what you're doing, since I've never seen this to be necessary, but since you asked, from the docs:

The earliest valid date is 1700-01-01T00:00:00Z GMT, or just after midnight on January 1, 1700. The latest valid date is 4000-12-31T00:00:00Z GMT, or just after midnight on December 31, 4000.

So therefore to construct the earliest possible date, you'd do something like
Date myDate = date.newinstance(1700, 1, 1);

(Untested but it should work. Also, probably irrelevant but your Java example is constructing a very late date, not a very early date.)

A: you can pass a number / string / undefined when creating a date object. When passing a number as parameter, it means how many milliseconds since the very first date (1970-01-01 08:00:00). So if you pass 0 as the parameter you can get the smallest possible value for date.
new Date(0)


text:
Q: Appcompat Theme not applied on all Widgets I have extended the Material Theme and applied it in my activity.
In style.xml
  <style name="AppTheme" parent="Theme.AppCompat.NoActionBar">
        <item name="colorPrimary">@color/primary</item>
        <item name="colorPrimaryDark">@color/primary_dark</item>
        <item name="colorAccent">@color/accent</item>
        <item name="android:windowBackground">@color/bg</item>
    </style>`

and
in manifest
    <application
        android:allowBackup="true"
        android:theme="@style/AppTheme"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name" >
...</application>

I see Material design styling on Toolbar, Buttons but it is not applied on ImageButton, ToggleButton and Seekbar in Pre Lollipop devices. They show up in Holo Theme.
In my gradle file I am using :
compile 'com.android.support:appcompat-v7:22.1.1'

What should I do to apply a uniform style to all widgets??

A: According to this blog post, the following widgets are currently supported:

*

*AppCompatAutoCompleteTextView

*AppCompatButton

*AppCompatCheckBox

*AppCompatCheckedTextView

*AppCompatEditText

*AppCompatMultiAutoCompleteTextView

*AppCompatRadioButton

*AppCompatRatingBar

*AppCompatSpinner

*AppCompatTextView

For the ToggleButton, you can try to use SwitchCompat instead.


text:
Q: toggle sidebar once, switch between blocks and close iI need some help with this one.
HTML

        Discover

        ViewList

        Filters

        Share

Watchlist

Share

Facebook

Twitter

Pinterest

Google+

Filters

Categories

Artists

Styles

And my poorly written Jquery
$('.filters').toggle(
    function(){
        if($('.share-content').is(':visible'))
            {
            $('.share-content').hide();
            $('.filters-content').show();
            }
        else{
            $('.filters-content').css({'display': 'block'}, {queue:false});
            $('.sidebar').stop().animate({left:'255px'}, {duration: 300, queue:false});
            $('.content-with-list').children().stop().animate({'margin-left':'255px'}, {duration: 300, queue:false});
            }
    },
    function()
    {
            $('.sidebar').stop().animate({left:'0'}, {duration: 300, queue:false});
            $('.content-with-list').children().stop().animate({'margin-left':'0'}, {duration: 300, queue:false});
    });

    $('.share').toggle(
    function()
    {
        if($('.filters-content').is(':visible'))
            {
            $('.filters-content').hide();
            $('.share-content').show();
            }
        else{
            $('.share-content').css({'display': 'block'}, {queue:false});
            $('.sidebar').stop().animate({left:'255px'}, {duration: 300, queue:false});
            $('.content-with-list').children().stop().animate({'margin-left':'255px'}, {duration: 300, queue:false});
            }
    },
    function()
    {
        $('.sidebar').stop().animate({left:'0'}, {duration: 300, queue:false});
        $('.content-with-list').children().stop().animate({'margin-left':'0'}, {duration: 300, queue:false});
    });

So even though the code looks terrible it was working for two blocks but now I need to add third one and I'm stuck on this one.I would really like to know how can I make code with little repetitions and make my sidebar open only once shift between content and then close the sidebar if the same link was clicked.
Thank you for your patience in advance.

A: jsBin demo
$('.sidebar li').click(function() {
    var el = $('.sidebar-content > div').eq( $(this).index() );
    check = el.is(':visible') ? el.hide() : ($('.sidebar-content > div').hide()) (el.show());
});


text:
Q: transactional behavior in spring-kafka I read spring-kafka/kafka documentation back and forth, and still cannot find a way, how to do proper transactional behavior with error recovering. I believe this is not trivial question, so please read until end. I believe whole this question revolves around finding way how to reposition over failing record or how to ack in error handler. But mabye there are better ways, I don't know.
So records are flowing in, and some of them are invalid. What I would like to have as a minimal solution is(in which I will then fix sevaral problems you probably see as well):
1) we cannot afford the luxury of stopping the production in case of some trivial mishap, like one or few invalid records. Thus if there is invalid record in kafka topic, I would like to log it, or resend it to different queue, but then proceed with processing following records.
2) there are permanent and temporary failures. Permanent failure is record unable to deserialize, record failing data validation. In this case, I'd like to skip the invalid record, as discussed in 1). Temporary failure might be some specific exception or state, like for example database connection errors, network issues etc. In this case, we do not want to skip failing record, we want to retry, after some delay.
Subject of this question is ONLY implementing skip/don't skip behavior.
Lets say, that this is our starting point:
private Map<String, Object> createKafkaConsumerFactoryProperties(String bootstrapServers, String groupId, Class<?> valueDeserializerClass) {
Map<String, Object> props = new HashMap<>();
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, valueDeserializerClass);
props.put(ConsumerConfig.GROUP_ID_CONFIG, groupId);

return props;
}

@Bean(name="SomeFactory")
public ConcurrentKafkaListenerContainerFactory<String, String> kafkaListenerContainerFactory(
    @Value("${…}") String bootstrapServers,
    @Value("${…}") String groupId) {

ConcurrentKafkaListenerContainerFactory<String, String> factory =
        new ConcurrentKafkaListenerContainerFactory<>();

ConsumerFactory<String, String> consumerFactory = new DefaultKafkaConsumerFactory<>(
        createKafkaConsumerFactoryProperties(bootstrapServers, groupId, AvroDeserializer.class),
        new StringDeserializer(),
        new AvroDeserializer(SomeClass.class));

factory.setConsumerFactory(consumerFactory);
//        factory.setConcurrency(2);
//        factory.setBatchListener(true);
return factory;
}

and we have listener like:
@KafkaListener(topics = "${…}", containerFactory = "SomeFactory")
public void receive(@Valid List<SomeClass> messageList) {/*logic*/}

Now how this behave if I understand correctly:

*

*when listener gets message, ~when we reach inside of receive method, the kafka message will be already acked, and if receive method throw an exception, the next poll will return following record. Because ack happened, and we do not have error handler defined, thus logging error handler will kick in. This is not necessarily what we want. We can use SeekToCurrentErrorHandler to reprocess the message. Or one can specify TransactionManager, and if exception 'leaks' from listener, repositioning will also happen. If someone know performance comparison of these two approaches, please tell me.

*when message cannot be deserialized, deserializer will fail, message will not be acked and same record will be polled again. This is some sort of "poison packet" since kafka will spin on this message indefinitelly. We do have retry.backoff.ms to at least slow it down, but I can't see any max number retries or something. So the best thing we can do is to stop/pause container in this situation. Which is way to harsh. Btw. I'm new to kafka/spring-kafka, I did not see anywhere mention, how to manually reposition offset from outside of an application, meaning OK, listener is down, but now what? Another solution would be not to fail deserializer, and return something. But what?? KafkaNull, great, but then our listener will fail because SomeClass ClassCastException. We can send some artificial value of SomeClass, which is again horrible, because this is not a data what we actually get. Also this is architectonically incorrect.

*or we can use repositioning error handler, which would be great, well if we know how to do that. I need to seek to next record. But while documentation says, that ErrorHandler should communicate which record caused the failure, it seems that it fails to do so. So even in non-batch listener I have list of records(1 failed + bunch of unprocessed), and have no idea where set offset to.
So what is the solution to this madness?
Well the best I can come up with right now is pretty ugly: do not fail in deserializer (bad), do not accept specific type in listener (bad), filter out KafkaNulls manually (bad) and finally trigger bean validation manually (bad). Is there a better way? Thanks for examplantion, I'd be grateful for every hint or direction given how to achieve this.

A: See the documentation for the upcoming 2.2 release (due tomorrow).
The DefaultAfterRollbackProcessor (when using transactions) and SeekToCurrentErrorHandler (when not using transactions) can now recover (skip) records that keep failing, and will do so after 10 failures, by default. They can be configured to publish failed records to a dead-letter topic.
Also see the Error Handling Deserializer which catches deserialization problems and passes them to the container so they can be sent to the error handler.


text:
Q: Angular App not running because of localization I have an application which was working till a few days back. The application uses localization. Everything looked perfect. Suddenly it stopped working and started giving me this error.
Uncaught Error: It looks like your application or one of its dependencies is using i18n.
Angular 9 introduced a global `$localize()` function that needs to be loaded.
Please run `ng add @angular/localize` from the Angular CLI.
(For non-CLI projects, add `import '@angular/localize/init';` to your `polyfills.ts` file.
For server-side rendering applications add the import to your `main.server.ts` file.)
    at push../node_modules/@angular/core/fesm5/core.js._global.$localize (core.js:32666:1)
    at Module../node_modules/@ng-bootstrap/ng-bootstrap/fesm5/ng-bootstrap.js (ng-bootstrap.js:70:1)
    at __webpack_require__ (bootstrap:84:1)
    at Module../src/app/app.module.ts (app.component.ts:9:26)
    at __webpack_require__ (bootstrap:84:1)
    at Module../src/main.ts (main.ts:1:1)
    at __webpack_require__ (bootstrap:84:1)
    at Object.0 (main.ts:15:35)
    at __webpack_require__ (bootstrap:84:1)
    at checkDeferredModules (bootstrap:45:1)

I am not sure whether I upgraded the angular cli or not. But once I started getting this error, i uninstalled the angular cli and installed the latest version. But of no use.
Tried executing  ng add @angular/localize
Installing packages for tooling via npm.
An unhandled exception occurred: npm ERR! code ERESOLVE
npm ERR! ERESOLVE could not resolve
npm ERR!
npm ERR! While resolving: @ng-bootstrap/ng-bootstrap@7.0.0
npm ERR! Found: @angular/common@9.1.11
npm ERR! node_modules/@angular/common
npm ERR!   peer @angular/common@"9.1.11" from @angular/forms@9.1.11
npm ERR!   node_modules/@angular/forms
npm ERR!     @angular/forms@"^9.1.1" from the root project
npm ERR!   peer @angular/common@"9.1.11" from @angular/platform-browser@9.1.11
npm ERR!   node_modules/@angular/platform-browser
npm ERR!     peer @angular/platform-browser@"9.1.11" from @angular/forms@9.1.11
npm ERR!     node_modules/@angular/forms
npm ERR!       @angular/forms@"^9.1.1" from the root project
npm ERR!     peer @angular/platform-browser@"9.1.11" from @angular/platform-browser-dynamic@9.1.11
npm ERR!     node_modules/@angular/platform-browser-dynamic
npm ERR!       peer @angular/platform-browser-dynamic@"^9.0.6" from angular-datatables@9.0.2
npm ERR!       node_modules/angular-datatables
npm ERR!         angular-datatables@"^9.0.2" from the root project
npm ERR!       1 more (the root project)
npm ERR!     3 more (@angular/router, angular-datatables, the root project)
npm ERR!   9 more (@angular/platform-browser-dynamic, @angular/router, ...)
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer @angular/common@"^10.0.0" from @ng-bootstrap/ng-bootstrap@7.0.0
npm ERR! node_modules/@ng-bootstrap/ng-bootstrap
npm ERR!   @ng-bootstrap/ng-bootstrap@"^7.0.0" from the root project
npm ERR!
npm ERR! Conflicting peer dependency: @angular/common@10.2.5
npm ERR! node_modules/@angular/common
npm ERR!   peer @angular/common@"^10.0.0" from @ng-bootstrap/ng-bootstrap@7.0.0
npm ERR!   node_modules/@ng-bootstrap/ng-bootstrap
npm ERR!     @ng-bootstrap/ng-bootstrap@"^7.0.0" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See C:\Users\Shah Jahan\AppData\Local\npm-cache\eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Shah Jahan\AppData\Local\npm-cache\_logs\2022-04-30T07_47_17_303Z-debug-0.log
Package install failed, see above.
See "C:\Users\SHAHJA~1\AppData\Local\Temp\ng-fYNTDv\angular-errors.log" for further details.

The log file generated is as follows:
[error] Error: npm ERR! code ERESOLVE
npm ERR! ERESOLVE could not resolve
npm ERR!
npm ERR! While resolving: @ng-bootstrap/ng-bootstrap@7.0.0
npm ERR! Found: @angular/common@9.1.11
npm ERR! node_modules/@angular/common
npm ERR!   peer @angular/common@"9.1.11" from @angular/forms@9.1.11
npm ERR!   node_modules/@angular/forms
npm ERR!     @angular/forms@"^9.1.1" from the root project
npm ERR!   peer @angular/common@"9.1.11" from @angular/platform-browser@9.1.11
npm ERR!   node_modules/@angular/platform-browser
npm ERR!     peer @angular/platform-browser@"9.1.11" from @angular/forms@9.1.11
npm ERR!     node_modules/@angular/forms
npm ERR!       @angular/forms@"^9.1.1" from the root project
npm ERR!     peer @angular/platform-browser@"9.1.11" from @angular/platform-browser-dynamic@9.1.11
npm ERR!     node_modules/@angular/platform-browser-dynamic
npm ERR!       peer @angular/platform-browser-dynamic@"^9.0.6" from angular-datatables@9.0.2
npm ERR!       node_modules/angular-datatables
npm ERR!         angular-datatables@"^9.0.2" from the root project
npm ERR!       1 more (the root project)
npm ERR!     3 more (@angular/router, angular-datatables, the root project)
npm ERR!   9 more (@angular/platform-browser-dynamic, @angular/router, ...)
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer @angular/common@"^10.0.0" from @ng-bootstrap/ng-bootstrap@7.0.0
npm ERR! node_modules/@ng-bootstrap/ng-bootstrap
npm ERR!   @ng-bootstrap/ng-bootstrap@"^7.0.0" from the root project
npm ERR!
npm ERR! Conflicting peer dependency: @angular/common@10.2.5
npm ERR! node_modules/@angular/common
npm ERR!   peer @angular/common@"^10.0.0" from @ng-bootstrap/ng-bootstrap@7.0.0
npm ERR!   node_modules/@ng-bootstrap/ng-bootstrap
npm ERR!     @ng-bootstrap/ng-bootstrap@"^7.0.0" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See C:\Users\Shah Jahan\AppData\Local\npm-cache\eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Shah Jahan\AppData\Local\npm-cache\_logs\2022-04-30T07_47_17_303Z-debug-0.log
Package install failed, see above.
    at Object.installPackage (C:\Devs\Projects\LibMan\LibManWeb\node_modules\@angular\cli\tasks\install-package.js:39:15)
    at AddCommand.run (C:\Devs\Projects\LibMan\LibManWeb\node_modules\@angular\cli\commands\add-impl.js:148:31)
    at async AddCommand.validateAndRun (C:\Devs\Projects\LibMan\LibManWeb\node_modules\@angular\cli\models\command.js:134:28)
    at async Object.runCommand (C:\Devs\Projects\LibMan\LibManWeb\node_modules\@angular\cli\models\command-runner.js:201:24)
    at async default_1 (C:\Devs\Projects\LibMan\LibManWeb\node_modules\@angular\cli\lib\cli\index.js:62:31)

Can anyone help pls?

A: I suspect that it is trying to install the incorrect version of @angular/localize. It should be installing 9.1.11. Update your package.json to include that version and then run npm install. You may need to delete the node_modules folder first as it may have already installed the incorrect file dependencies.
Note that all @angular/xxx packages are versioned so that the first number matches the angular version you are running. i.e. @angular/localize : 9.1.11 we know it is for Angular 9.


text:
Q: Stubbing Carrierwave in RSpec to speed up tests I'm saving an object to database in RSpec. This object has a Carrierwave field with its presence validation. I'm using fixture_file_upload for that field in a factory and it's very slow. I would like to stub Carrierwave file handling completely, but all solutions seem outdated and I can't get them to work.
My model:
class Product < ActiveRecord::Base
  validates_presence_of   :image
  mount_uploader :image,  ProductMainImageUploader
end

My factory:
factory :product do
  name          { Faker::Product.product_name }
  slug          { name ? name.parameterize : nil }
  image         { 'sample_image.jpg' }
end

My spec:
describe Product do
  it "creates record" do
    ProductMainImageUploader.any_instance.stub(:store!)
    ProductMainImageUploader.any_instance.stub(:store_image!)
    product = create(:product)
  end
end

Results:
  1) Product creates record
     Failure/Error: product = create(:product, name: 'heyo')
     ActiveRecord::RecordInvalid:
       Validation failed: Image can't be blank
     # ./spec/models/product_spec.rb:26:in `block (2 levels) in <top (required)>'

The stubs have no effect at all. I'm using Ruby 2.1.0. What can I do to fix this?

A: Try stubbing image
before do
  Product.stub(:image).and_return(ProductMainImageUploader.new)
end


text:
Q: Functions to return a structure in c I have a fight game between 4 Magicians and 1 Demon in C.
Each of them have 3 attributes :

*

*NAME

*PV(Life points)

*PM(Magic points)

I had to create a structure for Magician and Demon so i wrote :
struct Magician{

      char name_magician[20];
      int pm;
      int pv;

};

struct Demon{

  char name_demon[20];
  int pv;
  int pm;

};

typedef struct Magician magician;

typedef struct Demon demon;

Now:
How can i create a function that create a Demon?
And a function to create a group of 4 Magicians ?
What i tried in main function basically the simple :
demon d1;
d1.name_demon="demonx123";
d1.pv=15;
d1.pm=20;

A: To make group of Magician, you can use array of Magician structure.
Something like...
> struct Magician m[4];

Use this statement in a function.
This will create you 4 members of Magician.Now you can initialize them as you are doing for demon.

A: Returning a single structure from a function is easy: You do it just like any other function returning a value:
demon create_demon(void)
{
    demon d;
    // Initialize the demon

    return d;
}

Returning an array of multiple structures is a little harder, but just like for returning a single structure is the same as returning any value, returning an array of structures is exactly the same as returning an array of any other value. This can be done either by allocating on the heap, and returning a pointer. Or by passing a pointer to the first element as an argument to the function.

A: This way you can easily create your demons.
 struct demon *createDemon(char *name, int pv, int pm){
     struct demon *tmp = malloc(sizeof(struct demon));

     if (tmp == NULL || sizeof(tmp->name) < strlen(name))
         return NULL;

     for (int i = 0; i < strlen(name); i++)
         tmp->name[i] = name[i];
     tmp->pm = pm;
     tmp->pv = pv;

     return tmp;
}

And in case you wonder, this way you can remove it again.
void removeDemon(struct demon *dtr){
    if (dtr != NULL){
        free(dtr);
    }
}

To make your structure a little less static you should however change
the way you initialize the name of your creature, like:
struct demon{
    char *name;
    int pv;
    int pm;
};

This way you can allocate the space you need for your creatures name dynamically like:
struct demon *createDemon(char *name, int pv, int pm){

    // Try to allocate demon structure. If fail return NULL
    struct demon *tmp = malloc(sizeof(struct demon));
    if (tmp == NULL)
        return NULL;

    // Try to allocate demon name. If fail, return NULL
    tmp->name = malloc(strlen(name));
    if (tmp->name == NULL) {
        free(tmp->name);
        return NULL;
    }

    // Set Variables and return structure
    tmp->name = name;
    tmp->pm = pm;
    tmp->pv = pv;

    return tmp;
}

And you need to renew your removal function as well to remove the allocated space created for the name like:
void removeDemon(struct demon *dtr){
    if (dtr != NULL){
        free(dtr->name);
        free(dtr);
    }
}

A:  struct Magician *m = malloc (sizeof(struct Magician)*NumOfMagitians);

And return the pointer


text:
Q: Fancy Box jquery - opening behind php overlay www.yorkshirephotographer.net/new
you can view all code
The gallery/portfolio page is working in standard mode - when you click a photo it opens correctly
When the website optimises for mobiles/tablets the gallery photo is shown behind the page block/php block - needs to be infront?
Thanks
Ben
ps - click 'portfolio' to see gallery pictures

A: This isn't to do with the Javascript, really: it's a CSS problem. Your #content area has a z-index of 10000 in your style-600.css; that's higher than the fancybox (z-index: 8010). Change that, and you should be OK.


text:
Q: Render data from JSON in react native im trying to render these JSON data but I cant access company at all.I cant figure out where is the problem? This is the JSON:
[
{
   "address": {
       "country": "Albania",
       "city": "Tirana",
       "street": "Sheshi Skenderbe"
   },
   "_id": "5fc96784e740aaa9af2139ae",
   "company": "Big market",
   "phone": "+35568123456"
}
]

This is my code:
const [data, setData] = useState([]);
  useEffect(() => {
    (async () => {
      try {
        const response = await axiosApiInstance.get(`/companies/list/1`);
        setData(response.data);
        console.log(response.data, "Data from Furnitoret");
      } catch (err) {
        Alert.alert("Mesazhi", err.response.data.message);
      }
    })();
  }, []);

and the render
 <FlatList
        keyExtractor={(item, i) => i.toString()}
        data={data}
        renderItem={({ item, i }) => (
          <Card
            title={data.company}
            onPress={() => navigation.navigate("Porosia")}
          />
        )}
      />

A: Within your renderItem prop of the flatlist, you giving the name item to each element in the data array, but then you are trying to use your data object which is the complete list, instead of the current item.
It should be
      <FlatList
        keyExtractor={(item, i) => item._id}
        data={data}
        renderItem={({ item, i }) => (
          <Card
            title={item.company} // <----------------- item not data
            onPress={() => navigation.navigate("Porosia")}
          />
        )}
      />

Also, as a side note you might want to use the company id as the key instead of the array index, as you might run into performance problems when updating this list later on
keyExtractor={(item, i) => item._id}

A: change data.company to item.company like
<Card
    title={item.company}
/>


text:
Q: Self-submiting form redirect I have a php from that includes the external process.php, which handles all my validation and sending the mail function and submits to it self by setting  action="<?php echo $_SERVER['PHP_SELF'] ?>"
Everything works great, it validates properly and mails the form to my email, but when I try to include the header("location: thanks.html") to redirect after submit, it doesn't redirect. Am I doing this incorrectly or is it an issue with self-submitting the form? I'm also using Jquery and Jquery Mobile. Any help is appreciated
Heres my php
<?php
if(($_SERVER['REQUEST_METHOD'] =='POST') && (!empty ($_POST['action']))):

if (isset ($_POST['myname'])){$myname=$_POST['myname'];}
if (isset ($_POST['myphone'])){$myphone=$_POST['myphone'];}
if (isset ($_POST['myemail'])){$myemail=$_POST['myemail'];}
if (isset ($_POST['job'])){$job=$_POST['job'];}
if (isset ($_POST['comments'])){
    $comments= filter_var($_POST['comments'], FILTER_SANITIZE_STRING);}

$formerrors = false;

      if($myname === '') :
      $err_myname = '
 Sorry, your name is rquired
';
      $formerrors=true;
      endif;

      if($myphone === ''):
      $err_myphone = '
 Sorry, your phone number is rquired
';
      $formerrors=true;
      endif;

      if($myemail === ''):
      $err_myemaile =  '
 Sorry, your email is rquired
';
      $formerrors=true;
      endif;

      if($job === ''):
      $err_job =  '
 Sorry, your business is rquired
';
      $formerrors=true;
      endif;

if (!($formerrors)) :
$to = "myemail@emial.com";
$subject = " Request from $myname --Show and Tell";

$message = "A new show and tell request from:\n
            $myname \n
            $myemail\n
            $myphone\n
            $job\n
            $comments\n";
$replyto = "From: $myemail";

if(mail($to, $subject, $message)):
    $msg ="Thanks for filling out our form";
    header('location: http://localhost/thanks.html');
    else:
    $msg = "There was a problem sending the message";
    endif; //mail data

endif; //check errors

endif; //form submitted

?>

And my html

<?php if (isset($msg)) { echo '

', $msg, '

';}?>
<form id="form" action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">

    Your Name*:

    <input type="text" name="myname" id="myname" placeholder="John Smith" value="<?php if (isset($myname)) {echo $myname;}  ?>" required/>
    <?php  if (isset($err_myname)) {echo $err_myname;} ?>

    Email*:

    <input type="email" name="myemail" id="myemail" placeholder="jsmith@email.com" value="<?php if (isset($myemail)) {echo $myemail;}  ?>"  />
    <?php  if (isset($err_myemail)) {echo $err_myemail;} ?>
    <?php  if (isset($err_wrong)) {echo $err_wrong;} ?>

    Phone number*:

    <input onblur="formatPhone(this);" type="tel" name="myphone" id="myphone" placeholder="1234567890"   value="<?php if (isset($myphone)) {echo $myphone;}  ?>"  required/>
    <?php  if (isset($err_myphone)) {echo $err_myphone;} ?>

    Name of Business*:

    <input  type="text" name="job" id="job" placeholder="Where do you work?"   value="<?php if (isset($job)) {echo $job;}  ?>"  required/>
    <?php  if (isset($err_job)) {echo $err_job;} ?>

      Comments:

      <textarea cols="40" rows="8" name="comments" id="comments" placeholder="Questions or Comments?">
      <?php if (isset($comments)) {echo $comments;}?>
      </textarea>

<input name="Reset" type="reset" value="Reset" data-role="button" data-inline="true" />

<input type="submit" value="Submit" data-role="button"
data-inline="true" name="action" />

</form>

A: 1/ Simple test, are you sure you don't have a whitespace or any other character sent before the header()
2/ Did you check you got the http://www.php.net/manual/en/outcontrol.configuration.php#ini.output-buffering option on ? (Else you have to explicitly start output buffering)


text:
Q: How to include commands in Bash's PS1 without breaking line length calculation? Tonin pointed out a bug in my default prompt. Minimal example:

*

*Set PS1:
PS1='$(exit_code=$?; [[ $exit_code -eq 0 ]] || printf %s $(tput setaf 1) $exit_code $(tput sgr0) " ")$ '

At this point, the prompt looks like this:
$

*Now trigger the exit code output by running:
false

Now the prompt contains the exit code in red at the beginning of the line:
1 $

*Press Ctrl-r.

*Type "false". Now the prompt contains only the search:
(reverse-i-search)`false': false

*Press Enter.

The resulting terminal history now contains the following:
1 $ch)`false': false

Expected output:
1 $ false

That is, it seems the history search output is mixed with the prompt and hiding the actual command which was run.
I tried working around this by using PROMPT_COMMAND:
set_exit_code() {
    exit_code=$?
    [[ $exit_code -eq 0 ]] || printf %s $(tput setaf 1) $exit_code $(tput sgr0) " "
}
set_bash_prompt() {
    PS1='$(set_exit_code)$ ' # Double quotes give the same result
}
PROMPT_COMMAND=set_bash_prompt

This doesn't seem to work - the line looks exactly the same as before after searching and running.
How can I fix this?

A: I found the answer on askubuntu.com.  @qeirha mentioned that you have to tell bash that the sequence of characters should not be counted in the prompt's length, and you do that by enclosing it in \[ \].  Based on the example provided, here is one solution:
red=$(tput setaf 1)

reset=$(tput sgr0)

[ "$PS1" = "\\s-\\v\\\$ " ] && PS1='$(exit_code=$?; [[ $exit_code -eq 0 ]] || printf %s \[$red\] $exit_code \[$reset\] " ")$ '

A: Expanding on @manatwork answer but keeping your code splitting the PS1 compute in different functions, you can write your prompt the following way:
set_exit_code() {
    exit_code=$?
    [[ $exit_code -eq 0 ]] || printf "\[$(tput setaf 1)\] $exit_code \[$(tput sgr0)\] "
}
set_bash_prompt() {
    PS1="$(set_exit_code)$ " # with double quotes!
}
PROMPT_COMMAND=set_bash_prompt

Double quotes are mandatory both when setting PS1 and when using printf in the function.

A: PS1='$(exit_code=$?; [[ $exit_code -eq 0 ]] || printf %s \[$(tput setaf 1)\] $exit_code \[$(tput sgr0)\] " ")$ '

(Sorry, no explanation here. See How to customize PS1 properly? or any other question about prompt length calculation issues and \[..\].)


text:
Q: Writing a value from a row into the another row and column I am trying to "marry" two imaginary people in my DB. What I want to do is select people within a certain age-range and then write each others IDs in a column.
If this is my table
ID | sex | age | married to
 1 | M   | 25  | NULL
 2 | F   | 28  | NULL
 3 | M   | 75  | NULL

The result should look something like this:
ID | sex  | age | married_to
 1 | M    | 25  | 2
 2 | F    | 28  | 1
 3 | M    | 75  | NULL

I know the select-statement should look something like this:
SELECT ID FROM table WHERE age BETWEEN ageMin AND ageMax AND married_to IS NULL

But I don't know how to get SQLite to write the ID in the right column. Espacially how to make this work in a DB with about 150k entries. For me the tricky part is to always just write into one row without having a super slow program. Could somebody help me out?

A: First, you need to capture two IDs. One for person A and one for person B, to be married.
Next, you will need to perform two update queries once you have the IDs:

*

*Update person A's "married to" to equal person B's ID

*Update person B's "married to" to equal person A's ID

SQLite allows you to select a random row.
SELECT ID FROM table WHERE age BETWEEN ageMin
      AND ageMax AND married_to IS NULL ORDER BY RANDOM() LIMIT 1

You could do this twice, check to ensure the IDs are separate, and then perform the update queries.
UPDATE table SET married_to = Person_B_ID WHERE ID = *Person A's ID*

and
UPDATE table SET married_to = Person_A_ID  WHERE ID = *Person B's ID*

You can run this sequence of queries any number of times. However, the performance of RANDOM() may not be suitable for a large database. If this is the case you may want to run a query to get all the IDs of people who need to be married, and then match those up using some other programming language. You could then automatically generate the update queries to "marry" the pairs in the database.