text:
Q: How can I loop through array and get value of all it's items I want to  loop through an array of objects and get all data of all of objects but only I only get the data of last object I'don't why it skips the first object , please any one could help me
Here is my array
item {
  _id: new ObjectId("627ed71261b2bd692178bdca"),
  sn: 'fN300W15076fd5bg6dwf',
  merchantId: '9000000058800',
  merchantName: '999',
  networkType: '220509',
  __v: 0,
  terminalId: '987654321',
  resultData: [
    {
      _id: new ObjectId("627edb194884d85b48890da8"),
      uniqueID: '68461616865',
      transactionAmount: '050413',
      currencyCode: '9000000058800',
      terminalId: '987654321',
      transactionDate: '999',
      transactionTime: '220509',
      transactionType: 'DECLINED',
      cardPAN_PCI: 'XXXXXXXXXXXXXXX166',
      onlineRetrievalReferenceNumber: '6161651613516',
      outcome: 'DONE',
      encryptionKeyKCV: '651616161616516',
      transactionEncrypted: 'SUHTHROTRTH161461'
    },
    {
      _id: new ObjectId("627edb494884d85b48890daa"),
      uniqueID: '71616516',
      transactionAmount: '050413',
      currencyCode: '9000000058800',
      terminalId: '987654321',
      transactionDate: '999',
      transactionTime: '220509',
      transactionType: 'DECLINED',
      cardPAN_PCI: 'XXXXXXXXXXXXXXX166',
      onlineRetrievalReferenceNumber: '6161651613516',
      outcome: 'DONE',
      encryptionKeyKCV: '651616161616516',
      transactionEncrypted: 'SUHTHROTRTH161461'
    },
    {
      _id: new ObjectId("627edb5c4884d85b48890dac"),
      uniqueID: '7117117717',
      transactionAmount: '050413',
      currencyCode: '9000000058800',
      terminalId: '987654321',
      transactionDate: '999',
      transactionTime: '220509',
      transactionType: 'APPROVED',
      cardPAN_PCI: 'XXXXXXXXXXXXXXX166',
      onlineRetrievalReferenceNumber: '6161651613516',
      outcome: 'DONE',
      encryptionKeyKCV: '651616161616516',
      transactionEncrypted: 'SUHTHROTRTH161461'
    },
    {
      _id: new ObjectId("627edb674884d85b48890dae"),
      uniqueID: '7117117717',
      transactionAmount: '050413',
      currencyCode: '9000000058800',
      terminalId: '987654321',
      transactionDate: '999',
      transactionTime: '220509',
      transactionType: 'PENDING',
      cardPAN_PCI: 'XXXXXXXXXXXXXXX166',
      onlineRetrievalReferenceNumber: '6161651613516',
      outcome: 'DONE',
      encryptionKeyKCV: '651616161616516',
      transactionEncrypted: 'SUHTHROTRTH161461'
    }
  ]
}
----------------------------------------------------
item {
  _id: new ObjectId("627ed78561b2bd692178bdd3"),
  sn: 'fN300W15076fd5bg6dwf',
  merchantId: '9000000058800',
  merchantName: '999',
  networkType: '220509',
  __v: 0,
  terminalId: '123456789',
  resultData: [
    {
      _id: new ObjectId("627edb884884d85b48890db0"),
      uniqueID: '97279279',
      transactionAmount: '050413',
      currencyCode: '9000000058800',
      terminalId: '123456789',
      transactionDate: '999',
      transactionTime: '220509',
      transactionType: 'GOOD',
      cardPAN_PCI: 'XXXXXXXXXXXXXXX166',
      onlineRetrievalReferenceNumber: '6161651613516',
      outcome: 'DONE',
      encryptionKeyKCV: '651616161616516',
      transactionEncrypted: 'SUHTHROTRTH161461'
    },
    {
      _id: new ObjectId("627edb994884d85b48890db2"),
      uniqueID: '928498452',
      transactionAmount: '050413',
      currencyCode: '9000000058800',
      terminalId: '123456789',
      transactionDate: '999',
      transactionTime: '220509',
      transactionType: 'DECLINED',
      cardPAN_PCI: 'XXXXXXXXXXXXXXX166',
      onlineRetrievalReferenceNumber: '6161651613516',
      outcome: 'DONE',
      encryptionKeyKCV: '651616161616516',
      transactionEncrypted: 'SUHTHROTRTH161461'
    },
    {
      _id: new ObjectId("627edba54884d85b48890db4"),
      uniqueID: '6824684294',
      transactionAmount: '050413',
      currencyCode: '9000000058800',
      terminalId: '123456789',
      transactionDate: '999',
      transactionTime: '220509',
      transactionType: 'DECLINED',
      cardPAN_PCI: 'XXXXXXXXXXXXXXX166',
      onlineRetrievalReferenceNumber: '6161651613516',
      outcome: 'DONE',
      encryptionKeyKCV: '651616161616516',
      transactionEncrypted: 'SUHTHROTRTH161461'
    },
    {
      _id: new ObjectId("627edbe0ade509d1bd9b5277"),
      uniqueID: '6824684294',
      transactionAmount: '050413',
      currencyCode: '9000000058800',
      terminalId: '123456789',
      transactionDate: '999',
      transactionTime: '220509',
      transactionType: 'DECLINED',
      cardPAN_PCI: 'XXXXXXXXXXXXXXX166',
      onlineRetrievalReferenceNumber: '6161651613516',
      outcome: 'DONE',
      encryptionKeyKCV: '651616161616516',
      transactionEncrypted: 'SUHTHROTRTH161461'
    }
  ]
}
----------------------------------------------------
[
  {
    _id: new ObjectId("627edb884884d85b48890db0"),
    uniqueID: '97279279',
    transactionAmount: '050413',
    currencyCode: '9000000058800',
    terminalId: '123456789',
    transactionDate: '999',
    transactionTime: '220509',
    transactionType: 'GOOD',
    cardPAN_PCI: 'XXXXXXXXXXXXXXX166',
    onlineRetrievalReferenceNumber: '6161651613516',
    outcome: 'DONE',
    encryptionKeyKCV: '651616161616516',
    transactionEncrypted: 'SUHTHROTRTH161461'
  },
  {
    _id: new ObjectId("627edb994884d85b48890db2"),
    uniqueID: '928498452',
    transactionAmount: '050413',
    currencyCode: '9000000058800',
    terminalId: '123456789',
    transactionDate: '999',
    transactionTime: '220509',
    transactionType: 'DECLINED',
    cardPAN_PCI: 'XXXXXXXXXXXXXXX166',
    onlineRetrievalReferenceNumber: '6161651613516',
    outcome: 'DONE',
    encryptionKeyKCV: '651616161616516',
    transactionEncrypted: 'SUHTHROTRTH161461'
  },
  {
    _id: new ObjectId("627edba54884d85b48890db4"),
    uniqueID: '6824684294',
    transactionAmount: '050413',
    currencyCode: '9000000058800',
    terminalId: '123456789',
    transactionDate: '999',
    transactionTime: '220509',
    transactionType: 'DECLINED',
    cardPAN_PCI: 'XXXXXXXXXXXXXXX166',
    onlineRetrievalReferenceNumber: '6161651613516',
    outcome: 'DONE',
    encryptionKeyKCV: '651616161616516',
    transactionEncrypted: 'SUHTHROTRTH161461'
  },
  {
    _id: new ObjectId("627edbe0ade509d1bd9b5277"),
    uniqueID: '6824684294',
    transactionAmount: '050413',
    currencyCode: '9000000058800',
    terminalId: '123456789',
    transactionDate: '999',
    transactionTime: '220509',
    transactionType: 'DECLINED',
    cardPAN_PCI: 'XXXXXXXXXXXXXXX166',
    onlineRetrievalReferenceNumber: '6161651613516',
    outcome: 'DONE',
    encryptionKeyKCV: '651616161616516',
    transactionEncrypted: 'SUHTHROTRTH161461'
  }
]

as you see I get only the array of last object
For who's curious how my code looks like
  async getLogByTPE() {
    let result;
    const data = await this.tpeModel
      .aggregate([
        {
          $lookup: {
            from: 'logs',
            localField: 'terminalId',
            foreignField: 'terminalId',
            as: 'resultData',
          },
        },
        // { $unwind: '$resultData' },
        // {
        //   $project: {
        //     uniqueID: '$logs.currenuniqueIDcyCode',
        //     terminalId: '$logs.terminalId',
        //     transactionAmount: '$logs.transactionAmount',
        //     currencyCode: '$logs.currencyCode',
        //     transactionDate: '$logs.transactionDate',
        //     transactionTime: '$logs.transactionTime',
        //     transactionType: '$logs.transactionType',
        //     cardPAN_PCI: '$logs.cardPAN_PCI',
        //     onlineRetrievalReferenceNumber:
        //       '$logs.onlineRetrievalReferenceNumber',
        //     outcome: '$logs.outcome',
        //     encryptionKeyKCV: '$logs.encryptionKeyKCV',
        //     transactionEncrypted: '$logs.transactionEncrypted',
        //   },
        // },
      ])
      .then((ok) => {
        //start of test
        // for (let i = 0; i <= ok.length; i++) {
        //   console.log('ok', ok[i].resultData[i]);
        //   data1 = JSON.stringify(ok[i]);
        // }

        //end of test
        // console.log('OOOKKKK', ok);
        ok.forEach((item) => {
          console.log('item', item);
          console.log('----------------------------------------------------');
          //console.log('resultData', item.resultData);
          result = item.resultData;
          // result = item['resultData'].forEach((sub) => {
          //   console.log('sub', sub);
          //   return sub;
          // });
        });
      });

    // let subitemresult;
    // let result = data.forEach((item) => {
    //   console.log('item', item);
    //   console.log(
    //     'item.resultData',
    //     item.resultData.forEach((subitem) => {
    //       console.log('subitem', subitem);
    //     }),
    //   );
    // });
    // console.log('data', data);
    // console.log('result', JSON.stringify(result));
    console.log(result);
    return result;
  }

ok => my array of objects
item => objects inside of array
resultData => the data I want to get
unfortunately I only  resultData of last object as shown above

A: The result variable where you store the data inside the loop gets overrided on every iteration, so when you return, there is only the last value stored.
A quick fix could be assign an empty array in your declaration on result
  let result: any = [];

Then inside the loop you could push to the array result.
Change this result = item.resultData; for
  result.push(item.resultData);


text:
Q: Unable to launch a wpf application on windows XP machine I have created a WPF application with target Framework 4.5 on Windows 8 machine. The application has reference to two c# dlls with same same target framework. I have used Linq to entities to connect to a MS Sql server database in my application.
Now, When I tried to run the same application by running the exe file located in Debug folder in a Windows XP machine, it gives following error message

D:\Main\TPMS\Debug\TPMS.exe is not a valid win32 application.

What is the issue here?

A: .NET Framework 4.5 is not supported on windows XP. Try targeting .NET Framework 4.0. Another option is to use Mono but since it lacks support of WPF then you should stick to .NET Framework 4.0

A: The .NET Framework 4.5 and later versions are not supported on Windows XP
NET Framework 4.5 and Windows XP

redpajama_set_name: RedPajamaStackExchange


text:
Q: Conda environment not showing up in VS Code I installed miniconda on Windows 10 and created an environment (I followed this guide: https://www.notion.so/shashankkalanithi/Setting-Up-Conda-Environment-ba83f7f019ea44b9af37588eed419eb9). However when I open the VS Code I don't see that environment python interpeter on kernel list. There is only one interpreter on the list: ~\Miniconda3\python.exe
How can I fix this?

A: You can try to follow methods from
vscode - Create a conda environment

Additional notes:
...To ensure the environment is set up well from a shell perspective, one
option is to use an Anaconda prompt with the activated environment to
launch VS Code using the code . command. At that point you just need
to select the interpreter using the Command Palette or by clicking on
the status bar.

A: Firstly you need to create an environment with python in it otherwise it won't recognize it. Create an environment like this first
conda create --name tf26 python==3.10

Use your preferred name and python version here thereafter restart VS Code. You will definitely see your env.
Note:
You can delete any unused env if want like this
conda env remove --name <env_name>

A: I wanted to use the new environment as a Jupyter kernel and had to install the jupyter package for it to show up in the kernel selection of VSCode. You can install it by running conda install jupyter.

A: in vscode press ctrl+shift+p and type python:Select Interpreter you should see all the environment there. If it does not appear create a .py file and try again. also you can press the reload icon on the search bar where you typed python:select interpreter.

A: I finally resolved the problem.
This thread says that you need to create the conda environment passing the python argument:
conda create -n your_env_name python=3.7

Doing this the environment appears in the Select interpreter to start Jupyter server options.

A: The extension automatically looks for interpreters in the following locations:

Conda environments that contain a Python interpreter. VS Code does not
show conda environments that don't contain an interpreter.

After you create a conda environment, you need to activate it and install some packages in order to get the python interpreter. And remember to reload the VSCode. If it still does not exist, you can try to choose Enter interpreter path, to point the path manually.

A: In your project .vscode/settings.json file, just replace the old python.pythonPath setting with the new one (or add if non-existing) python.defaultInterpreterPath and it will work. The value for the setting is the path to the venv you're using in your project.
Afterward, Ctrl+Shift+P via Python: Select Interpreter will allow you to choose a different interpreter.

A: I had the same problem.
After I opened Anaconda Prompt as Administrator and created the environment, I saw it in VS code

Open "Anaconda Prompt" from the Windows start button as
"Administrator."

A: You may check and set up the Conda path. It seems VS code has some problem to find the envs installed. You can go to Setting and search "Conda". Find "Python: Conda Path", and add the path of executable conda. Good luck!

A: The reason why vscode doesn't show the environment is that it doesn't have a python interpreter in it because of inheriting or something.
The solution is also simple. Just manually install python in that environment.
conda install python


text:
Q: Visual Studio 2015 - What does the "Analyzers" reference mean? Creating a plain C# Console App in Visual Studio 2015 Preview, we get a pseudo reference named "Analyzers":

What does the "Analyzers" reference just above mean?
The project file has nothing inside and the properties window shows nothing (completely blank) about this entry (though, in contrast to "reference properties" it says "folder properties" in the header, but that does not say much).
I would expect this to be related to Roslyn, but I have no idea. I have ReSharper installed, but I don't assume it has anything to do with it.
Edit 6.8.2016
The accepted answer explains the tooling provided by analyzers, but leaves open why a development tool becomes a (runtime?) reference. Actually it is not a runtime reference, unlike the other references. So the answer to this miracle is Hans Passants comment below:

They picked a clumsy place to add the code analyzers feature, they just couldn't find a better place without drastically overhauling the solution explorer and nuget. – Hans Passant May 26 '15 at 8:59

A: Live Code Analyzers are used to add custom error messages and warnings that appear live as you're typing, along with automatic code fixes to help you clean them up. They are available as NuGet packages that you add to your projects in Visual Studio 2015.
It is one of the best and helpful key new features of Visual Studio 2015 that lets a NuGet package enable custom warnings and errors in the editor live as you type the code, with automatic code fixes that can clean up those issues for us.
Packages can even be bundled together as a "code-aware library" that pulls in both an API and the domain-specific analyzers to make sure that you stay on course when using it.
We'll have a targeted guidance from the moment we download the NuGet package. And because these analyzers are part of our project, everyone on your team gets to see the same warnings.
Edit 1 :
Analyzers have rules attached to them like below :

These rules focus on the most critical problems in your code,
  including potential security holes, application crashes, and other
  important logic and design errors. You should include this rule set in
  any custom rule set you create for your projects.

A: Currently there are a number of good Analyzers available – Microsoft.AnalyzerPowerPack, Code Cracker, CSharp Essentials, SonarLint etc
Each of these analyzers have their own rule set, so we can decide which analyzer to add, based on our requirements. Once installed via Nuget, the light bulbs and quick actions in VS2015 will pick up the associated rule set and provide the developers with coding assistance on the fly.


text:
Q: Hibernate - How to do @Query update with reference to @JoinColumn attribute @Entity
public class TransactionInfo {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    @OneToOne
    @JoinColumn(name="txnRequestId")
    private TransactionRequest txnRequest;

    ..
}

I would like to do a bulk update on this table using the txnRequestId id field (which is mapped with id field of TransactionRequest table)
With my limited knowledge on HQL so far, I tried this query with tr.txnRequest.id field to compare id of TransactionRequest table -
@Repository
public interface TransactionInfoRepository extends JpaRepository<TransactionInfo, Long>, JpaSpecificationExecutor<TransactionInfo> {

@Transactional
@Modifying
@Query("UPDATE TransactionInfo as tr SET status=?2 WHERE tr.status=?1 and tr.txnRequest.id in (?3)")
int updateStatusToRequestedByTxnReqId(Enum.TransactionStatus oldStatus, Enum.TransactionStatus newStatus, List<Long> trIds);

Exception -
Unexpected errororg.hibernate.hql.internal.QueryExecutionRequestException: Not supported for DML operations [UPDATE com.project.model.TransactionInfo as tr SET status=?2 WHERE tr.status=?1 and tr.txnRequest.id in (?3)]; nested exception is java.lang.IllegalStateException: org.hibernate.hql.internal.QueryExecutionRequestException: Not supported for
DML operations [UPDATE com.project.model.TransactionInfo as tr SET status=?2 WHERE tr.status=?1 and tr.txnRequest.id in (?3)]
org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.hql.internal.QueryExecutionRequestException: Not supported for DML operations [UPDATE com.project.model.TransactionInfo as tr SET status=?2 WHERE tr.stat
us=?1 and tr.txnRequest.id in (?3)]; nested exception is java.lang.IllegalStateException: org.hibernate.hql.internal.QueryExecutionRequestException: Not supported for DML operations [UPDATE com.project.model.TransactionInfo as
tr SET status=?2 WHERE tr.status=?1 and tr.txnRequest.id in (?3)]

I also tried with tr.txnRequestId but got -
 org.hibernate.QueryException: could not resolve property: txnRequestId of: com.project.model.TransactionInfo

I would appreciate a documentation link  or link to this chapter in Hibernate, as I could not reach upto studying these things yet and hence do not know what to search for.

A: You can use Native query then you can use txnRequestId
@Query("UPDATE TransactionInfo SET status=?2 WHERE status=?1 and txnRequestId in (?3)", nativeQuery = true)
int updateStatusToRequestedByTxnReqId(Enum.TransactionStatus oldStatus, Enum.TransactionStatus newStatus, List<Long> trIds);

Assuming your database table name is TransactionInfo


text:
Q: Trying to delete elements from a database SQLite3 from a tkinter treeview GUI using python I have been working on project for my class dealing with GUI in python. I am using tkinter. I have a treeview and I am displaying data in the treeview from a database from SQlite DB. However, I added a delete function to be able to select values from the treeview and then delete them with the delete function and button, I keep getting the same issue: The current statement uses 2, and there are 1 supplied. I have a tuple though so I am quite confused as to why I am getting this error.
Please help.!
def delete():
    conn2 = sq.connect('Clients.db')
    c2 = conn2.cursor()
    for selected_item in tree1.selection():
        c2.execute("DELETE FROM clients WHERE name=? AND phone=?",           (tree1.set(selected_item, '#1'), ))
    conn2.commit()
    tree1.delete(selected_item)

I keep getting get this when I select a value from the treeview and hit the delete button. ( By the way, the delete button is binded with the delete function): sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 2, and there are 1 supplied.
I want to be able to select a value from the treeview and then hit delete and it will delete. Please help. Thank you


text:
Q: Can older-versioned iOS users browse apps exclusive to latest iOS? (e.g iOS5 users see iOS6 apps in App Store) I'm planning to make my app an iOS6 only release.
I'm curious though, will older-versioned iOS users (iOS5 etc) still be able to browse and search for my app in the App Store? Will going iOS6-exclusive limit my exposure?

A: No. If you set the target deployment OS as 6, users on 5.1 or earlier will not see your app when using the App Store app on their device, as the App Store filters based on the target OS. However, they will be able to see it and download it when browsing the App Store via iTunes on their desktop, but they won't be able to run it on their device.
My recommendation: unless your app makes use of things exclusively available for iOS 6 (such as Passbook), make your app with a minimum target OS of 5.1. I'd reckon there are still a lot of users who are hesitant to upgrade to iOS 6 because of Maps alone.


text:
Q: Group by consecutive dates and sum by similar dates in xslt Gurus
I am try to print data rows by consecutive dates and taking a sum of all the time off units in each row into by one summarized row with start date being the first day of the time off and end date being the last time off in the consecutive group. I used below xslt and it worked excellently however there could be case when a time off is cancelled in the system then for the same date I can get a negative value for the unit in which case my xslt below is not working as I am unable to handle similar dates and similar type scenarios. Any advise please.
XML
<?xml version='1.0' encoding='UTF-8'?>
<Data>
    <Worker>
        <Worker_ID>12</Worker_ID>
        <Time_Off>
            <Type>Compassionate Leave</Type>
            <Date>2018-02-09-08:00</Date>
            <Units>1</Units>
        </Time_Off>
        <Time_Off>
            <Type>Compassionate Leave</Type>
            <Date>2018-02-08-08:00</Date>
            <Units>1</Units>
        </Time_Off>
        <Time_Off>
            <Type>Compassionate Leave</Type>
            <Date>2018-02-08-08:00</Date>
            <Units>-1</Units>
        </Time_Off>
        <Time_Off>
            <Type>Compassionate Leave</Type>
            <Date>2018-02-01-08:00</Date>
            <Units>1</Units>
        </Time_Off>
        <Time_Off>
            <Type>Statutory Holiday</Type>
            <Date>2018-02-07-08:00</Date>
            <Units>1</Units>
        </Time_Off>
        <Time_Off>
            <Type>Statutory Holiday</Type>
            <Date>2018-02-06-08:00</Date>
            <Units>1</Units>
        </Time_Off>
    </Worker>

</Data>

Xslt:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:mf="http://example.com/mf"
    exclude-result-prefixes="xs mf"
    version="3.0">

    <xsl:output method="text"/>
    <xsl:strip-space elements="*"/>

    <xsl:function name="mf:date" as="xs:date">
        <xsl:param name="input" as="xs:string"/>
        <xsl:sequence select="xs:date(substring($input, 1, 10))"/>
    </xsl:function>

    <xsl:function name="mf:line" as="xs:string">
        <xsl:param name="group" as="element(Time_Off)*"/>
        <xsl:value-of
            select="$group[1]/../Worker_ID,
            $group[1]/Type,
            mf:date($group[1]/Date),
            mf:date($group[last()]/Date),
            sum($group/Units)"
            separator=","/>
    </xsl:function>

    <xsl:template match="Worker">
        <xsl:for-each-group select="Time_Off" group-by="Type">
            <xsl:variable name="sorted-times" as="element(Time_Off)*">
                <xsl:perform-sort select="current-group()">
                    <xsl:sort select="mf:date(Date)"/>
                </xsl:perform-sort>
            </xsl:variable>
            <xsl:for-each-group select="$sorted-times" group-by="mf:date(Date) - xs:dayTimeDuration('P1D') * position()">
                <xsl:value-of select="mf:line(current-group()) || '
'"/>
            </xsl:for-each-group>
        </xsl:for-each-group>
    </xsl:template>

</xsl:stylesheet>

The output I get is below:
12,Compassionate Leave,2018-02-01,2018-02-01,1
12,Compassionate Leave,2018-02-08,2018-02-08,1
12,Compassionate Leave,2018-02-08,2018-02-09,0
12,Statutory Holiday,2018-02-06,2018-02-07,2

My desired output is below:
12,Compassionate Leave,2018-02-01,2018-02-01,1
12,Compassionate Leave,2018-02-08,2018-02-09,1
12,Statutory Holiday,2018-02-06,2018-02-07,2

A: You have posted an XSLT 3 stylesheet so I guess although you tagged the question as XSLT 2 it is fine to use XSLT 3, therefore here is a suggestion using xsl:iterate:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:mf="http://example.com/mf"
    exclude-result-prefixes="xs mf"
    version="3.0">

  <xsl:output method="text"/>
  <xsl:strip-space elements="*"/>

  <xsl:function name="mf:date" as="xs:date">
      <xsl:param name="input" as="xs:string"/>
      <xsl:sequence select="xs:date(substring($input, 1, 10))"/>
  </xsl:function>

  <xsl:function name="mf:line" as="xs:string">
      <xsl:param name="group" as="element(Time_Off)*"/>
      <xsl:value-of
        select="$group[1]/../Worker_ID,
                $group[1]/Type,
                mf:date($group[1]/Date),
                mf:date($group[last()]/Date),
                sum($group/Units)"
                separator=","/>
  </xsl:function>

  <xsl:template match="Worker">
      <xsl:for-each-group select="Time_Off" group-by="Type">
          <xsl:variable name="sorted-times" as="element(Time_Off)*">
              <xsl:perform-sort select="current-group()">
                  <xsl:sort select="mf:date(Date)"/>
              </xsl:perform-sort>
          </xsl:variable>
          <xsl:iterate select="$sorted-times">
              <xsl:param name="group" as="element(Time_Off)*" select="()"/>
              <xsl:on-completion>
                 <xsl:value-of select="mf:line($group), ''" separator="
"/>
              </xsl:on-completion>
              <xsl:variable name="new-group" as="xs:boolean"
                select="$group
                   and mf:date(Date) - mf:date($group[last()]/Date) gt xs:dayTimeDuration('P1D')"/>
              <xsl:if test="$new-group">
                  <xsl:value-of select="mf:line($group), ''" separator="
"/>
              </xsl:if>
              <xsl:next-iteration>
                  <xsl:with-param name="group" select="if ($new-group) then . else ($group, .)"/>
              </xsl:next-iteration>
          </xsl:iterate>
      </xsl:for-each-group>
  </xsl:template>

</xsl:stylesheet>

Online at https://xsltfiddle.liberty-development.net/pPgCcov/2.


text:
Q: Comparison in loop (optimization) Let's consider the situation:
bool b = checking_some_condition();

for (int i = 0; i < 1000000; ++i)
{
    if (b)
           do_something(i);
    else
           do_something_else(i);
}

Is it obvious that compiler optimizes the code above into something like this? :
if (b)
{
    for (int i = 0; i < 1000000; ++i)
        do_something(i);
}
else
{
    for (int i = 0; i < 1000000; ++i)
        do_something_else(i);
}

Of course, I am only giving example the present the situation. I know that checking bool value 1000000 times is hardly noticeable for the performace, but if I'd have more complex comparisons with multiple ways of how the code inside loop would go, change in performance could be significant. Especially if this code would be inside the function that is called multiple times.

A: As was mentioned in the comments above you can't really make a safe assumption what the compiler will optimize or won't. It's their "freedom" to do these things or not.
If you want to get a feeling for what's going on the best way is to look at the generated assembly which will give you and objective way of arguing what the compiler might have done. https://godbolt.org/z/W-5Hve shows the easy example you posted above.
However, please try to make the example in godbolt as realistic as possible and then check the assembly. Even if two snippets will yield the same assembly in godbolt to make sure that this will also happen in your codebase you need to check the assembly of your compiled implementation in you codebase as well.
Summarizing this, what I normally do is:
- try a realistic example in godbolt and play with different compilers/flags and change the code until I think I know whats going on.
- compile my project and look at the assembly there to try and find the specific function again to make sure that the result in my code base is the same.
As a little extra: objdump -M intel -dC executable will show you the assembly of an executable.


text:
Q: Expected highest order statistic as a function of sample size Take any non-negative iid random variables $X_1,X_2,...$.
Let $X^{(n)}=\max\{X_1,...,X_n\}$ be the highest order statistic among $n$ samples.
Consider the expecetaction $E[X^{(n)}]$ as a function of $n$.
Do we have restrictions on $E[X^{(n)}]$ except for that it is increasing and concave in $n$?
In other words, for any function $f:\mathbb{N}\to \mathbb{R}_+$ which is increasing and concave, can we find a random variable such that $f(n)=E[X^{(n)}]$ for all $n$?
Here, $f$ being concave means $f(n+2)-f(n+1) \le f(n+1)-f(n)$ for any $n \in \mathbb{N}\cup\{0\}$.

A: If the CDF of $X$ is $F(x)$, the CDF of $X^{(n)}$ is $F(x)^n$.  Assuming these expectations are finite, we have
$$ f(n) = \mathbb E[X^{(n)}] = \int_0^\infty \left(1 - F(x)^n\right)\; dx $$
But there's no need to restrict this formula to integer $n$: for any $t > 0$, let's take
$$ f(t) = \int_0^\infty \left(1 - F(x)^t\right)\; dx $$
Now the $k$'th derivative of this is
$$f^{(k)}(t) = \int_0^\infty - F(x)^t \ln(F(x))^k\; dx  $$
which is nonnegative for odd $k$ and nonpositive for even $k$ (since $0 \le F \le 1$).  As a consequence, the $k$'th differences of $f(n)$ are also nonnegative for odd $k$ and nonpositive for even $k$.  So there are indeed other constraints on $f$.


text:
Q: Adding Input to day cell in month view of FullCalendar I'm trying to modify the FullCalendar month view so each day cell has an input element.
Here's my code:

(...)
dayRender: function (date, cell) {
          cell.append('<input type="number" style="margin-top: 60px; width: 30%; margin-left: 2px; z-index: 10; pointer-events: all!important">');
        }
(...)

So far, that input is showing but it doesn't focus on click. How would I go about making it focus?
As you can see, I tried seeting the pointer-events of the input to all, while setting the table pointer-events to none, but the result is the same.

A: I know it's probably a bit too late for you to answer this question but this can be fixed with simple CSS by adding higher z-index on calendar background:
 .fc-row .fc-bg {
    z-index: 5;
  }

I hope it helps for someone who was looking for the same problem.

A: I have been trying and it works handling the event of dayClick. So, when the day is clicked I manually focus the input. Here is the code:
dayClick: function() {
    $(this).find("input").focus();
}

Maybe is not the best solution but it works.


text:
Q: IMAP - ignore picture or attachment? I'm working with my first ever Python project and I've been stuck for a while now. It's a program that reads my email from a specific email folder and saves the message down to a csv file. The problem is when someone includes an image or attaches something the program saves the image code instead of the message.
def checkmail():
    try:
        # create an IMAP4 class with SSL
        imap = imaplib.IMAP4_SSL("imap.gmail.com")
        imap.login(username, password)
        imap.select("FromB") #Inbox to use
        result, data = imap.uid('search', None, "UNSEEN")  # (ALL/UNSEEN)
        inbox_item_list = data[0].split()

        most_recent = inbox_item_list[-1]

        for item in inbox_item_list:
            result2, email_data = imap.uid('fetch', most_recent, '(RFC822)')
            raw_email = email_data[0][1].decode("utf-8")
            email_message = email.message_from_string(raw_email)
            date_ = email_message['date'].format(time.strftime("%d-%b-%Y"))
            counter = 1
            for part in email_message.walk():
                if part.get_content_maintype() == "multipart":
                    continue
                filename = part.get_filename()
                content_type = part.get_content_type()

                if not filename:
                    ext = mimetypes.guess_extension(part.get_content_type())
                    if not ext:
                        ext = '.bin'
                    if 'text' in content_type:
                        ext = '.txt'
                    filename = 'msg-part-%08d%s' %(counter, ext)
                counter += 1

            save_path = os.path.join(os.getcwd(), "jobb")
            if not os.path.exists(save_path):
                os.makedirs(save_path)
            with open(os.path.join(save_path, filename), 'wb') as fp:
                fp.write(part.get_payload(decode=True))

                #print(content_type)
                if "plain" in content_type:
                    print("z")
                    #print(part.get_payload())
                elif "html" in content_type:
                    html_ = part.get_payload(decode=True)
                    charset = part.get_content_charset('iso-8859-1')
                    chars = html_.decode(charset, 'replace')
                    soup = BeautifulSoup(chars, "html.parser")
                    text_mail = soup.get_text()
                    print("En ny csv sparad")
                else:
                    # Here I have just a print function earlier and everytime
                    # there was an image the program printed the print function.
                    # So I figured what if I instead put in the code that saves
                    # the text when there is no image but that didn't work. And
                    # now I'm stuck I don't know how to solve this and would
                    # like guidance.
                    html_ = part.get_payload(decode=True)
                    charset = part.get_content_charset('iso-8859-1')
                    chars = html_.decode(charset, 'replace')
                    soup = BeautifulSoup(chars, "html.parser")
                    text_mail = soup.get_text()
                    print("One new csv saved")

        testing123 = {'text': [text_mail],
                      'date': [date_]
                     }

        df = pd.DataFrame(testing123, columns=['text', 'date'])
        dt = datetime.today()
        date_today = dt.timestamp()
        df.to_csv("D:\APMPYTHON\(%s).csv" % date_today)
    except:
        print("No new email")


text:
Q: Way different execution times of Bubble sort and Insertion sort despite the same complexity I have task to compare 3d Matrix Bubble sort and Insertion sort execution times. They only should sort numbers in each row. I wrote a methods in Java like below:
static void BubbleSort(char tab2D[][], int tabSize) throws InterruptedException {
    for (int i = 0; i < tabSize; i++) {
        for (int j = 1; j < tabSize - i; j++) {
            for (int k = 0; k < tabSize; k++) {
                if (tab2D[k][j - 1] > tab2D[k][j]) {
                    char temp = tab2D[k][j];
                    tab2D[k][j] = tab2D[k][j - 1];
                    tab2D[k][j - 1] = temp;
                }
            }
        }
    }
}

static void InsertionSort(char tab2D[][], int size) throws InterruptedException {
    char temp;
    int i, j;

    for (int ii = 0; ii < size; ii++) {
        for (i = 1; i < size; i++) {
            temp = tab2D[ii][i];
            for (j = i - 1; j >= 0 && tab2D[ii][j] > temp; j--) {
                tab2D[ii][j + 1] = tab2D[ii][j];
            }
            tab2D[ii][j + 1] = temp;
        }
    }
}

As far as I know both algorithms have time complexity O(n^2), yet there's my results for both algorithms:
100x100 Matrix: Bubble sort=21 ms, Insertion sort=3 ms
300x300 Matrix: Bubble sort=495 ms, Insertion sort=20 ms
700x700 Matrix: Bubble sort=6877 ms, Insertion sort=249 ms

Measuring time like:
start = System.currentTimeMillis();
// sort method
stop = System.currentTimeMillis();
time = stop - start;

I don't really understand where's problem, as Bubble sort is WAY too slow comparing to Insertion. As I understand their times should be similar. Checked even both versions of algorithms editing them to sort only arrays, Bubble sort is still way slower and I can't tell why.
Next thing I tried was to put Thread.Sleep(1) in both algorithms just bellow swapping moment. After doing that I realized that times finally look similar and are only just a bit different. Could someone explain why is that happening? Are times I measured before correct?

A: As mentioned in comments, one cannot say anything useful about the actual time it takes to run an algorithm, based on a given time complexity. Two algorithms that have the same time complexity do not necessarily have to need the same time to complete the same job.
That being said, here are some differences between the two functions that explain why InsertionSort needs less time to do the job on average:

*

*If we ignore the tab2D[ii][j] > temp condition in the inner loop of InsertionSort, both functions perform the same total number of loop iterations. However, as InsertionSort has a condition in the inner loop that can make it exit early, InsertionSort will often make fewer iterations.

*Both make a data comparison in their inner loops, but BubbleSort must read two values from the array to do that, while InsertionSort only needs one access to the array (as the other value is in temp)

*The inner loop of InsertionSort can focus on one value that bubbles into its right place, meaning it does not actually has to swap, but only copy. BubbleSort has to swap, which involves three assignments instead of one. Granted, BubbleSort does not have to swap in each iteration of its inner loop, but that is offset against the fact that InsertionSort does not move all array values (in the loop's range) either -- as it has this early exit. This gives a feel of BubbleSort doing 3 assignments, where InsertionSort only needs 1 assignment (plus an overhead of 2 assignments outside of the inner loop). We can see that on average BubbleSort will perform more assignments (involving the array) than InsertionSort.


text:
Q: How should I modify the code to call API and return with array? I am trying to modify my static menu to dynamic sidebar menu.
my Core UI file (TheSidebar.tsx) accepts _naigation.js as a array.
Here is what I want to modify in _navigation.js

*

*before rendering, call axios to get data for dynamic menu title

*after receiving response, update static title (ex Menu1, Menu2) to {apiResult.[0]} for dynamic menu.

*return array

How should I insert api call in _navigation.js and return array to TheSidebar.tsx?
Please allow me to share your kind advicee.
TheSidebar.tsx
return (
    <CSidebar>
       ...
      <CSidebarNav>
       ...
       ...
        <CCreateElement
          items={navigation} // it only accepts array.
          components={{
            CSidebarNavDivider,
            CSidebarNavDropdown,
            CSidebarNavItem,
            CSidebarNavTitle
          }}
        />
)

const navigation = [
  {
    _tag: 'CSidebarNavItem',
    name: 'Menu1', //should change to dynamic data ex) menu2 --> {responseResult.[2]}
    to: '/dashboard',
    icon: <CIcon name="cil-speedometer" customClasses="c-sidebar-nav-icon" />,
    badge: {
      color: 'primary',
      text: 'haha',
    },
  },
  {
    _tag: 'CSidebarNavItem',
    name: 'Menu 2', //should change to dynamic data ex) menu2 --> {responseResult.[2]}
    to: '/dashboard',
    icon: <CIcon name="cil-speedometer" customClasses="c-sidebar-nav-icon" />,
    badge: {
      color: 'primary',
      text: 'haha',
    },
  },
];

export default navigation;


text:
Q: How do I create an application from my site? When I get a web view output for my site, nothing happens after entering the number and clicking the button to send the verification code.
But when I enter the URL in each browser and after entering the number click on the button, I get the confirmation code.
my address URL: https://app.my30t.ir/login
I've recently tried testing sample browser source code in GitHub but I don't get a normal result. please guide me.
public class MainActivity extends ActionBarActivity {

    private WebView myWebView;
    private EditText editText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myWebView = (WebView) findViewById(R.id.activity_main_webview);
        WebSettings webSettings = myWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        myWebView.loadUrl("https://app.my30t.ir/login");
        myWebView.setWebViewClient(new WebViewClient());
        myWebView.setWebViewClient(new TutorialWebViewClient());
        editText = (EditText) findViewById(R.id.editText);
        editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
                @Override
                public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                    boolean handled = false;
                    if(actionId == EditorInfo.IME_ACTION_SEND) {
                        myWebView.loadUrl(editText.getText().toString());
                        handled = true;
                    }
                    return handled;
                }
            });
    }
}

A: Try this
   editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
                @Override
                public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                    boolean handled = false;
                    if((actionId == EditorInfo.IME_ACTION_SEARCH
            || actionId == EditorInfo.IME_ACTION_DONE
            || event.getAction() == KeyEvent.ACTION_DOWN
            && event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
                        myWebView.loadUrl(editText.getText().toString());
                        handled = true;
                    }
                    return handled;
                }
            });


text:
Q: Shared library compilation in GCC with -O3 don't export as much symbols as in -O0 I would ask for your advice.
I have a problem with shared library compilation under gcc.
There are several template class and methods. With -o0 optimization each one is exported as expected, in -o3 some of them will be hidden/not compiled/not exported (nm output clearly shows it). It looks like the methods are getting inline and there is a bug with it. I cannot see different reason.
The question: How to export all symbols in -o3 optimization. Why -o0 produce more than -o3.
Maybe I need some special treatment in case of templates in shared library? For example I should make explicit template specialization?
If needed, I will prepare a smallest possible example with the issue.
edit:
Code and verbose gcc logs (o0.log and o3.log) on git hub: https://github.com/MOJNICK/shadow/tree/stack_debug/libcomparator

nm output in -O0 (among other not worth to mention symbols):
./lib/libcomparator.so:00000000000008e0 T instantiate()
./lib/libcomparator.so:000000000000098c W IterateProcess<unsigned char>::color_distance(unsigned char*, unsigned char*)
./lib/libcomparator.so:0000000000000950 W IterateProcess<unsigned char>::iterate_H(unsigned char*, unsigned char*)
./lib/libcomparator.so:0000000000000946 W IterateProcess<unsigned char>::IterateProcess()
./lib/libcomparator.so:0000000000000946 W IterateProcess<unsigned char>::IterateProcess()
./lib/libcomparator.so:0000000000000919 W std::pow(double, int)

nm output in -O3 (among other not worth to mention symbols):
  ./lib/libcomparator.so:00000000000006a0 T instantiate()

libcomparator.hpp
#ifndef COMPARATOR_HPP
    #define COMPARATOR_HPP
    #include <cmath>

    typedef char unsigned UCHAR;

    template <class TYPE>
    class IterateProcess
    {
    public:
        IterateProcess();
        double iterate_H(TYPE* pix0, TYPE* pix1);
        double color_distance(TYPE* pix0, TYPE* pix1);
    private:
    };
#endif

libcomparator.cpp:
#include "libcomparator.hpp"

template <class TYPE> IterateProcess<TYPE>::IterateProcess(){}

template <class TYPE> double IterateProcess<TYPE>::iterate_H(TYPE* pix0, TYPE* pix1)
{
    return color_distance(pix0, pix1);
}

template <class TYPE> double IterateProcess<TYPE>::color_distance(TYPE* pix0, TYPE* pix1)
{
    double var = -(pix1[0] / static_cast<double>(pix0[0]) + pix1[1] / static_cast<double>(pix0[1]) + pix1[2] / static_cast<double>(pix0[2]));//for minimize color_distance
    return std::pow(pix1[0] / static_cast<double>(pix0[0]) + var, 2) + std::pow(pix1[1] / static_cast<double>(pix0[1]) + var, 2) + std::pow(pix1[2] / static_cast<double>(pix0[2]) + var, 2);
}

void instantiate()
{
    UCHAR pix [] = {10,10,10};
    IterateProcess<UCHAR> specifyIT;
    specifyIT.iterate_H(pix, pix);
}

If you need to build, do in Release.
To switch -O3 to -O0 comment out line in main CmakeLists.txt:
string( REPLACE "-O3" "-O0" CMAKE_CXX_FLAGS_RELEASE ${CMAKE_CXX_FLAGS_RELEASE})

A: You have to tell the compiler that it should always export the symbols even if they could be removed in case of optimization like:
 template class __attribute__((visibility ("default"))) IterateProcess<UCHAR>;

Add this after your class definition and you should get the symbols exported.
After adding this I got:
0000000000000910 W _ZN14IterateProcessIhE14color_distanceEPhS1_
0000000000000880 W _ZN14IterateProcessIhE9iterate_HEPhS1_
0000000000000870 W _ZN14IterateProcessIhEC1Ev
0000000000000870 W _ZN14IterateProcessIhEC2Ev

I compiled with:
 g++ -shared main.cpp -O3 -o x.so -fPIC

EDIT: Why optimized code is not seen by default:
Simply because it is not generated! If your call from instantiate is fully inlined, there is no code left in any object file because it is never needed anymore. For creating a shared library, you have to tell the compiler, that you really want to get currently unused instances. But this is a really obscure use case! In c++ you should present most as possible in header files to enable the compiler to optimize as much as possible! So splitting code in .h/.cpp and place template code into cpp file is really seldom I would advice you to avoid that.


text:
Q: What system is behind the ordering of ANSI colors? Sorry. Google banned me.
I'm trying to understand terminal special chars and colors. And what I can't understand is ordering of colors.
0 black
1 red
2 green
3 yellow
4 blue
5 magenta
6 cyan
7 white

RGYBMC... RGB + CMYK + drink time?
Please help Dora to find common sense.

A: If you convert the color numbers to binary, you will find the first bit corresponds to blue, the second bit is green and the third is red.
Example: 310=0112=green+red=yellow


text:
Q: Login with GNU screen with username and password in a script I need to login to a screen session with screen /dev/tty.usbmodem1415 115200 and then there is a prompt for username and password.
login:
Password:

After entering I would like to enter a simple command. E.g. ls and then exit the screen session.
Is there a way to script this entire process?

A: Thanks! Found the answer
#!/usr/bin/expect -f

set username "hello"
set password "secret"
spawn screen /dev/tty.usbmodem1415 115200

expect "?ogin:"
send "$username\r"

expect "?assword:"
send "$password\r"

send "ls\r"


text:
Q: Grabing a data attribute of a clicked element? I have a link that opens a modal when clicked, however that element also has a data-id="#id here" attribute that I need to grab so I can pass it to my php script for processing. How can I accomplish this?
My JS code:
$(document).ready(function() {
$('#edit_general').click(editModal);

});

function editModal(event)
{
var modal = $('#editModal');
modal.modal({
    show: true
});
}

My html:

<a id="edit_general" href="#editModal" data-uid="<?php echo $u->id; ?>">Edit General

I tried using the this keyword but it didn't work.
How can I accomplish this?

A: Try this: Demo http://jsfiddle.net/szS2J/1/ or http://jsfiddle.net/ug7ze/
$(this).data('uid')

Hope it fits the cause :)
like this:
$('#edit_general').click(editModal);
      $(this).data('uid')

full
$(document).ready(function() {
    $('#edit_general').click(editModal);

});

function editModal(event) {
    alert($(this).data('uid'));
    var modal = $('#editModal');
    modal.modal({
        show: true
    });
}

A: You can get the value using the attr method: $(this).attr('data-uid')

A: Like this stored in data_id.
   $(document).ready(function() {
      $('#edit_general').click(function() {
         var data_id = $(this).data('uid');
         var modal = $('#editModal');
            modal.modal({
            show: true
         });
      });
   });


text:
Q: MySQL Connection will not close This is really simple, all i'm trying to do is fill a datatable, i have everything surrounded by using() and the connection will not dispose/close.  Please help
DataTable loginTbl = MySQLProcessing.MySQLProcessor.StoreProcedureDTTable("Login", ParamArgs, "Login");

 public static DataTable StoreProcedureDTTable(string mysqlQuery, List<string> CommandArgs, string queryName)
    {

        DataTable DTTableTable = new DataTable();
        using (MySqlCommand MySQLCommandFunc = new MySqlCommand(mysqlQuery))
        {
            MySQLCommandFunc.CommandType = CommandType.StoredProcedure;
            foreach (string args in CommandArgs)
            {
                string[] splitArgs = args.Split('|');
                MySQLCommandFunc.Parameters.AddWithValue(splitArgs[0], splitArgs[1]);
            }
            using (MySqlDataAdapter DataDTTables = new MySqlDataAdapter(MySQLCommandFunc))
            {
                DataDTTables.SelectCommand.CommandTimeout = 240000;
                lock (_object)
                {
                    using (MySqlConnection con = new MySqlConnection(ConfigurationManager.ConnectionStrings["mysqlCon"].ConnectionString))
                    {
                        MySQLCommandFunc.Connection = con;
                        DataDTTables.Fill(DTTableTable);
                    }

                }
            }
        }
        DataTable catchConnectionTable = DTTableTable;
        DTTableTable.Dispose();
        return catchConnectionTable;
    }

A: Add Pooling=False to the connection string

A: Have you tried:
      using (MySqlConnection con = new MySqlConnection(ConfigurationManager.ConnectionStrings["mysqlCon"].ConnectionString))
      {
           con.open();
           MySqlDataAdapter DataDTTables = new MySqlDataAdapter(MySQLCommandFunc)
           DataDTTables.SelectCommand.CommandTimeout = 240000;
           MySQLCommandFunc.Connection = con;
           DataDTTables.Fill(DTTableTable);
           con.close();
     }

?

A: Alternatives to Pooling=false are SqlConnection.ClearPool and SqlConnection.ClearAllPools methods. For more information read: SQL Server Connection Pooling (ADO.NET)


text:
Q: Find all group homomorphisms from $\mathbb{Z}^n$ to $ \mathbb{Z}^n$ Can we find all group homomorphism from $\mathbb{Z}^n$ to $\mathbb{Z}^n$?
For such a map surjective always imply isomorphism (like $\mathbb{Z}$)?

A: if the epic morphism were not monic then it would have a non-trivial kernel $K$. then, we would have $Z^n \cong Z^n \oplus K$

A: $\operatorname{Hom}_{\mathbb Z}(\mathbb Z^n,\mathbb Z^n)\simeq\operatorname{Hom}_{\mathbb Z}(\mathbb Z,\mathbb Z^n)^n\simeq\mathbb Z^{n^2}$. In fact, a group homomorphism from $\mathbb Z^n$ to $\mathbb Z^n$ corresponds to a matrix in $M_{n}(\mathbb Z)$.
Every surjective endomorphism of $\mathbb Z^n$ is an isomorphism: if $A\in M_n(\mathbb Z)$ is the corresponding matrix of a surjective endomorphism of $\mathbb Z^n$, then there exists $B\in M_n(\mathbb Z)$ such that $AB=I_n$. Now, by taking the determinant, it follows that $A$ is invertible. (For a more general case see here.)


text:
Q: DOJO DataGrid+JsonRest+pagination From what I have read on the internet about DataGrid pagination, I still can make it work. I have a DataGrid like this:
var grid = new DataGrid({
    store: dataStore = new ObjectStore({objectStore: jsonrest_store}),
    structure: [
        {name: 'aaa', field: 'aaa', 'width': initialCol1},
        {name: 'bbb', field: 'bbb', 'width': initialCol2},
        {name: 'ccc', field: 'ccc', 'width': initialCol3},
        {name: 'ddd', field: 'ddd', 'width': initialCol4}
    ],
    rowsPerPage: 10,
    autoHeight: 8,
    keepRows: 100
}, "id_of_container");
grid.startup();

I tried different combinations of rowsPerPage and autoheight(number/off) but whenever I scroll down no call is made not even on the fetch of the ObjectStore. Does anyone know what the problem is?

A: Try giving this in your grid declaration
filter: {
             isServerSide: true,
 }

//It should fire the request automatically


text:
Q: Fit to text within the div I need fit text within the fixed width container, for example i have 150px width in particular div but text is dynamically will come so based one font size change and fit to the container, kindly suggest
Note:
only javascript

A: You could use this method, stolen from this answer:
How to: Reduce font-size if a line breaks
Written by AlexK

var divWidth = $("#theDiv").width();
var text = $("#text");
var fontSize = 12;

while (text.width() > divWidth)
  text.css("font-size", fontSize -= 0.5);

text.css("display", "inline");

  This sentence is too large to fit within the div.

Note that you need JQuery for this.
If you don't want to use jQuery, it shouldn't be hard to replace it with JS.
JSFiddle


text:
Q: Compare list of JSONArray in ArrayList I have an ArrayList containing a list of JSONArrays
staffArray = new ArrayList<JSONArray>();

the JSONArray is in a form of this:
[
    {
      "id": "k40dn-dff02-mm1",
      "name": "staff1",
      "tel": "0123456789",
    },
    {
      "id": "ch2mq-pmw01-ps6",
      "name": "staff2",
      "tel": "9876543210",
    }
    ...
]

And the ArrayList will be containing different sizes of JSONArray.
Now I want to check in the ArrayList for each JSONArray, if they contain the same value for "id". So say that if the ArrayList has three different sizes of JSONArray, how can I tell the they each contain a JSONObject with the same value for "id" in it.
So far I have tried this to extract the string:
for(int i = 0; i < staffArray.size(); i++){
    JSONArray jsonArray = new JSONArray();
    jsonArray = staffArray.get(i);
    for(int j = 0; j < jsonArray.length(); j ++){
        JSONObject json = null;
        try {
            json = jsonArray.getJSONObject(j);
            String id = json.getString("id");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

A: If you would like to check for duplicate IDs in your ArrayList, you could do something like this:
ArrayList<JSONArray> staffArray = new ArrayList<>();

Set<String> ids = new HashSet<>();
for (JSONArray array : staffArray) {
    for (int i = 0; i < array.length(); i++) {
        JSONObject obj = array.getJSONObject(i);
        if (!ids.add(obj.getString("id"))) {
            // duplicate IDs found, do something
        }
    }
}

A: How about using group by to group the json arrays with same id something like this
public static void groupById(List<JSONArray> staffArray) {
    Map<String, List<JSONArray>> jsonArraysById = staffArray.stream().collect(Collectors.groupingBy(jsonArray -> getIdFromJsonArray(jsonArray)));
    jsonArraysById.forEach((id, arrays) -> {
        System.out.println("Arrays with id " + id + " are " + arrays);
    });
}

public static String getIdFromJsonArray(JSONArray jsonArray) {
    String result = null;
    for (int j = 0; j < jsonArray.length(); j++) {
        JSONObject json = null;
        try {
            json = jsonArray.getJSONObject(j);
            result = json.getString("id");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    return result;
}


text:
Q: Angular 6 HTTP Interceptor Refresh token 401 handling I have built my AuthInterceptor which on a 401 error sends a request to get a new token.
The handle401Error method is called when I encounter a 401 error, But I don't seem to be getting any response in my this.authService.refreshToken().pipe()
AuthInterceptor
import { Injectable, Injector } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, tap, switchMap } from 'rxjs/operators';
import { AuthService } from '../services/auth.service';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  isRefreshingToken:boolean = false;
  constructor(public authService: AuthService, private injector: Injector) {}

    addToken(req: HttpRequest<any>, token: string): HttpRequest<any> {
        return req.clone({ setHeaders: {
          Authorization: 'Bearer ' + token,
          'Content-Type': 'application/json'
       }})
    }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    request = this.addToken(request, this.authService.getToken())
    return next.handle(request).pipe (
      catchError((error: Error) => {
        if(error instanceof HttpErrorResponse){
          console.log('err', error);
          switch(error.status) {
            case 401:
            this.handle401Error(request, next)
            default:
            return throwError(error);
          }

        } else {
          return throwError(error);
        }
      })
    );
  }

  handle401Error(request: HttpRequest<any>, next: HttpHandler){
    console.log('handle 401');
    if(!this.isRefreshingToken) { //do not send another refresh token request if already in progress
      this.isRefreshingToken = true;

      return this.authService.refreshToken().pipe(
        switchMap((newToken: string) => {
          console.log('newToken', newToken) // I DO NOT GET A VALUE HERE
            if (newToken) {
              return next.handle(this.addToken(request, newToken));
            }

        }),
        catchError((error) => {
          console.log('error', error) //NOR DO I GET AN ERROR
          return throwError(error)
        }),
        tap(data => console.log(data))
      )
    }
  }
}

AuthService Refresh Token
refreshToken(): Observable<string> {
    console.log('refreshToken');
    let token = 'xxx-xxx-xx';

    return of(token).pipe(delay(1000));
}

A: Besides the missing return in 'case 401', here's how I would handle it.
The basic idea is that you want to retry the entire observable once you receive the new refresh token. Also, the request is patched inside an observable so that on each retry it will get the new token from the auth service.
import { HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Injectable } from '@angular/core';

import { Observable } from 'rxjs';
import { catchError, retryWhen, switchMap, tap } from 'rxjs/operators';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  private retryRequest = Symbol('reload');
  private refreshToken = this.authService.refreshToken()
    .pipe(
      tap(newToken => {
        if (newToken) {
          throw this.retryRequest;
        }
      }),
      share(),
    ) as Observable<any>;

  constructor(public authService: AuthService) { }

  private addToken(req: HttpRequest<any>, token: string): HttpRequest<any> {
    return req.clone({
      setHeaders: {
        Authorization: 'Bearer ' + token,
        'Content-Type': 'application/json'
      }
    });
  }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const request$ = new Observable<HttpRequest<any>>(observer => {
      observer.next(this.addToken(request, this.authService.getToken()));
      observer.complete();
    });

    return request$.pipe(
      switchMap(req => next.handle(req)),
      catchError((error: Error) => {
        if (error instanceof HttpErrorResponse) {
          switch (error.status) {
            case 401:
              return this.refreshToken;
            default:
              throw error;
          }
        } else {
          throw error;
        }
      }),
      retryWhen(err$ =>
        err$.pipe(
          tap(err => {
            if (err === this.retryRequest) { return; }
            throw err;
          })
        )
      )
    );
  }
}


text:
Q: What kind of security do I need for when having a database that holds back accounts and credit card details? I'm a newbie when it comes to security. I've read posts that mentioned that encryption alone doesn't make an app,website or database secure.
I'm also new to certificates and stuff. I've barely touched these things but I'm gonna create a website that connects to my local testing database for the purpose of testing the security and as temporary playground.
It's basically like UBER. I want to prevent the server/database from being accessed and to prevent data from being stolen, what kind of security system do I actually need for this type of website or service?
PS: Currently I'm using Bitnami WAPP stack. I use Apache/PHP combined with PostgreSQL.

A: Only store credit card details in your server when you can't rely on a third party. A safe way is having credit card details stored encrypted using public key cryptography using your password-protected private key, so you can reveal the credit card details on your personal machine (e.g. via javascript libraries on your web-based application) by holding the private key file and entering the password. That way the credit card details are never stored anywhere, and only visible by you and anyone you authorise by giving your private key file and password.

A: Using third parties like Braintree or Stripe is a highly recommended idea. Let their big teams of security experts deal with the security side of things. That way, even you and your employees can't see customers' credit card details (only the last 4 digits), but you can still charge them via the third party. Customers appreciate knowing there info is safe.
I'd rather give my card details to PayPal and let 100 companies use PayPal to charge me, instead of giving my card details to 100 companies.


text:
Q: Script bash chmod in a cicle i want that script do a cicle when i introduce a dir and will ask each file i have there to change perm . why this output is always cant fin "file?" but the file exist
fucntion permi {

    echo "What is the path of the file? the introduce the name of the file:"

    read DIRECT

    file=`ls -l ${dir} | cut -f 9 -d " "`

    while read file
    do

        echo "[u|g|o]"

        read who

        echo "[r|w|x]"

        read ans

        chmod ${who}+${ans} $file

    done

}

A: you may try this
fucntion permi {

echo "What is the path of the file? the introduce the name of the file:"
# read path from user with pattern .. eg (/home/mebada/test/* for all files, /home/mebada/test/*txt for all text files)

read path

# here I am iterating over the list of directory files .. no need to cut because I am just ls without ls long format (ls -l)
for myFile in `ls  $path`;  do
    # showing file current permission
    ls -l ${myFile}
    echo
    echo "[u|g|o]"
    echo
    read who

    echo "[r|w|x]"

    read ans
    #change file permission
    chmod ${who}+${ans} $myFile

    # show after permission
    ls -l $myFile
    echo
    #Separator between two files
    echo " ---- "
  done
 }

A: There are four major problems here. First, ls -l ${dir} | cut -f 9 -d " " does not generate a list of filenames. It picks out the 9th "field" from a long-format ls listing, but that might or might not be the filename, depending on exactly what ls -l prints. On my Mac, it mostly prints part of the date field. In general parsing ls is a bad idea, and parsing ls -l is even worse. There are better ways to do it.
Second, the loop (while read file) doesn't do anything like what you want. What it does is read lines from standard input (generally, the that means it'll wait for the user to type something in), and puts what it reads into the variable file (which replaces the output from ls -l ${dir} | cut -f 9 -d " "). What you wanted to do was read from the variable file, not into that variable.
The third problem is that when working with the files you've found (e.g. chmoding them), you need to supply the directory path and the filename, like chmod ${who}+${ans} $dir/$file.
But there's a better way that solves all three of these problems at once. Just use for file in "${dir}"/*. The wildcard will expand to a list of files in ${dir} (including the directory path) without any of the messiness of dealing with ls's output.
The fourth major problem is that you don't tell the user which file you're asking for the permissions to; the script just asks "[u|g|o]" and "[r|w|x]" over and over again, without saying which file it'll apply to.
I also have three minor suggestions: the function keyword is nonstandard; the more standard way to define a function is with parentheses: permi() { .... Also, rather than echoing a prompt for input, use read -p to print the prompt.  Finally, it's best to put double-quotes around variable references, to avoid trouble in case they contain spaces or some other special characters. With all these changes, here's what I get:
permi() {

    read -p "What is the path of the file? the introduce the name of the file: " dir

    for file in "$dir"/*; do

        echo "New permissions for $file:"
        read -p "[u|g|o] " who
        read -p "[r|w|x] " ans

        chmod "${who}+${ans}" "$file"

    done

}

A: When I run ls -l | cut -f 9 -d " " I get some empty fields, some years or single digits. I'd recommend just using ls (without -l) to get the file names, since you seem to care only for the file names anyway, and not for anything else ls -l prints.
Then quote the file name when changing permissions (chmod ... "$file"), in case it has spaces.


text:
Q: Null Hypothesis formulation from a "Fewer than" statement The aim of this exercise is to translate statements into Null and Alternative Hypotheses.
The example statement is: "Fewer than 5% of adults ride the bus to work in Los Angeles."
My Answer was : 0: ≤0.05;: >0.05.

*

*Given that 0 always has a symbol of =, ≤, or ≥.

*Given that  always has a symbol of >, <, ≠.

However, the correct answer is : 0: =0.05;: <0.05

*

*Why is the 0 statement 0: =0.05 and not : >0.05 ?

*Why is the  statement : <0.05 and not : >0.05 ?

A:
"Fewer than 5% of adults ride the bus to work in Los Angeles."

The null hypothesis to be verified is the complement: $H_0\geq 5\%$
To set up a test, we expect that the data contraddict this Hypothesis, i.e. sample mean is $4\%$. The test is performed to tell us if actually $4<5$ or the difference has to be attributed to the phenomena's variability.
The system is the following
$$\begin{cases}
H_0: p\geq 5\%\\
H_1: p<5\%
\end{cases}$$
This is a good answer and correct too.
For some reasons that should be clear to you, the previous Hypothesis System is equivalent to the following one
$$\begin{cases}
H_0: p= 5\%\\
H_1: p<5\%
\end{cases}$$


text:
Q: Как создать recommend system на основании обратной связи от пользователя? Задача: У меня есть список шаблонов емейлов, скажем их 100 штук.
Эти емейлы мы предлагаем пользователю. В свою очередь, он может выбрать один шаблон и отправить своему клиенту. В клиента тоже есть ряд признаков (например, город, стать, доход и т. д... )
Если клиент отвечает на шаблон, то мы говорим, что шаблон достиг цели. Если нет - не достиг.
Я хочу создать рекомендательный алгоритм, который будет рекомендовать шаблон на основании обратной связи от клиента (считаем что обратная связь позитивная, если клиент открыл емейл) и профиля клиента по ряду признаков, т. е. чем больше таких же клиентов отвечают на шаблон, тем более он популярный для данной группы клиентов.
Вот пример данных:

email_template_id - id отправленного емейла в БД
Answered? - ответил ли клиент на емейл или нет
Пот пример выходных данных

Где Recommended emails - рекомендованый список емейлов в подядке приоритета
Какие алгоритмы ML помогут достичь этой цели?
Буду благодарен за любые рекомендации
Спасибо


text:
Q: 2 bounder buffers shared with pthread calls, mutex locks and busy waiting I am generally new to C so I have loads of syntax errors and referencing problems. I have written prodcons.c, a Struct that will create a bounded buffer of size 50 and a few helper variables. In main I create a variable of this data struct and initialize it. I am attempting to take any amount of arguments (IE {1..1000}) lets say into the thousands and PUSH these into the buffer, while at the same time another C file producer.c is attempting to POP from the same buffer that I shared to it with a thread call. PUSH and POP both have a mutex lock to stop any changes to the critical section at the same time. Producer thread will then initialize another data struct, take the prime factors of each argument from main in their shared buffer, share a new initialized data struct with a Consumer.c function call in a thread. Consumer simply prints the number and its prime factors.
I believe I have to have #include prodcons.h in all of my files to use its functions, but please correct me if I am wrong.
Also, I am trying to create BUSY WAITNG, with main and producer each attempt to get to the critical section with while loops, calling POP and PUSH, but this is most likely wrong.
PLEASE HELP, ADVICE, SYNTAX. ANYTHING.
I honestly have tried to just compile the code, but my referencing and pointers and any correct way in C to share files and pointer calls to the data structure are off. I think I just need a lot of corrections.
Such as when using a struct pointer do I use pc->function() or pc.function()? These small syntax errors have got me stuck.
I am sharing everything by consumer.h and consumer.c because figure out the problems in main and producer then consumer I can figure out.
'''prodcons.h
#include <pthread.h>
#define BUFFER_SIZE (50)

struct prodcons {
        int buffer[BUFFER_SIZE];
        int count;
        int top;
        int next;
        pthread_mutex_t count_lock;
};

void pc_init(struct prodcons *pc);
int pc_pop(struct prodcons *pc);
void pc_push(struct prodcons *pc, int val);
'''

'''prodcons.c

void pc_init(struct prodcons *pc)
{
        count = 0;
        top = 0;
        next = 0;
}

int pc_pop(struct prodcons *pc)
{
        int val;
        pthread_mutex_lock(&pc.count_lock);

        if (counter > top)
        {
                val = pc.buffer[count];
                pc.buffer[count] = 0;
                pc.count--;
        }

        pthread_mutex_unlock(&pc.count_lock);
        return val;
}

void pc_push(struct prodcons *pc, int val)
{
        pthread_mutex_lock(&pc.count_lock);

        if (count < BUFFER_SIZE)
        {
                pc.buffer[count] = val;
                pc.count++;
        }

        pthread_mutex_unlock(&pc.count_lock);
}

'''main.c file

#include <pthread.h>
#include <stdlib.h>
#include <math.h>
#include "producer.h"
#include "prodcons.h"

int main(int argc, char *argv[])

{
        int index = 1;
        int num;
        struct prodcons pc_nums;

        //pthread_t tid[argc - 1];
        pthread_t tid;
        pthread_attr_t attr;

        if (argc <  2) {
                fprintf(stderr, "usage: No arguments\n");
                return -1;
        }
        if (atoi(argv[1]) <= 0)
        {
                fprintf(stderr, "%d not > 0 or you must provide a positive integer.\n", atoi(argv[1]));
                return -1;
        }

        /*get the default attributes */
        pthread_attr_init(&attr);

        //init the data structure
        pc_init(&pc_nums);

        //create producer thread
        pthread_create(&tid, &attr, *producer, &pc_nums);

        while (index < argc)
        {
                num = atoi(argv[index]);
                pc_push(&pc_nums, num);
                index++;
        }
}

'''producer.h
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <math.h>
#include "consumer.h"

void factor2pc(struct prodcons *pc, int number);
void *producer(void *data);

'''producer.c
#include <math.h>
#include <pthread.h>

void factor2pc(struct prodcons *pc, int number) {

        pthread_t tid;
        pthread_attr_t attr;
        //int counter = 0;

        //Add original value to int* primeNumbers for return printing
        pc->pc_push(&pc, number);

        //Print twos that divide argument
        while (number % 2 == 0)
        {
                pc->pc_push(&pc, 2);
                number = number/2;
        }

        //Argument is odd. Check using i + 2
        for (int i = 3; i <= sqrt(number); i = i + 2)
        {
                while (number % i == 0)
                {
                        pc->pc_push(&pc, i);
                        number = number/i;
                }
        }

        //When n is a prime number greater than 2
        if (number > 2)
        {
                pc->pc_push(&pc, number);
        }

        //add -1 to end of number prime factors to sign
        pc->pc_push(&pc, number);
}

void *producer(void *data) {

        int number;
        struct prodcons primeNums;
        pc_init(&primeNums);

        //call consumer thread
        pthread_t tid;
        pthread_attr_t attr;
        pthread_create(&tid, attr, *consumer, &primeNums);

        while (data.count < BUFFER_SIZE)
        {
                number = data.pc_pop(data);
                factor2pc(&primeNums, number);
        }
}

I expect an output each number and its prime numbers.


text:
Q: One line arrow functions without braces - can't have a semicolon? I'm new to React and ES6 syntax, and something I found interesting was that if I write:
return <input onChange={event => console.log(event.target.value);} />;

This will not work. I get a "Cannot find module" error.
But if I remove the semicolon in the arrow function:
return <input onChange={event => console.log(event.target.value)} />;

It works just fine. And if I kept the semicolon but added braces, as so:
return <input onChange={event => { console.log(event.target.value); }} />;

This works too. What is the reason for the first example above not working?

A: To properly understand why this is the case, let's make sure we know the difference between an expression, and a block.
At the most basic level, an expression is a bit of code that represents a value of some sort. So 123, a + b + c, calculateSomething(), these are all expressions. Expressions don't include semicolons in them.
A block in JS is a list of statements. These statements are surrounded by curly braces { }, and separated by semicolons.
Quite often, statements consist of an expression followed by a semicolon. So,
a = b + c;

is a statement. There are other kinds of statements: let, var, for, while, return, etc.
Now, back to the arrow function. An arrow function can come in two forms:
(some, args) => <an expression>
(some, args) => { <a statement>; <a statement>; ... }

Note the first form takes an expression, a single one. There should only be semicolons if you're using a block, like in the second form.
JSX works like this:
<input onChange={ <an expression> } />

You put the name of the prop you want, an equal sign, then a single expression in braces. Remember, single expressions don't have semicolons.
An arrow function is an expression. So, if you were to put a semicolon here...
<input onChange={ () => 'hello' ; } />

JS will see the expression, then see the semicolon after it and crash, because it's not supposed to be there.


text:
Q: Using react-bootstrap Alert in map not working I am trying to use the Alert component in react-boostrap using a map in the same way the do in this guide. I want to have this list as a component so that I can use it in several places. For this, I created an interface that looks like this:
import { ReactElement } from "react";
import { Variant } from "react-bootstrap/types";

export interface AlertItem {
    content: string | ReactElement;
    index: number;
    variant?: Variant
    header?: string;
}

In the components where I want to be able to display alerts as a list, I (dynamically) create an AlertItem[] array and a function that removes the AlertItem at index "i". I then try to display the list of alerts using <AlertList alerts={alerts} closeAlertCallback={closeAlert} />.
So my AlertList looks like this:
import { ReactElement } from "react";
import { Alert } from "react-bootstrap";
import { AlertItem } from "../interfaces/AlertItem";

interface Props {
    alerts: AlertItem[];
    closeAlertCallback: (index: number) => void;
}

const AlertList = ({alerts, closeAlertCallback}: Props): ReactElement => {
    if (alerts.length === 0) {
        return <></>;
    }

    return (
        <>
            {alerts.map((alert, i) => {
                <Alert key={`alert-${i}`} variant={alert.variant} onClose={() => closeAlertCallback(i)} dismissible>
                    {alert.header && <Alert.Heading>{alert.header}</Alert.Heading>}
                    {alert.content}
                </Alert>
            })}
        </>
    );
};

export default AlertList;

My problem is that this does not render at all. If I instead remove the map and always only render (and remove) the first item in the array, it renders that item just fine. The return then looks like this:
    return (
        <>
            <Alert variant={alerts[0].variant} onClose={() => closeAlertCallback(0)} dismissible>
                {alerts[0].header && <Alert.Heading>{alerts[0].header}</Alert.Heading>}
                {alerts[0].content}
            </Alert>
        </>
    );

Note that it is the only change in the file. The incoming alerts array and the closeAlertCallback is exactly the same. I can even remove the first alert in the array by clicking the X, which then renders the next alert.
I am at a total loss about what I'm doing wrong. I'm probably missing something obvious, or is just a bit blind and don't see the error.
Can someone else spot my mistake?

A: I think you are missing the 'return' inside the map function
return (
        <>
            {alerts.map((alert, i) => { return
                <Alert key={`alert-${i}`} variant={alert.variant} onClose={() => closeAlertCallback(i)} dismissible>
                    {alert.header && <Alert.Heading>{alert.header}</Alert.Heading>}
                    {alert.content}
                </Alert>
            })}
        </>
    );


text:
Q: Is CSRF safe at all? Lot of people talk about implementing CSRF to stop cross site attacks on a webpage. But i think it is pretty easy to compromise CSRF and make requests to a server.
So how it works ?

*

*You start with a page, render a form and keep a hidden field with CSRF token.

*When form is submitted the other page will expect CSRF token in order to validate the request.

*While validating the request, server will check CSRF token with a secret to see if token is valid.

*Now the secret itself is stored in session or cookie.

Which means if i go to a website, copy the CSRF token from the webpage, and session value from browser network tab. After this i can construct a CURL request, set these values and make as many requests as i can.
So what is the need of CSRF at all ?

A: The scenario you define is not CSRF.
Your scenario
Alice goes to Bob's website. Alice gets a cookie from Bob's website. Alice uses that data to make a request that she designed to Bob's website.
This is fine. Everything going on here is between Alice and Bob.
If Bob can't trust Alice to send good data, then that is a different problem entirely.
CSRF scenario
Alice goes to Bob's website. Alice gets a cookie from Bob's website. Alice goes to Mallery's website. Mallery's website triggers a form submission to Bob's website. Bob accepts the data because it came from Alice's browser with Alice's cookie.
i.e. Mallery's site is forging a request from Alice to Bob's site.
The anti-CSRF token is designed to prevent Mallery from making the request through Alice's browser (because Mallery can't get the token to put in the form data, so can't match the token in the cookie).


text:
Q: Simple PHP counter - how to print numbers with loop? How can I print out the numbers from 0 to 20 with a loop in PHP?
I hope some one can help.
Thanks!

A: You want a for loop:
http://php.net/manual/en/control-structures.for.php

A: Use a for loop:
for ($i = 0; $i <= 20; $i++)
{
    echo $i . "\n";
}


text:
Q: Comparing data in two mysql database I have two mysql database. I have to compare column data of one table in the first database with the column data of the second database. In both databases , table name and column names are same. I have to find the common data.  The column is a varchar field. But the problem is "newyork times" and "times newyork" and "newyork" should be considered as common. I am not able to generate the sql query. This is the procedure i have tried
drop procedure if exists test;
delimiter #
create procedure test()
begin

declare v_max int unsigned default 243;
declare v_counter int unsigned default 1;
declare pName varchar(255);

start transaction;
while v_counter < v_max do
select t.property_name from t.property where t.property_id=v_counter into pName;
SELECT distinct b.property.property_name,b.property.property_id from b.property where    b.property.property_name like '%'+pName+'%'
set v_counter=v_counter+1;
end while;
commit;
end #

delimiter ;

Is it possible to compare likewise?

A: It's not possible to tell MySQL to do such a vague comparison. It can't know which of the following should be considered "the same"

*

*newyork times

*new york times

*t

*york

If you have a limited number of "mistakes", you could normalise them in the lookup
WHERE t.property_name = REPLACE(v.property_name, 'new york times', 'new york')

But of course that very quickly becomes unmanageable.
Can you add a new column, even temporarily?  Then you could do some sort of cleansing of the data in a set of pre-passes.
UPDATE t
SET cleanpropertyname = 'new york times'
WHERE property_name IN ('new york times', 'new york', 'nyt')


text:
Q: Chessboard Java script advice need I need to optymalise my chessboard code (JS) to avoid  soo many lines of copied code for the same chess piece like pawn, and other pieces.
I need to create better data structure i think , but i dont have good idea how to iterate my data structure to locate all pieces on the board.This  is codepen link for this project.
For example this is my function to place knight piece on the board.
   function addKnight() {
        //piece create function
        var KnightFirst = oneKnight[8];
        var KnightSecond = oneKnight[15];
        var KnightThird = oneKnight[48];
        var KnightFour = oneKnight[55];

        pieceKnight1 = document.createElement("i");
        pieceKnight1.classList.add("fas");
        pieceKnight1.classList.add("fa-chess-knight");
        pieceKnight2 = document.createElement("i");
        pieceKnight2.classList.add("fas");
        pieceKnight2.classList.add("fa-chess-knight");
        pieceKnight3 = document.createElement("i");
        pieceKnight3.classList.add("fas");
        pieceKnight3.classList.add("fa-chess-knight");
        pieceKnight4 = document.createElement("i");
        pieceKnight4.classList.add("fas");
        pieceKnight4.classList.add("fa-chess-knight");

        KnightFirst.appendChild(pieceKnight1);
        KnightSecond.appendChild(pieceKnight2);
        pieceKnight2.classList.add("color");
        KnightThird.appendChild(pieceKnight3);
        KnightFour.appendChild(pieceKnight4);
        pieceKnight4.classList.add("color");

   }

A: I would do something like this. It isn't a complete code but just the structure.
var piece = {
    x, y,
    type,
    color,
    sprite: new Image(),

}
var pieces = [];

function addPieces () {

    if (i < 16) {
    for (let i = 0; i < 32; i++) {
        for (let j = 0; j < 16; j++) {
            pieces.push(piece);
            pieces[i].type = "pawn";

            if (j < 4) {
                //set position for white pawns
            } else {
                //set position for black pawns
            }
        } }

        if (i >= 16 && i < 20) {
        for (let j = 0; j < 4; j++) {
            pieces.push(piece);
            pieces[i].type = "knight";

            if (j < 2) {
                //set position for white knights
            } else {
                //set position for black knights
            }
        }}
        if (i >= 20 && i < 24) {
        for (let j = 0; j < 4; j++) {
            pieces.push(piece);
            pieces[i].type = "rook";

            if (j < 2) {
                //set position for white rooks
            } else {
                //set position for black rooks
            }
        }}

        if (i >= 24 && i < 28) {
        for (let j = 0; j < 4; j++) {
            pieces.push(piece);
            pieces[i].type = "bishop";

            if (j < 2) {
                //set position for white bishops
            } else {
                //set position for black bishops
            }
        }}

        if (i >= 28 && i < 30) {
        for (let j = 0; j < 2; j++) {
            pieces.push(piece);
            pieces[i].type = "queen";

            if (j < 1) {
                //set position for white queen
            } else {
                //set position for black queen
            }
        }}

        if (i >= 30 && i < 32) {
        for (let j = 0; j < 2; j++) {
            pieces.push(piece);
            pieces[i].type = "king";

            if (j < 1) {
                //set position for white king
            } else {
                //set position for black king
            }
        }    }
    }
}

You could apply the same type of function for the update each frame, but that's your call. Hope this helps!


text:
Q: Capitalize first letters in words in the string with different separators using java 8 stream I need to capitalize first letter in every word in the string, BUT it's not so easy as it seems to be as the word is considered to be any sequence of letters, digits, "_" , "-", "`" while all other chars are considered to be separators, i.e. after them the next letter must be capitalized.
Example what program should do:
For input: "#he&llo wo!r^ld"
Output should be: "#He&Llo Wo!R^Ld"
There are questions that sound similar here, but there solutions really don't help.
This one for example:
String output = Arrays.stream(input.split("[\\s&]+"))
                    .map(t -> t.substring(0, 1).toUpperCase() + t.substring(1))
                    .collect(Collectors.joining(" "));

As in my task there can be various separators, this solution doesn't work.

A: It is possible to split a string and keep the delimiters, so taking into account the requirement for delimiters:

word is considered to be any sequence of letters, digits, "_" , "-", "`" while all other chars are considered to be separators

the pattern which keeps the delimiters in the result array would be: "((?<=[^-`\\w])|(?=[^-`\\w]))":
[^-`\\w]: all characters except -, backtick and word characters \w: [A-Za-z0-9_]
Then, the "words" are capitalized, and delimiters are kept as is:
static String capitalize(String input) {
    if (null == input || 0 == input.length()) {
        return input;
    }
    return Arrays.stream(input.split("((?<=[^-`\\w])|(?=[^-`\\w]))"))
                 .map(s -> s.matches("[-`\\w]+") ? Character.toUpperCase(s.charAt(0)) + s.substring(1) : s)
                 .collect(Collectors.joining(""));
}

Tests:
System.out.println(capitalize("#he&l_lo-wo!r^ld"));
System.out.println(capitalize("#`he`&l+lo wo!r^ld"));

Output:
#He&l_lo-wo!R^Ld
#`he`&L+Lo Wo!R^Ld

Update
If it is needed to process not only ASCII set of characters but apply to other alphabets or character sets (e.g. Cyrillic, Greek, etc.), POSIX class \\p{IsWord} may be used and matching of Unicode characters needs to be enabled using pattern flag (?U):
static String capitalizeUnicode(String input) {
    if (null == input || 0 == input.length()) {
        return input;
    }

    return Arrays.stream(input.split("(?U)((?<=[^-`\\p{IsWord}])|(?=[^-`\\p{IsWord}]))")
                 .map(s -> s.matches("(?U)[-`\\p{IsWord}]+") ? Character.toUpperCase(s.charAt(0)) + s.substring(1) : s)
                 .collect(Collectors.joining(""));
}

Test:
System.out.println(capitalizeUnicode("#he&l_lo-wo!r^ld"));
System.out.println(capitalizeUnicode("#привет&`ёж`+дос^βιδ/ως"));

Output:
#He&L_lo-wo!R^Ld
#Привет&`ёж`+Дос^Βιδ/Ως

A: You can't use split that easily - split will eliminate the separators and give you only the things in between. As you need the separators, no can do.
One real dirty trick is to use something called 'lookahead'. That argument you pass to split is a regular expression. Most 'characters' in a regexp have the property that they consume the matching input. If you do input.split("\\s+") then that doesn't 'just' split on whitespace, it also consumes them: The whitespace is no longer part of the individual entries in your string array.
However, consider ^ and $. or \\b. These still match things but don't consume anything. You don't consume 'end of string'. In fact, ^^^hello$$$ matches the string "hello" just as well. You can do this yourself, using lookahead: It matches when the lookahead is there but does not consume it:
String[] args = "Hello World$Huh   Weird".split("(?=[\\s_$-]+)");
for (String arg : args) System.out.println("*" + args[i] + "*");

Unfortunately, this 'works', in that it saves your separators, but isn't getting you all that much closer to a solution:
*Hello*
* World*
*$Huh*
* *
* *
* Weird*

You can go with lookbehind as well, but it's limited; they don't do variable length, for example.
The conclusion should rapidly become: Actually, doing this with split is a mistake.
Then, once split is off the table, you should no longer use streams, either: Streams don't do well once you need to know stuff about the previous element in a stream to do the job: A stream of characters doesn't work, as you need to know if the previous character was a non-letter or not.
In general, "I want to do X, and use Y" is a mistake. Keep an open mind. It's akin to asking: "I want to butter my toast, and use a hammer to do it". Oookaaaaayyyy, you can probably do that, but, eh, why? There are butter knives right there in the drawer, just.. put down the hammer, that's toast. Not a nail.
Same here.
A simple loop can take care of this, no problem:
private static final String BREAK_CHARS = "&-_`";

public String toTitleCase(String input) {
  StringBuilder out = new StringBuilder();
  boolean atBreak = true;
  for (char c : input.toCharArray()) {
    out.append(atBreak ? Character.toUpperCase(c) : c);
    atBreak = Character.isWhitespace(c) || (BREAK_CHARS.indexOf(c) > -1);
  }
  return out.toString();
}

Simple. Efficient. Easy to read. Easy to modify. For example, if you want to go with 'any non-letter counts', trivial: atBreak = Character.isLetter(c);.
Contrast to the stream solution which is fragile, weird, far less efficient, and requires a regexp that needs half a page's worth of comment for anybody to understand it.
Can you do this with streams? Yes. You can butter toast with a hammer, too. Doesn't make it a good idea though. Put down the hammer!

A: You can use a simple FSM as you iterate over the characters in the string, with two states, either in a word, or not in a word. If you are not in a word and the next character is a letter, convert it to upper case, otherwise, if it is not a letter or if you are already in a word, simply copy it unmodified.
boolean isWord(int c) {
    return c == '`' || c == '_' || c == '-' || Character.isLetter(c) || Character.isDigit(c);
}

String capitalize(String s) {
    StringBuilder sb = new StringBuilder();
    boolean inWord = false;
    for (int c : s.codePoints().toArray()) {
        if (!inWord && Character.isLetter(c)) {
            sb.appendCodePoint(Character.toUpperCase(c));
        } else {
            sb.appendCodePoint(c);
        }
        inWord = isWord(c);
    }
    return sb.toString();
}

Note: I have used codePoints(), appendCodePoint(int), and int so that characters outside the basic multilingual plane (with code points greater than 64k) are handled correctly.

A:
I need to capitalize first letter in every word

Here is one way to do it.  Admittedly this is a might longer but your requirement to change the first letter to upper case (not first digit or first non-letter) required a helper method.  Otherwise it would have been easier.  Some others seemed to have missed this point.
Establish word pattern, and test data.
String wordPattern = "[\\w_-`]+";
Pattern p = Pattern.compile(wordPattern);
String[] inputData = { "#he&llo wo!r^ld", "0hel`lo-w0rld" };

Now this simply finds each successive word in the string based on the established regular expression.  As each word is found, it changes the first letter in the word to upper case and then puts it in a string buffer in the correct position where the match was found.
for (String input : inputData) {
    StringBuilder sb = new StringBuilder(input);
    Matcher m = p.matcher(input);
    while (m.find()) {
        sb.replace(m.start(), m.end(),
                upperFirstLetter(m.group()));
    }
    System.out.println(input + " -> " + sb);
}

prints
#he&llo wo!r^ld -> #He&Llo Wo!R^Ld
0hel`lo-w0rld -> 0Hel`lo-W0rld

Since words may start with digits, and the requirement was to convert the first letter (not character) to upper case. This method finds the first letter, converts it to upper case and
returns the new string.  So 01_hello would become 01_Hello

public static String upperFirstLetter(String word) {
    char[] chs = word.toCharArray();
    for (int i = 0; i < chs.length; i++) {
        if (Character.isLetter(chs[i])) {
            chs[i] = Character.toUpperCase(chs[i]);
            break;
        }
    }
    return String.valueOf(chs);
}


text:
Q: Diagonalizing quadratic forms I know how to diagonalize a given quadratic form using the Gaussian method. Though, I once read somewhere that there's another method which uses an augmented matrix, but I didn't go into details.
I would like to know about this method, perhaps by a simple example.
Say: $q: \mathbb R^2 \to \mathbb R$, $q(x,y) = xy - y^2$.
How would I use that method to diagonalize $q$?
Thank you.

A: $$ xy - y^2 = \left( \frac{x}{2} \right)^2 -  \left( \frac{x}{2} - y \right)^2  $$
see Transforming quadratic forms, how is this theorem called?


text:
Q: What do I need in my query, perhaps NOT EXISTS or NOT IN? I have a table called review:
review_id   cat_id   public_or_private
1           1              0
11          2              2
12          3              1
13          4              2
14          5              2

And a table called category:
cat_id   user_id
1        10298
2        10299
3        10300
4        10299
5        10298

My statement:
$sql2 = "SELECT *
        FROM review
            INNER JOIN category ON review.cat_id = category.cat_id
        WHERE review.public_or_private = 2";

This will give me the result:
review_id   cat_id   public_or_private   cat_id   user_id
    11          2              2           2        10299
    13          4              2           4        10299
    14          5              2           5        10298

contacts table:
user_id    contact_id
10299       10298
10299       10300
10300       10298
10300       10301

How can I hone this further? : I only want results if user_id is not in the contact_id column of the contacts table.
So from user 10300 point of view the result should be:
review_id   cat_id   public_or_private   cat_id   user_id
    11          2              2           2        10299
    13          4              2           4        10299

I believe I should be using NOT EXISTS or NOT IN but not sure how I should put it.

A: I think this is what you want:
SELECT *
        FROM review
            INNER JOIN category ON review.cat_id = category.cat_id
            LEFT JOIN contacts ON contacts.user_id = category.user_id
        WHERE review.public_or_private = 2
        AND contacts.contact_id IS NULL

And here an example to support that statement: http://www.sqlfiddle.com/#!9/7bfb62/3
This also works:
SELECT *
        FROM review
            INNER JOIN category ON review.cat_id = category.cat_id
        WHERE review.public_or_private = 2
        AND NOT EXISTS(
            SELECT *
            FROM contacts
            WHERE contacts.user_id = category.user_id
       );

And here is updated fiddle: http://www.sqlfiddle.com/#!9/7bfb62/5


text:
Q: unsupported protocol: The client and server don't support a common SSL protocol version or cipher suite I am trying to use Cloudflare SSL with my Azure app on a small basic service plan.
I have the SSL set to Flexible in the Cloudflare Crypto tab. The status is Active Certificate.
In the Cloudflare DNS tab I have the orange cloud for the A record and CName record for my domain.
A   mywebsite.com.au    points to XX.XX.XXX.XXX

CNAME  www  is an alias of mywebsite.azurewebsites.net

In Azure Custom Host Names I have a binding for www.mywebsite.com.au and mywebsite.com.au
when I go to https://www.mywebsite.com.au I get an error
unsupported protocol: The client and server don't support a common SSL protocol version or cipher suite.

I also get the error for https://mywebsite.com.au/
If I switch the orange cloud to a grey cloud for the www CName record in CloudFlare, then I get a different error
Your connection is not private
This server could not prove that it is www.mywebsite.com.au; its security certificate is from *.azurewebsites.net. This may be caused by a misconfiguration or an attacker intercepting your connection.

HTTPS Only is Set to OFF in the Azure Custom Host Names.
If I set the A record cloud in CloudFlare to Orange then
https://mywebsite.com.au/  reports ERR_SSL_VERSION_OR_CIPHER_MISMATCH
If I set it to grey (DNS Only) then the website shows with the https crossed out and the words Not Secure
[Update]
After clearing the chrome cache and waiting some time both
mywebsite.com.au and https:\mywebsite.com.au started to work with the orange cloud on the a record in cloudflare DNS
I had used dig with trace which showed the CloudFlare Name servers indicating that my change of the DNS to Cloudflare had gone through earlier.
The other thing I had done was to delete the www CName from CloudFlare DNS and www.mywebsite.com.au from the Azure Custom Host Names.
I have since been able to get the www working using the cname flattening work around given in Stephen Cleary's answer to this question