问:
Delete last 3 characters if they are equal to something
(without affecting the char level formatting in the cell)

I've already posted a similar question, but I unfortunately I realized I couldn't use any of the solutions because all of them removed all the formatting in the cells :(

I have a code that replaces various text strings. It looks like this (+ some more IFs):

```<code>Sub Fix()
  Dim X As Long, Cell As Range
  For Each Cell In Selection
    For X = Len(Cell.Text) To 1 Step -1
      If Cell.Characters(X, 3).Text = ", ," Then Cell.Characters(X, 3).Text = ","
      If Cell.Characters(X, 3).Text = ", (" Then Cell.Characters(X, 3).Text = " ("
      If Cell.Characters(X, 3).Text = ", [" Then Cell.Characters(X, 3).Text = " ["
      If Cell.Characters(X, 3).Text = ", -" Then Cell.Characters(X, 3).Text = " -"
      If Cell.Characters(1, 3).Text = "abc" Then Cell.Characters(1, 3).Text = ""
    Next
  Next
End Sub
</code>```

The last line of my code deletes abc if this is contained at the beginning of the selected cell(s).

I am looking to find out how to delete abc when this is contained at the end of the selected cell(s).

But it's really important for me to preserve all the original formatting in the cells (text size, colors, bold/italic/underline letters etc).

Please bear in mind that I am a complete beginner and I don't know anything about programming. I've copied the code above from the internet and just changed the values.

Thank you in advance for your help.

答:
If you want to remove the last three characters of a cell if they are abc, then:

Before:

the code:

```<code>Sub EasyAsABC()
    Dim s As String, L As Long
    With ActiveCell
        s = .Text
        L = Len(s)
        If Right(s, 3) = "abc" Then
            .Characters(L, 1).Text = ""
            .Characters(L - 1, 1).Text = ""
            .Characters(L - 2, 1).Text = ""
        End If
    End With
End Sub
</code>```

and after:

Body:
(without affecting the char level formatting in the cell)

I've already posted a similar question, but I unfortunately I realized I couldn't use any of the solutions because all of them removed all the formatting in the cells :(

I have a code that replaces various text strings. It looks like this (+ some more IFs):

Sub Fix()
  Dim X As Long, Cell As Range
  For Each Cell In Selection
    For X = Len(Cell.Text) To 1 Step -1
      If Cell.Characters(X, 3).Text = ", ," Then Cell.Characters(X, 3).Text = ","
      If Cell.Characters(X, 3).Text = ", (" Then Cell.Characters(X, 3).Text = " ("
      If Cell.Characters(X, 3).Text = ", [" Then Cell.Characters(X, 3).Text = " ["
      If Cell.Characters(X, 3).Text = ", -" Then Cell.Characters(X, 3).Text = " -"
      If Cell.Characters(1, 3).Text = "abc" Then Cell.Characters(1, 3).Text = ""
    Next
  Next
End Sub

The last line of my code deletes abc if this is contained at the beginning of the selected cell(s).

I am looking to find out how to delete abc when this is contained at the end of the selected cell(s).

But it's really important for me to preserve all the original formatting in the cells (text size, colors, bold/italic/underline letters etc).

Please bear in mind that I am a complete beginner and I don't know anything about programming. I've copied the code above from the internet and just changed the values.

Thank you in advance for your help.

Body:
If you want to remove the last three characters of a cell if they are abc, then:

Before:

the code:

Sub EasyAsABC()
    Dim s As String, L As Long
    With ActiveCell
        s = .Text
        L = Len(s)
        If Right(s, 3) = "abc" Then
            .Characters(L, 1).Text = ""
            .Characters(L - 1, 1).Text = ""
            .Characters(L - 2, 1).Text = ""
        End If
    End With
End Sub

and after:


来源: stackexchange

问:
Convert timestamp data to date time in Python
I have a DataFrame with a column containing timestamps and I would like to convert the column to date time in Python and save the file with a column containing the date and time. Here is the code:</p>

```<code>
    import pandas as pd
    df = pd.DataFrame({
        "time": [1465585763000, 1465586363000, 1465586963000,
                  1465587563000, 1465588163000]})
    df

</code>```

答:
This could also work</p>

```<code>import pandas as pd
from datetime import datetime as dt
d = {'time': [1465585763000, 1465586363000, 1465586963000,
              1465587563000, 1465588163000]}

print(d['time'])
new = [dt.fromtimestamp(x/1000).strftime('%Y-%m-%d %H:%M:%S') for x in d['time']]
pd.to_datetime(new)

</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a DataFrame with a column containing timestamps and I would like to convert the column to date time in Python and save the file with a column containing the date and time. Here is the code:

    import pandas as pd
    df = pd.DataFrame({
        "time": [1465585763000, 1465586363000, 1465586963000,
                  1465587563000, 1465588163000]})
    df

Body:
This could also work

import pandas as pd
from datetime import datetime as dt
d = {'time': [1465585763000, 1465586363000, 1465586963000,
              1465587563000, 1465588163000]}

print(d['time'])
new = [dt.fromtimestamp(x/1000).strftime('%Y-%m-%d %H:%M:%S') for x in d['time']]
pd.to_datetime(new)


问:
Can I use shouldInterceptRequest to block a particular call in Android?
I used the following code

```<code>public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
    alertsavedinternal(); //display an alert
    Log.d("DEBUG", "Should intercept request" +url);
    //log the url to console in debug mode.
    return null;
}
</code>```

However, while the alert is displayed my console also prints the log, besides which the url is also loaded in the background. How can I stop the url from loading?

Please correct my understanding of this function.

Thanks

答:
If you return null in shouldInterceptRequest, it means that the WebView will continue to load the resource as usual.

This is why you see the URL still being loaded.

In order to intercept and block the call, you need to return your own (Non-null) data instead.

ContentLicense: CC BY-SA 3.0

Body:
I used the following code

public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
    alertsavedinternal(); //display an alert
    Log.d("DEBUG", "Should intercept request" +url);
    //log the url to console in debug mode.
    return null;
}

However, while the alert is displayed my console also prints the log, besides which the url is also loaded in the background. How can I stop the url from loading?

Please correct my understanding of this function.

Thanks


问:
Count in records in xml with condition using XSLT
HI I am creating an XSLT file for transforming XML. I want to count records with condition

```<code><Body>
    <BankAccountTable class="entity">
      <AccountNum>123456789</AccountNum>
      <BankChequeTable class="entity">
        <AccountID>101</AccountID>
        <AmountCur>40.00</AmountCur>
        <ChequeStatus>Payment</ChequeStatus>
        <VendTable class="entity">
          <AccountNum>1</AccountNum>
        </VendTable>
      </BankChequeTable>
      <BankChequeTable class="entity">
        <AccountID>101</AccountID>
        <AmountCur>45.00</AmountCur>
        <ChequeStatus>Payment</ChequeStatus>
        <VendTable class="entity">
          <AccountNum>2</AccountNum>
        </VendTable>
      </BankChequeTable>
      <BankChequeTable class="entity">
        <AccountID>101</AccountID>
        <AmountCur>45.00</AmountCur>
        <ChequeStatus>Void</ChequeStatus>
        <VendTable class="entity">
          <AccountNum>2</AccountNum>
        </VendTable>
      </BankChequeTable>
    </BankAccountTable>
</code>```

Now i want to count BankAccountTable records where ChequeStatus must equals to Payment can any one suggest how to achieve this. I am using Xsl:stylesheet version="1.0".
I am able to count all record by using this line of code:

```<code><xsl:for-each select="/BankAccountTable"> <xsl:variable name="totalCount" select="count(child::BankChequeTable)"></xsl:variable>
</code>```

but I want it with condition. for following example count must be equals to 2.

Any help will be appreciated.

Thanks

答:
You can count the records like this:

```<code><xsl:variable name="totalCount" select="count(Body/BankAccountTable/BankChequeTable[ChequeStatus='Payment'])"/>
</code>```

See it working here: https://xsltfiddle.liberty-development.net/naZYrpt

Body:
HI I am creating an XSLT file for transforming XML. I want to count records with condition

    <BankAccountTable class="entity">
      <AccountNum>123456789</AccountNum>
      <BankChequeTable class="entity">
        <AccountID>101</AccountID>
        <AmountCur>40.00</AmountCur>
        <ChequeStatus>Payment</ChequeStatus>
        <VendTable class="entity">
          <AccountNum>1</AccountNum>
        </VendTable>
      </BankChequeTable>
      <BankChequeTable class="entity">
        <AccountID>101</AccountID>
        <AmountCur>45.00</AmountCur>
        <ChequeStatus>Payment</ChequeStatus>
        <VendTable class="entity">
          <AccountNum>2</AccountNum>
        </VendTable>
      </BankChequeTable>
      <BankChequeTable class="entity">
        <AccountID>101</AccountID>
        <AmountCur>45.00</AmountCur>
        <ChequeStatus>Void</ChequeStatus>
        <VendTable class="entity">
          <AccountNum>2</AccountNum>
        </VendTable>
      </BankChequeTable>
    </BankAccountTable>

Now i want to count BankAccountTable records where ChequeStatus must equals to Payment can any one suggest how to achieve this. I am using Xsl:stylesheet version="1.0".
I am able to count all record by using this line of code:

<xsl:for-each select="/BankAccountTable"> <xsl:variable name="totalCount" select="count(child::BankChequeTable)"></xsl:variable>

but I want it with condition. for following example count must be equals to 2.

Any help will be appreciated.

Thanks

Body:
You can count the records like this:

<xsl:variable name="totalCount" select="count(Body/BankAccountTable/BankChequeTable[ChequeStatus='Payment'])"/>

See it working here: https://xsltfiddle.liberty-development.net/naZYrpt


问:
Google web fonts and SSL error
My site is working well with Google webfonts UNTIL the user hits the SSL portion of the site.

At that point, chrome throws the partial encoding error, and my cufon menu losses it's kerning.

I'm including my webfont with this css:

```<code>@font-face {
src: local('Lusitana'), url(https://themes.googleusercontent.com/static/fonts/lusitana
/v1/tAIvAkRzqMJf8Y4fM1R7PXYhjbSpvc47ee6xR_80Hnw.woff) format('woff');
}
</code>```

My js console then gives me this error:

[blocked] The page at https://domain.com/ecommerce.php ran insecure content from
  http://fonts.googleapis.com/css?family=Lusitana:regular,700&subset=latin.

Any ideas how I can get google fonts to force SSL?

答:
I also had this error caused by a theme in WordPress. It caused slow page loading and the following error reported by development console:

Mixed Content: The page at 'https://xxxxxxx.co.uk/' was loaded over HTTPS, but requested an insecure stylesheet 'http://fonts.googleapis.com/css?
family=Droid+Serif%3A400%2C700%2C400italic%2C700italic&ver=5.4.1'. This
request has been blocked; the content must be served over HTTPS.

The culprit was Wordpress theme called "Fresh and Clean".  It inherits code written in 2014 which contains 'pre-SSL' coding practices

To resolve the problem all need to do is make changes inside the following file in the theme:

/wp-content/themes/wpex-freshandclean/functions/scripts.php

Look inside for any occurences of http://  and change each one to https://

Title: Google web fonts and SSL error

Body:
My site is working well with Google webfonts UNTIL the user hits the SSL portion of the site.

At that point, chrome throws the partial encoding error, and my cufon menu losses it's kerning.

I'm including my webfont with this css:

@font-face {
src: local('Lusitana'), url(https://themes.googleusercontent.com/static/fonts/lusitana
/v1/tAIvAkRzqMJf8Y4fM1R7PXYhjbSpvc47ee6xR_80Hnw.woff) format('woff');
}

My js console then gives me this error:

[blocked] The page at https://domain.com/ecommerce.php ran insecure content from
  http://fonts.googleapis.com/css?family=Lusitana:regular,700&subset=latin.

Any ideas how I can get google fonts to force SSL?


问:
Qt: Storing a custom object in a collection by value
Let's say I have this class:

```<code>class Bear
{
public:
    Bear ();
    Bear (Bear &other);

    // ... methods

private:
    BearInfo* m_pInfo;
};
</code>```

Can I store Bear objects in a QList<Bear> by value?  According to the documentation:

Internally, QList<T> is represented as an array of pointers to items of type T. If T is itself a
  pointer type or a basic type that is no larger than a pointer, or if T is one of Qt's shared
  classes, then QList<T> stores the items directly in the pointer array.

While my class just consists of a pointer, it is neither a pointer type nor a basic type, so it seems to me that the QList will store pointers (Bear*), which is not what I want. And since the BearInfo structure must be mutable, I cannot derive Bear from QSharedDataPointer.

Any suggestions how I can enable this class to be stored by value in the Qt collections?

答:
just use an stl container, it's available everywhere, even in QT.

its what i do. :)

Body:
Let's say I have this class:

class Bear
{
public:
    Bear ();
    Bear (Bear &other);

    // ... methods

private:
    BearInfo* m_pInfo;
};

Can I store Bear objects in a QList<Bear> by value?  According to the documentation:

Internally, QList<T> is represented as an array of pointers to items of type T. If T is itself a
  pointer type or a basic type that is no larger than a pointer, or if T is one of Qt's shared
  classes, then QList<T> stores the items directly in the pointer array.

While my class just consists of a pointer, it is neither a pointer type nor a basic type, so it seems to me that the QList will store pointers (Bear*), which is not what I want. And since the BearInfo structure must be mutable, I cannot derive Bear from QSharedDataPointer.

Any suggestions how I can enable this class to be stored by value in the Qt collections?


问:
Python write XML data from API to SQL Server (using parse to .csv as intermediate hop)
python novice here.

Trying to pull data from API and insert into SQL Server table (existing) for use in BI tool.

Original result from API is XML with a terribly unfriendly-for-a-novice format.

I have managed to parse this (likely not in the most pythonic way and open to suggestions) to .csv format (3 separate files due to nature of nested XML).  Now that I have these in .csv I am trying to write them to my SQL-Server tables, one table per .csv but have hit a snag.  I am using the code from this answer and all seems okay other than the leading comma that gets created in the column names section of the query.  Anyone help me remove that leading comma?

This is the code as I have written currently:

```<code>import json
import requests
import pandas as pd
import csv
from pandas.io.json import json_normalize
from datetime import date, timedelta

url = "https://**myAPI_URL.com/Transaction"

paramHeader = '{"Version": "1.0"'
paramHeader += ', "FromDate":"2020-05-01 00:00"'
paramHeader += ', "ToDate": "2020-05-31 00:00"'
paramHeader += ', "MerchantOrgID": null'
paramHeader += ', "CardholderOrgID": null'
paramHeader += ', "CardNumber": null'
paramHeader += ', "DriverID": null'
paramHeader += ', "VehicleID": null'
paramHeader += ', "BillingGroupID": null'
paramHeader += ', "BillingCycleID": null'
paramHeader += ', "EntryMethodID": null'
paramHeader += ', "CardTypeID": null'
paramHeader += ', "TranTypeID": null'
paramHeader += ', "TaxExemptOnly": null}'

headers = {'APIKey': '**myAPI_KEY**'
    , 'content-type': 'application/json'
    , 'Accept': 'application/json'
    , 'parameters': paramHeader}

response = requests.get(url, data='', headers=headers)
if response.status_code == 200:
    r = json.loads(response.content.decode('utf-8'))

    cleanData = pd.json_normalize(r)

    transactionDetails = pd.json_normalize(data=r, record_path='Details', meta=['ID'])

    taxes = pd.json_normalize(data=r, record_path=['Details', 'Taxes'],
                                 meta=['ID'])

    cleanData.to_csv('**filePath**/mainTransactions.csv')
    transactionDetails.to_csv('**filePath**/transactionsDetails.csv')
    taxes.to_csv('**filePath/transactionsTaxes.csv')

    import pyodbc
    connection = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=**serverIP**;PORT=1433;DATABASE=myDBName;UID=myUserID;PWD=myPWord;')

    with open('**filePath**/transactionsDetails.csv', 'r') as f:
        reader = csv.reader(f)
        columns = next(reader)
        query = 'insert into transactionDetails({0}) values ({1})'
        query = query.format(','.join(columns), ','.join('?' * (int(len(columns)))))
        print(query)   #for debug purposes
        cursor = connection.cursor()
        for data in reader:
            cursor.execute(query, data)
        cursor.commit()
</code>```

This code results in the following error:

```<code>insert into transactionDetails(,RowNumber,RawProductCode,RawUnitPrice,RawAmount,Quantity,ResolvedProductID,ProductCategoryID,ProductCategory,IsFuel,ProductName,ProductCode,IsTaxProduct,ResolvedUnitPrice,ResolvedAmount,Taxes,ID) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
Traceback (most recent call last):
  File "**workingDirectory**/myProject.py", line 85, in <module>
    cursor.execute(query, data)
pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Incorrect syntax near ','. (102) (SQLExecDirectW)")

Process finished with exit code 1
</code>```

Manually executing the same query (using all 1's as test data) after removing the leading comma results in a successful write to DB.

```<code>myTableName> insert into transactionDetails(RowNumber,RawProductCode,RawUnitPrice,RawAmount,Quantity,ResolvedProductID,ProductCategoryID,ProductCategory,IsFuel,ProductName,ProductCode,IsTaxProduct,ResolvedUnitPrice,ResolvedAmount,Taxes,ID) values (1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1)
[2020-05-28 20:08:55] 1 row affected in 188 ms
</code>```

Thanks!

答:
The leading comma is just inserted because the first element from your columns resolves to an empty string somehow. If this is consistent you can just account for it by slicing the columns:

# Just take the slice starting from the 1st element
# Also, no need to use int(len()), len() already returns an integer.
query = query.format(','.join(columns[1:]), ','.join('?' * len(columns[1:])))
```

<p>An even simpler way to perform the above is to first perform the slice when getting the columns for the first time.</p>

<pre class="lang-py prettyprint-override"><code>columns = next(reader)[1:]
query = 'insert into transactionDetails({0}) values ({0})'
query = query.format(','.join(columns), ','.join('?' * len(columns)))
</code>```

Some additional Python tips

Don't structure your paramHeader by concatenating a bunch of strings. It's very messy and dangerous (prone to typos). The content is supposed to be a json object, so simply make a dictionary and use the json module to output a properly formatted json object:

```<code>>>> import json
>>> my_json = {
... "this": 123,
... "that": "string"
... }
>>> json.dumps(my_json)
'{"this": 123, "that": "string"}'
</code>```

dumps stands for "dump string".

Body:
python novice here.

Trying to pull data from API and insert into SQL Server table (existing) for use in BI tool.

Original result from API is XML with a terribly unfriendly-for-a-novice format.

I have managed to parse this (likely not in the most pythonic way and open to suggestions) to .csv format (3 separate files due to nature of nested XML).  Now that I have these in .csv I am trying to write them to my SQL-Server tables, one table per .csv but have hit a snag.  I am using the code from this answer and all seems okay other than the leading comma that gets created in the column names section of the query.  Anyone help me remove that leading comma?

This is the code as I have written currently:

import json
import requests
import pandas as pd
import csv
from pandas.io.json import json_normalize
from datetime import date, timedelta

url = "https://**myAPI_URL.com/Transaction"

paramHeader = '{"Version": "1.0"'
paramHeader += ', "FromDate":"2020-05-01 00:00"'
paramHeader += ', "ToDate": "2020-05-31 00:00"'
paramHeader += ', "MerchantOrgID": null'
paramHeader += ', "CardholderOrgID": null'
paramHeader += ', "CardNumber": null'
paramHeader += ', "DriverID": null'
paramHeader += ', "VehicleID": null'
paramHeader += ', "BillingGroupID": null'
paramHeader += ', "BillingCycleID": null'
paramHeader += ', "EntryMethodID": null'
paramHeader += ', "CardTypeID": null'
paramHeader += ', "TranTypeID": null'
paramHeader += ', "TaxExemptOnly": null}'

headers = {'APIKey': '**myAPI_KEY**'
    , 'content-type': 'application/json'
    , 'Accept': 'application/json'
    , 'parameters': paramHeader}

response = requests.get(url, data='', headers=headers)
if response.status_code == 200:
    r = json.loads(response.content.decode('utf-8'))

    cleanData = pd.json_normalize(r)

    transactionDetails = pd.json_normalize(data=r, record_path='Details', meta=['ID'])

    taxes = pd.json_normalize(data=r, record_path=['Details', 'Taxes'],
                                 meta=['ID'])

    cleanData.to_csv('**filePath**/mainTransactions.csv')
    transactionDetails.to_csv('**filePath**/transactionsDetails.csv')
    taxes.to_csv('**filePath/transactionsTaxes.csv')

    import pyodbc
    connection = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=**serverIP**;PORT=1433;DATABASE=myDBName;UID=myUserID;PWD=myPWord;')

    with open('**filePath**/transactionsDetails.csv', 'r') as f:
        reader = csv.reader(f)
        columns = next(reader)
        query = 'insert into transactionDetails({0}) values ({1})'
        query = query.format(','.join(columns), ','.join('?' * (int(len(columns)))))
        print(query)   #for debug purposes
        cursor = connection.cursor()
        for data in reader:
            cursor.execute(query, data)
        cursor.commit()

This code results in the following error:

insert into transactionDetails(,RowNumber,RawProductCode,RawUnitPrice,RawAmount,Quantity,ResolvedProductID,ProductCategoryID,ProductCategory,IsFuel,ProductName,ProductCode,IsTaxProduct,ResolvedUnitPrice,ResolvedAmount,Taxes,ID) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
Traceback (most recent call last):
  File "**workingDirectory**/myProject.py", line 85, in <module>
    cursor.execute(query, data)
pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Incorrect syntax near ','. (102) (SQLExecDirectW)")

Process finished with exit code 1

Manually executing the same query (using all 1's as test data) after removing the leading comma results in a successful write to DB.

myTableName> insert into transactionDetails(RowNumber,RawProductCode,RawUnitPrice,RawAmount,Quantity,ResolvedProductID,ProductCategoryID,ProductCategory,IsFuel,ProductName,ProductCode,IsTaxProduct,ResolvedUnitPrice,ResolvedAmount,Taxes,ID) values (1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1)
[2020-05-28 20:08:55] 1 row affected in 188 ms

Thanks!

Body:
The leading comma is just inserted because the first element from your columns resolves to an empty string somehow. If this is consistent you can just account for it by slicing the columns:

# Just take the slice starting from the 1st element
# Also, no need to use int(len()), len() already returns an integer.
query = query.format(','.join(columns[1:]), ','.join('?' * len(columns[1:])))

An even simpler way to perform the above is to first perform the slice when getting the columns for the first time.

columns = next(reader)[1:]
query = 'insert into transactionDetails({0}) values ({0})'
query = query.format(','.join(columns), ','.join('?' * len(columns)))

Some additional Python tips

Don't structure your paramHeader by concatenating a bunch of strings. It's very messy and dangerous (prone to typos). The content is supposed to be a json object, so simply make a dictionary and use the json module to output a properly formatted json object:

>>> import json
>>> my_json = {
... "this": 123,
... "that": "string"
... }
>>> json.dumps(my_json)
'{"this": 123, "that": "string"}'

dumps stands for "dump string".


问:
Import Mathmatical equation and image from docx file using PHP DOMDocument::loadXML
I want to import in the data from the docx file to my CRM, I am using PHP DOMDocument::loadXML method for it, but I am not able to find a way through which I can import the Mathmatical formula and the images from the document file.
The Image of the word file is

The code through which I am trying to import is

```<code>    <?php
    $questionSheetRecord= readDocx("demo-stack.docx");
    echo "```";
    print_r($questionSheetRecord);
    echo "```";

    function readDocx($filePath) {
        // Create new ZIP archive
        $zip = new ZipArchive;
        $dataFile = 'word/document.xml';
        // Open received archive file
        $returnArray=array();
        if (true === $zip->open($filePath)) {
            // If done, search for the data file in the archive
            if (($index = $zip->locateName($dataFile)) !== false) {
                // If found, read it to the string
                $data = $zip->getFromIndex($index);
                // Close archive file
                $zip->close();
                // Load XML from a string
                // Skip errors and warnings
                $xml = DOMDocument::loadXML($data, LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING);
                // Return data without XML formatting tags

                foreach($xml->getElementsByTagName('p') as $child) {
                    $returnArray[]=  $child->nodeValue;
                }

                $text = $xml->saveXML();

                return $returnArray;
            }
            $zip->close();
        }
        // In case of failure return empty string
        return "";
    }
    ?>
</code>```

`
Link of word file is
Word File to import data
and link of code is Code Link

The output that I am getting while running this code is

  I want these a :  along with their post formula and picture.

I have gone through the other questions asked relating this issue but they are not the proper solution for this question.

Thank you

答:
Please go through the "update-v1.1.php" and "demo.docx" file. Here you can get a code for extracting images from the word file, But the drawback in this code is that if you want to add any image in the word file then you have to add a tag "IMG1", here IMG has a post value of the sequence of the image, like if this is the first image in the word file then the tag will be IMG1 and if it is the sixth image then it will be IMG6. When you will run the code you will get the array which you can use in any why you want.

If anyone find any better solution please inform me here only.

Also I am searching a solution of exporting data into word with images at any specified place (means in-between text sentences, I want to insert 1 or more than one images).

Body:
I want to import in the data from the docx file to my CRM, I am using PHP DOMDocument::loadXML method for it, but I am not able to find a way through which I can import the Mathmatical formula and the images from the document file.
The Image of the word file is

The code through which I am trying to import is

    <?php
    $questionSheetRecord= readDocx("demo-stack.docx");
    echo "
";
    print_r($questionSheetRecord);
    echo "
";

    function readDocx($filePath) {
        // Create new ZIP archive
        $zip = new ZipArchive;
        $dataFile = 'word/document.xml';
        // Open received archive file
        $returnArray=array();
        if (true === $zip->open($filePath)) {
            // If done, search for the data file in the archive
            if (($index = $zip->locateName($dataFile)) !== false) {
                // If found, read it to the string
                $data = $zip->getFromIndex($index);
                // Close archive file
                $zip->close();
                // Load XML from a string
                // Skip errors and warnings
                $xml = DOMDocument::loadXML($data, LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING);
                // Return data without XML formatting tags

                foreach($xml->getElementsByTagName('p') as $child) {
                    $returnArray[]=  $child->nodeValue;
                }

                $text = $xml->saveXML();

                return $returnArray;
            }
            $zip->close();
        }
        // In case of failure return empty string
        return "";
    }
    ?>

`
Link of word file is
Word File to import data
and link of code is Code Link

The output that I am getting while running this code is

  I want these a :  along with their post formula and picture.

I have gone through the other questions asked relating this issue but they are not the proper solution for this question.

Thank you


问:
Axios GET request resulting in CORS error
I'm working on a VueJS app, and I want to use the Yahoo! Shopping API (documentation: https://developer.yahoo.co.jp/webapi/shopping/shopping/v1/itemsearch.html) to fetch products using their barcode. However, I keep getting a CORS error and I'm not sure why, or what I can do to make it work. My code is as follows:

```<code>data() {
  return {
    appId: 'dj00aiZpPUQ4RTBUUTVSNUs3TyZzPWNvbnN1bWVyc2VjcmV0Jng9NTI-',
    apiUrl: 'https://shopping.yahooapis.jp/ShoppingWebService/V1/json/itemSearch'
  }
}

...

axios.get(this.apiUrl, {
  params: {
    appid: this.appId,
    jan: 4589707054951
  }
})
.then((response) => {
  console.log(response);
})
.catch((error) => {
  alert(error)
})
</code>```

The specific error I get is this:

Access to XMLHttpRequest at
  'https://shopping.yahooapis.jp/ShoppingWebService/V1/json/itemSearch?appid=dj00aiZpPUQ4RTBUUTVSNUs3TyZzPWNvbnN1bWVyc2VjcmV0Jng9NTI-&jan=4589707054951'
  from origin 'https://0.0.0.0:8080' has been blocked by CORS policy: No
  'Access-Control-Allow-Origin' header is present on the requested
  resource.

What can I do to make this work? So far the only way it works is using the CORS Chrome extension, but that's naturally just for testing.

Thanks a lot.

答:
I got the same error. I solved it in the following manner.

This error occurs because we are tryign to access the data hosted on a different server. CORS issue is a browser issue where a certain browser does allow you to access the contents hosted on a different or a virtual server. If you observe the app that you are running on is on the local-host (https://0.0.0.0:8080) and trying to access the data hosted on https://shopping.yahooapis.jp/ShoppingWebService/V1/json/itemSearch. You can solve this problem simply by adding in a few lines of code in your vue application.

Step 1:
Create a new file called vue.config.js in your root directory of the vue application, that is beside your package.json file. Add the following code in your vue.config.js file:

```<code>module.exports = {
   devServer:{
   proxy: "https://shopping.yahooapis.jp"
  }
}
</code>```

Note: https://shopping.yahooapis.jp would be your base url.

Step 2:
Now, go back to your code in data(). Replace the domain name/base url of the apiUrl with https://0.0.0.0:8080. that is now your apiUrl would be https://0.0.0.0:8080/ShoppingWebService/V1/json/itemSearch.

```<code>data() {
  return {
    appId: 'dj00aiZpPUQ4RTBUUTVSNUs3TyZzPWNvbnN1bWVyc2VjcmV0Jng9NTI-',
    apiUrl: 'https://0.0.0.0:8080/ShoppingWebService/V1/json/itemSearch'
  }
}
</code>```

Step 3:
Restart your application. Eg, npm run serve.

Body:
I'm working on a VueJS app, and I want to use the Yahoo! Shopping API (documentation: https://developer.yahoo.co.jp/webapi/shopping/shopping/v1/itemsearch.html) to fetch products using their barcode. However, I keep getting a CORS error and I'm not sure why, or what I can do to make it work. My code is as follows:

data() {
  return {
    appId: 'dj00aiZpPUQ4RTBUUTVSNUs3TyZzPWNvbnN1bWVyc2VjcmV0Jng9NTI-',
    apiUrl: 'https://shopping.yahooapis.jp/ShoppingWebService/V1/json/itemSearch'
  }
}

...

axios.get(this.apiUrl, {
  params: {
    appid: this.appId,
    jan: 4589707054951
  }
})
.then((response) => {
  console.log(response);
})
.catch((error) => {
  alert(error)
})

The specific error I get is this:

Access to XMLHttpRequest at
  'https://shopping.yahooapis.jp/ShoppingWebService/V1/json/itemSearch?appid=dj00aiZpPUQ4RTBUUTVSNUs3TyZzPWNvbnN1bWVyc2VjcmV0Jng9NTI-&jan=4589707054951'
  from origin 'https://0.0.0.0:8080' has been blocked by CORS policy: No
  'Access-Control-Allow-Origin' header is present on the requested
  resource.

What can I do to make this work? So far the only way it works is using the CORS Chrome extension, but that's naturally just for testing.

Thanks a lot.

Body:
I got the same error. I solved it in the following manner.

This error occurs because we are tryign to access the data hosted on a different server. CORS issue is a browser issue where a certain browser does allow you to access the contents hosted on a different or a virtual server. If you observe the app that you are running on is on the local-host (https://0.0.0.0:8080) and trying to access the data hosted on https://shopping.yahooapis.jp/ShoppingWebService/V1/json/itemSearch. You can solve this problem simply by adding in a few lines of code in your vue application.

Step 1:
Create a new file called vue.config.js in your root directory of the vue application, that is beside your package.json file. Add the following code in your vue.config.js file:

module.exports = {
   devServer:{
   proxy: "https://shopping.yahooapis.jp"
  }
}

Note: https://shopping.yahooapis.jp would be your base url.

Step 2:
Now, go back to your code in data(). Replace the domain name/base url of the apiUrl with https://0.0.0.0:8080. that is now your apiUrl would be https://0.0.0.0:8080/ShoppingWebService/V1/json/itemSearch.

data() {
  return {
    appId: 'dj00aiZpPUQ4RTBUUTVSNUs3TyZzPWNvbnN1bWVyc2VjcmV0Jng9NTI-',
    apiUrl: 'https://0.0.0.0:8080/ShoppingWebService/V1/json/itemSearch'
  }
}

Step 3:
Restart your application. Eg, npm run serve.


问:
How to push to another repository which is below to another tenant by CI
How to push to another repository which is below to another tenant by CI?
We have to release code to our customers. They also use Azure devops. Is it possible to do it by CI?</p>

答:
I used "Git mirror" to solve my problem. And I used PAT.</p>

```<code># Starter pipeline
# Start with a minimal pipeline that you can customize to build and deploy your code.
# Add steps that build, run tests, deploy, and more:
# https://aka.ms/yaml
trigger:
- master
pool:
  vmImage: 'ubuntu-latest'
steps:
- script: |
     cd /tmp && rm -rf /tmp/$(TmpRepoDir)
     git -c http.extraheader="AUTHORIZATION: bearer $(System.AccessToken)" clone --mirror $(Build.Repository.Uri) $(TmpRepoDir)
     git -C /tmp/$(TmpRepoDir) push --mirror https://{anything}:{PTA}/{organization}/{project name}/_git/{repository name}
  displayName: 'Copy to GitLab'
</code>```

Body:
I used "Git mirror" to solve my problem. And I used PAT.

# Starter pipeline
# Start with a minimal pipeline that you can customize to build and deploy your code.
# Add steps that build, run tests, deploy, and more:
# https://aka.ms/yaml
trigger:
- master
pool:
  vmImage: 'ubuntu-latest'
steps:
- script: |
     cd /tmp && rm -rf /tmp/$(TmpRepoDir)
     git -c http.extraheader="AUTHORIZATION: bearer $(System.AccessToken)" clone --mirror $(Build.Repository.Uri) $(TmpRepoDir)
     git -C /tmp/$(TmpRepoDir) push --mirror https://{anything}:{PTA}/{organization}/{project name}/_git/{repository name}
  displayName: 'Copy to GitLab'


问:
How would one go about defining an event in an interface?
I want my ICanTarget interface to have an event such as "OnTarget" that fires with a gameObject argument, every time it acquires a target. This can be AI Targeting or PlayerTargeting, hence the interface.

I want my combat script to respond to the targeting event coming from whatever ICanTarget component it has. Any Ideas?

答:
```<code>public interface ICanTarget
{
    event System.Action<GameObject> OnTarget;
}
</code>```


问:
docker push with local notary server returns error: x509: certificate signed by unknown authority
I have been working at setting up a docker notary on a Centos 8 machine. I followed the README.md for the notary project which tells me to use the testing certificate the project
comes with by moving it to the .notary folder in my home directory. My hope here is that when my docker client is setup for it and when I properly tag the image a docker push to my private docker repo (jFrog Artifactory) would result in a published image that is signed by the notary.

My private repo is running on its own machine and not on the machine where the notary server is running.

But every time I go for the push I get this error:

```<code>Signing and pushing trust metadata
Error: error contacting notary server: x509: certificate signed by unknown authority
</code>```

One of the ways I tried to fix this is by copying over the test certificates from fixtures/root-ca.crt to /etc/pki/ca-trust/source/anchors/ after which I ran update-ca-trust.

```<code>$ sudo cp fixtures/root-ca.crt /etc/pki/ca-trust/source/anchors/
$ update-ca-trust
</code>```

But doing this also didn't help. Why is the notary server throwing this error? Help to resolve this would be greatly appreciated.

答:
I haven’t had issues working on Azure container registry.
Working on Jfrog registry, I had same error

Your work around helped me
“
$ sudo cp fixtures/root-ca.crt /etc/pki/ca-trust/source/anchors/
$ update-ca-trust
“
If it helps I can post my steps
Thanks @RijoSimon

Body:
I have been working at setting up a docker notary on a Centos 8 machine. I followed the README.md for the notary project which tells me to use the testing certificate the project
comes with by moving it to the .notary folder in my home directory. My hope here is that when my docker client is setup for it and when I properly tag the image a docker push to my private docker repo (jFrog Artifactory) would result in a published image that is signed by the notary.

My private repo is running on its own machine and not on the machine where the notary server is running.

But every time I go for the push I get this error:

Signing and pushing trust metadata
Error: error contacting notary server: x509: certificate signed by unknown authority

One of the ways I tried to fix this is by copying over the test certificates from fixtures/root-ca.crt to /etc/pki/ca-trust/source/anchors/ after which I ran update-ca-trust.

$ sudo cp fixtures/root-ca.crt /etc/pki/ca-trust/source/anchors/
$ update-ca-trust

But doing this also didn't help. Why is the notary server throwing this error? Help to resolve this would be greatly appreciated.


问:
Logic App - initialize variable from JSON Content
I am new to Logic APP and was wondering how to parse Json attributes . In other words
passing the below Jason to a queue (the values will change as we send different Json to the queue)

```<code>[
  {
     "name":"test",
     "country":"USA"

  }
]
</code>```

I am trying to get name & country

Here are the steps I took

then I added JSON parse Action ( not sure if this is the right action)

then ( I am just trying to get the attributes name & country)

Then I get error

答:
For this requirement, please refer to the steps I provided below:

1. I initialize a variable named "myData" first to simulate your json data.

2. To get the value of the name and country, we just do as below:

The expressions for name and country are:

```<code>variables('myData')[0]?['name']
variables('myData')[0]?['country']
</code>```

As your logic app starts with the "When a message is received in a queue(peek-lock)" trigger, it seems your json data comes from the trigger. So you need to change the expression to something like:

```<code>triggerBody()[0]?['name']
</code>```

If your json data doesn't come from the trigger(service bus message), please let me know and provide more details, or you can click "Peek code" to see its expression and then modify your expression in initialize variable action.

Update:

It seems we can not parse the "content" from the trigger directly, you can initialize a variable to store the "content" from the queue trigger and use "Parse JSON" action to parse this "content" variable.

Body:
I am new to Logic APP and was wondering how to parse Json attributes . In other words
passing the below Jason to a queue (the values will change as we send different Json to the queue)

[
  {
     "name":"test",
     "country":"USA"

  }
]

I am trying to get name & country

Here are the steps I took

then I added JSON parse Action ( not sure if this is the right action)

then ( I am just trying to get the attributes name & country)

Then I get error

Body:
For this requirement, please refer to the steps I provided below:

1. I initialize a variable named "myData" first to simulate your json data.

2. To get the value of the name and country, we just do as below:

The expressions for name and country are:

variables('myData')[0]?['name']
variables('myData')[0]?['country']

As your logic app starts with the "When a message is received in a queue(peek-lock)" trigger, it seems your json data comes from the trigger. So you need to change the expression to something like:

triggerBody()[0]?['name']

If your json data doesn't come from the trigger(service bus message), please let me know and provide more details, or you can click "Peek code" to see its expression and then modify your expression in initialize variable action.

Update:

It seems we can not parse the "content" from the trigger directly, you can initialize a variable to store the "content" from the queue trigger and use "Parse JSON" action to parse this "content" variable.


问:
python + script failed regarding to cryptography under /usr/lib64/python2.7
I create the following python script

this python script will read the file /lpp/airflow/.sec/rmq_pass to var - pass_hash

and will decrypt it to decrypted_pass

```<code>more security_test.py
import sys
import os
import base64
from cryptography.fernet import Fernet

key_file = "/lpp/airflow/.sec/key"
rmq_pass_file = "/lpp/airflow/.sec/rmq_pass"

key = open(key_file, 'r')
f = Fernet(key.read())

pass_hash  = open(rmq_pass_file, 'r')
#decrypting the password from "pass_file" file using the key from the "key_file".
decrypted_pass = f.decrypt(pass_hash.read())
ConnStr = "amqp://airflow:" + decrypted_pass  + "@localhost:5672//"
</code>```

when I run the script
its failed on /usr/lib64/python2.7/site-packages/cryptography/fernet.py , or any under /usr/lib64/python2.7/site-packages/cryptography

we try to re-install the package cryptography , but this didn't help

and idea what is could be ?

```<code>python  security_test.py
Traceback (most recent call last):
  File "security_test.py", line 14, in <module>
    decrypted_pass = f.decrypt(pass_hash.read())
  File "/usr/lib64/python2.7/site-packages/cryptography/fernet.py", line 75, in decrypt
    return self._decrypt_data(data, timestamp, ttl)
  File "/usr/lib64/python2.7/site-packages/cryptography/fernet.py", line 117, in _decrypt_data
    self._verify_signature(data)
  File "/usr/lib64/python2.7/site-packages/cryptography/fernet.py", line 101, in _verify_signature
    h = HMAC(self._signing_key, hashes.SHA256(), backend=self._backend)
  File "/usr/lib64/python2.7/site-packages/cryptography/hazmat/primitives/hmac.py", line 31, in __init__
    self._ctx = self._backend.create_hmac_ctx(key, self.algorithm)
  File "/usr/lib64/python2.7/site-packages/cryptography/hazmat/backends/openssl/backend.py", line 207, in create_hmac_ctx
    return _HMACContext(self, key, algorithm)
  File "/usr/lib64/python2.7/site-packages/cryptography/hazmat/backends/openssl/hmac.py", line 34, in __init__
    key_ptr = self._backend._ffi.from_buffer(key)
TypeError: from_buffer() cannot return the address of the raw string within a str or unicode or bytearray object
</code>```

IMPORTANT NOTE - on other machine this script is working fine

what is the best way to resolve it ? by remove all modules and install them again ? or by re-install python ?

答: If this was installed by pip, then this issue is due to having an out-of-date cffi package (I was able to reproduce this problem by force-installing cffi 1.5 in a virtualenv). Newer versions of cryptography require cffi >= 1.8, but pip does not always resolve that properly (depending on a variety of other scenarios). You can pip install -U cffi to see if that resolves it, but in general you should strongly consider running Python code inside of a virtualenv and not installing packages into the global package space. The OS package manager assumes that it owns global packages and you can cause many issues with your install if you mix and match distribution packages with pip installs.

Body:
I create the following python script

this python script will read the file /lpp/airflow/.sec/rmq_pass to var - pass_hash

and will decrypt it to decrypted_pass

more security_test.py
import sys
import os
import base64
from cryptography.fernet import Fernet

key_file = "/lpp/airflow/.sec/key"
rmq_pass_file = "/lpp/airflow/.sec/rmq_pass"

key = open(key_file, 'r')
f = Fernet(key.read())

pass_hash  = open(rmq_pass_file, 'r')
#decrypting the password from "pass_file" file using the key from the "key_file".
decrypted_pass = f.decrypt(pass_hash.read())
ConnStr = "amqp://airflow:" + decrypted_pass  + "@localhost:5672//"

when I run the script
its failed on /usr/lib64/python2.7/site-packages/cryptography/fernet.py , or any under /usr/lib64/python2.7/site-packages/cryptography

we try to re-install the package cryptography , but this didn't help

and idea what is could be ?

python  security_test.py
Traceback (most recent call last):
  File "security_test.py", line 14, in <module>
    decrypted_pass = f.decrypt(pass_hash.read())
  File "/usr/lib64/python2.7/site-packages/cryptography/fernet.py", line 75, in decrypt
    return self._decrypt_data(data, timestamp, ttl)
  File "/usr/lib64/python2.7/site-packages/cryptography/fernet.py", line 117, in _decrypt_data
    self._verify_signature(data)
  File "/usr/lib64/python2.7/site-packages/cryptography/fernet.py", line 101, in _verify_signature
    h = HMAC(self._signing_key, hashes.SHA256(), backend=self._backend)
  File "/usr/lib64/python2.7/site-packages/cryptography/hazmat/primitives/hmac.py", line 31, in __init__
    self._ctx = self._backend.create_hmac_ctx(key, self.algorithm)
  File "/usr/lib64/python2.7/site-packages/cryptography/hazmat/backends/openssl/backend.py", line 207, in create_hmac_ctx
    return _HMACContext(self, key, algorithm)
  File "/usr/lib64/python2.7/site-packages/cryptography/hazmat/backends/openssl/hmac.py", line 34, in __init__
    key_ptr = self._backend._ffi.from_buffer(key)
TypeError: from_buffer() cannot return the address of the raw string within a str or unicode or bytearray object

IMPORTANT NOTE - on other machine this script is working fine

what is the best way to resolve it ? by remove all modules and install them again ? or by re-install python ?


问:
Redirecting old permalink structure to the new one
I had a wordpress site installed in a sub folder with category/post-title permalink structure, which resulted in the following url structure

http://www.mysite.com/subfolder/category/post-title

However as I needed to move my site to the root folder and changed the permalink structure to year/month/post-title, which looks like below, users who visit my website through the links published on other websites see 404 error page as expected.

http://www.mysite.com/year/month/post-title

While doing the changes, moving wordpress to the root directory and changing permalink structure, I forgot to take into account that such problem could occur. Anyway, I made a mistake and now I'm trying to fix the problem.

I wonder is there a way to redirect the old urls to the new ones? Editing .htaccess or using a plugin or something else. The method doesn't matter at this stage. All I want is to solve the problem

Any help?
Thanks in advance.

答: If you're using Apache, mod_alias or mod_rewrite should be the way to go. If you're using IIS, you'll need different solutions based upon whether you're on IIS 6.x or IIS 7.x.</p>


问:
How to Avoid Copying whole Values of a vector to the other container
How do I avoid copying whole values of vector kws into req_kws (the vector of vectors) below, while keeping two containers kws and req_kws in my code?

```<code> vector<vector<string>> req_kws;
 for (string& request : requests) {
    vector<string>& kws = req_kws.back(); //<-- define &kws to empty req_kws
    kws = split(kwsStr, ",");   //split is a parsing function upon string kwsStr
    req_kws.push_back(kws);
 }
</code>```

I used in line number 3

```<code>vector<string>& kws = req_kws.back();
</code>```

In this way, instead of storing all values of kws vector, only its reference is stored into req_kws.

But, I am getting a segmentation fault during the runtime.  Is there a way to fix it?

Thank you for your help.

Additional note;

Please note my constraint stated above that I need to keep both line number 4 (kws) and 5 (req_kws) intact, and want to use line number 3 of reference (&) or something similar to save the execution time from the same values being stored to both kws and req_kws. I have the other parts of the codes with the same problem, which are more complicate so that I can Not simply combine two lines of 4 and 5 into one.

Additional Question (Similar problem):

Thank you for your solution down below.  However, how about the following case, which is similar as above but more complicated.

vector<unordered_map<string, string>> ads_kwsBids;
for (const auto& kwBid : kwsBids) {
    …
    unordered_map<string, string>& kwsBidsMap = ads_kwsBids.back(); //to prevent from being whole container copied
    for (unsigned j = 0; j < nsize; j++) {
        unsigned jdx = 2 * j;
        kwsBidsMap[splitedStr[jdx]] = splitedStr[jdx + 1];// constructing map kwsBidsMap
    }
    ads_kwsBids.push_back(kwsBidsMap);
}
```

<p>In line number 4, that is,</p>

<pre class="lang-cpp prettyprint-override"><code>unordered_map<string, string>& kwsBidsMap = ads_kwsBids.back();
</code>```

Because of the reference &, it yields the segmentation fault.  But, the reference is also the one that prevents kwsBidMap from being copied into ads_kwsBids.  Is there a way still to use the reference & on kwsBidMap and not get the segmentation fault?

答:
In the code shown, req_kws is an empty vector.  Calling back() on an empty vector is Undefined Behavior. You either need to add an element to the vector first, or rewrite the code to not depend on having a value present.

From what I can gather you are trying to do, I think a simple

```<code>req_kws.push_back(split(request, ","));
</code>```

should suffice.

Alternatively, you can rewrite the loop as

```<code>for (string& request : requests) {
    req_kws.push_back(split(request, ","));
    vector<string>& kws = req_kws.back();
}
</code>```

This will split the request string, store it in the req_kws vector, then create the kws reference to that newly added element.  Depending on what else you do with it, you may need to add req_kws.reserve(requests.size()); before the for loop to avoid reallocations when adding to the vector.

Body:
How do I avoid copying whole values of vector kws into req_kws (the vector of vectors) below, while keeping two containers kws and req_kws in my code?

 vector<vector<string>> req_kws;
 for (string& request : requests) {
    vector<string>& kws = req_kws.back(); //<-- define &kws to empty req_kws
    kws = split(kwsStr, ",");   //split is a parsing function upon string kwsStr
    req_kws.push_back(kws);
 }

I used in line number 3

vector<string>& kws = req_kws.back();

In this way, instead of storing all values of kws vector, only its reference is stored into req_kws.

But, I am getting a segmentation fault during the runtime.  Is there a way to fix it?

Thank you for your help.

Additional note;

Please note my constraint stated above that I need to keep both line number 4 (kws) and 5 (req_kws) intact, and want to use line number 3 of reference (&) or something similar to save the execution time from the same values being stored to both kws and req_kws. I have the other parts of the codes with the same problem, which are more complicate so that I can Not simply combine two lines of 4 and 5 into one.

Additional Question (Similar problem):

Thank you for your solution down below.  However, how about the following case, which is similar as above but more complicated.

vector<unordered_map<string, string>> ads_kwsBids;
for (const auto& kwBid : kwsBids) {
    …
    unordered_map<string, string>& kwsBidsMap = ads_kwsBids.back(); //to prevent from being whole container copied
    for (unsigned j = 0; j < nsize; j++) {
        unsigned jdx = 2 * j;
        kwsBidsMap[splitedStr[jdx]] = splitedStr[jdx + 1];// constructing map kwsBidsMap
    }
    ads_kwsBids.push_back(kwsBidsMap);
}

In line number 4, that is,

unordered_map<string, string>& kwsBidsMap = ads_kwsBids.back();

Because of the reference &, it yields the segmentation fault.  But, the reference is also the one that prevents kwsBidMap from being copied into ads_kwsBids.  Is there a way still to use the reference & on kwsBidMap and not get the segmentation fault?

Body:
In the code shown, req_kws is an empty vector.  Calling back() on an empty vector is Undefined Behavior. You either need to add an element to the vector first, or rewrite the code to not depend on having a value present.

From what I can gather you are trying to do, I think a simple

req_kws.push_back(split(request, ","));

should suffice.

Alternatively, you can rewrite the loop as

for (string& request : requests) {
    req_kws.push_back(split(request, ","));
    vector<string>& kws = req_kws.back();
}

This will split the request string, store it in the req_kws vector, then create the kws reference to that newly added element.  Depending on what else you do with it, you may need to add req_kws.reserve(requests.size()); before the for loop to avoid reallocations when adding to the vector.


问:
Is this a good db architecture and if not what can i change about it

I found this in an old post and i'm thinking of using it for a project, but i don't know if i should change it or leave it, here's what i want to change:

remove product options and add product id and option group id to options

remove order details and have it's info in orders

is what i'm doing bad? also if you could be kind to tell me some of the best practices for something like this i would greatly appreciate it.

thanks for your time.

答:
Both tables are there for a good reason.

productoptions is a mapping table between options  and products: this is a many-to-many relationship, where a given product may have multiple options, and an option may be used by  multiple products. If you remove this table, you end up redondantly adding the optionName to each and every row in productoptions that relate to the same option, which is inefficient, and might break data integrity (how do you ensure that a given option always has the same name?).

As for order_details: this is a many to one relationship towards orders. An order may have mutliple details line, each referring to a different product. Removing this table means losing this possibility.


问:
PHP - Pregmatch help
I am trying to parse PHPIDS's XML rule list (downloadable on their site http://phpids.org/), against the entered URL using the XML's regular expressions.

Now, i know very little about regex, and i've tried looking around and i haven't found much information on it which i've found helpful.

What i'd like to do is something like this (psuedo)
if URL == regex die();

This is my latest attempt, of many:

```<code><?php
$file="default_filter.xml";
$load = simplexml_load_file($file);

$regex = $load->filter->rule;
$url = explode(" ","http://localhost/test.php");
$url2 = "http://localhost/test.php";
if(in_array($regex,$url))
{
echo "bad url";
}
if(preg_match($regex,$url2))
{
echo "bad url";
}
//The above gives me Warning: preg_match() [function.preg-match]: Unknown modifier '|' in C:\wamp\www\test.php on line 12
//Which, already i don't understand regex so i dont know why the above is a problem...
?>
</code>```

If i can get it to work, i'll loop through the rules, but for now i'm just trying 1 regex to get it working.

but i cannot figure out get the regex working.

This is the regex which is being pulled from the XML file:

```<code><rule><![CDATA[(?:"[^"]*[^-]?>)|(?:[^\w\s]\s*\/>)|(?:>")]]></rule>
</code>```

although i do not understand one bit of that...

Thanks in advance to anyone who can assit me.

答:
About the only thing I can say is the delimiters are missing. Given that the $regex contains only the regex and not the <![CDATA[ portion this should work:

```<code>if(preg_match('#'.$regex.'#',$url2))
</code>```

Give that a shot.

Title: PHP - Pregmatch help

Body:
I am trying to parse PHPIDS's XML rule list (downloadable on their site http://phpids.org/), against the entered URL using the XML's regular expressions.

Now, i know very little about regex, and i've tried looking around and i haven't found much information on it which i've found helpful.

What i'd like to do is something like this (psuedo)
if URL == regex die();

This is my latest attempt, of many:

<?php
$file="default_filter.xml";
$load = simplexml_load_file($file);

$regex = $load->filter->rule;
$url = explode(" ","http://localhost/test.php");
$url2 = "http://localhost/test.php";
if(in_array($regex,$url))
{
echo "bad url";
}
if(preg_match($regex,$url2))
{
echo "bad url";
}
//The above gives me Warning: preg_match() [function.preg-match]: Unknown modifier '|' in C:\wamp\www\test.php on line 12
//Which, already i don't understand regex so i dont know why the above is a problem...
?>

If i can get it to work, i'll loop through the rules, but for now i'm just trying 1 regex to get it working.

but i cannot figure out get the regex working.

This is the regex which is being pulled from the XML file:

<rule><![CDATA[(?:"[^"]*[^-]?>)|(?:[^\w\s]\s*\/>)|(?:>")]]></rule>

although i do not understand one bit of that...

Thanks in advance to anyone who can assit me.

Body:
About the only thing I can say is the delimiters are missing. Given that the $regex contains only the regex and not the <![CDATA[ portion this should work:

if(preg_match('#'.$regex.'#',$url2))

Give that a shot.


问:
JOOQ MySQL DATETIME Type
I'm trying to generate this simple SQL with JOOQ and for some reason I can't get it done. I want the following code to be generated for MySQL databases.

```<code>CREATE TABLE T (
    F DATETIME
);
</code>```

I expected it to be something like

```<code>dsl.createTable(name("T"))
   .column("F", MySQLDataType.DATETIME);
</code>```

Unfortunately, MySQLDataType is deprecated. JOOQ explicitly says to only use types declared in SQLDataType, but for some reason I can't find any.

I've already tried with DATE, LOCALDATE, LOCALDATETIME but all of them generate a TIMESTAMP field.

I'm using JOOQ to generate DDL for MySQL and Oracle DBMS' at the same time. Oracle types are generated fine (I get DATE and it's all right) but MySQL only gives me TIMESTAMPs.

Any hints?

答:
```<code>In jooq 3.13.2
<generator>
     <generate>
     <javaTimeTypes>false</javaTimeTypes>
     </generate>
...
</code>```

To force timestamp usage

jooq manual

Title: JOOQ MySQL DATETIME Type

Body:
I'm trying to generate this simple SQL with JOOQ and for some reason I can't get it done. I want the following code to be generated for MySQL databases.

CREATE TABLE T (
    F DATETIME
);

I expected it to be something like

dsl.createTable(name("T"))
   .column("F", MySQLDataType.DATETIME);

Unfortunately, MySQLDataType is deprecated. JOOQ explicitly says to only use types declared in SQLDataType, but for some reason I can't find any.

I've already tried with DATE, LOCALDATE, LOCALDATETIME but all of them generate a TIMESTAMP field.

I'm using JOOQ to generate DDL for MySQL and Oracle DBMS' at the same time. Oracle types are generated fine (I get DATE and it's all right) but MySQL only gives me TIMESTAMPs.

Any hints?

Body:
In jooq 3.13.2
<generator>
     <generate>
     <javaTimeTypes>false</javaTimeTypes>
     </generate>
...

To force timestamp usage

jooq manual


问:
Issue in using sqlcipher, error returned: "file is not a database"
Apologies if the solution is buried somewhere in another thread or post. I could not find anything specific to this. I’m getting [Error: file is not a database].

My scenario:

Downloaded sqlcipher to a PopOS installation. (3.15.2 //sqlcipher --version)

Was successful in creating a new encrypted database. Could open, close and see results.

Downloaded that database fie to MacOS (Catalina). (3.31.0 //sqlcipher --version)

I opened the database and entered the “PRAGMA key” statement as the first input. (Confirmation: “ok”.) However, anything I do after that results in [Error: file is not a database].

Is this different versions that is causing the issue?

答:
Had posted the above question at the following link as well:
https://discuss.zetetic.net/t/error-file-is-not-a-database/4434 (copied the response below)

"This discussion forum post should point you in the correct direction: Upgrading to SQLCipher 4 1 (https://discuss.zetetic.net/t/upgrading-to-sqlcipher-4/3283). It sounds like your database was created using SQLCipher v3 and you’re attempting to open it using SQLCipher v4. To verify this assumption is correct, you can run PRAGMA cipher_version on each side."

The above was helpful to convert a 3.4 encrypted file into a 4.x version. However, to upgrade my Linux install to 4.x, these instructions were super helpful: https://github.com/sqlitebrowser/sqlitebrowser/wiki/SQLCipher:-Build-from-Source-on-Debian-Stretch---Newbie-Instructions


问:
MySQL licensing and GPL
As far as I know, when I build a desktop/server app using any GPL code like MySQL I will have to release the source code of my software under the GPL.

If I want to develop a web-app using MySQL, my code will link against the MySQL libraries. Must I release the sourcecode of my webapp in this situation to be in accordance with the GPL?

答:
If your distribution includes and installs MySql in the same package, it requires a commercial license.

But if you only distribute your code, with a mere "requires MySql" notice and an installation script (to create/populate the tables), there should be no problem, AFAIK.

IANAL, of course.

ContentLicense: CC BY-SA 2.5

Title: MySQL licensing and GPL

LastEditorDisplayName: Roger Pate

OwnerDisplayName: Mister X


问:
Java for Iphone App Development?
I have been primarily using Java and have experience with it. I want to develop some iphone apps and wanted to know if there a way to develop iphone app using Java or iphone development can be only done using Objective-C?

Also if Objective-C is the only way to go then would really appreciate if you can recommend some books or links where I can get started on Iphone Development, my background is completely based on Java and I have not work with C or C++ professionally in the past.

Any recommendations/suggestions would highly help.

Can we have quick comparison of Objective-C vs Java or its like comparing oranges with Apple, am just trying to get some similarities in objective-c from java perspective so that I have some knowledge to leverage on while learning Objective-C, any suggestions?

答:
As far as I can tell you can't use Java for iOS development. In my opinion, the only reason to use C or C++ would be legacy/interoperability compatibility, or if you were extensively familiar with those languages. Since you're not, I'd advise biting the bullet and learning Objective C. I've just done so recently (although admittedly I come from a C background) and found it pretty straightforward.

I'd say start here, in general:

http://developer.apple.com/devcenter/ios/index.action

and here, a bit more specifically:

http://developer.apple.com/library/ios/#referencelibrary/GettingStarted/GS_iPhoneGeneral/_index.html#//apple_ref/doc/uid/TP40007853

and here, for a good hands-on runthrough:

http://developer.apple.com/library/ios/#documentation/iPhone/Conceptual/iPhone101/Articles/00_Introduction.html#//apple_ref/doc/uid/TP40007514

I know that looks like I'm just saying RTFM, but that's what I did (read through all those articles while walking through the "hello world" app) and I found it to be an effective teaching method.
And of course, use SO for any specific questions you may have.
Good luck.

Title: Java for Iphone App Development?


问:
Issues when upgrading and dockerising a Postgres v9.2 legacy database using pg_dumpall and pg_dump
I am using an official postgres v12 docker image that I want to initialise with two SQL dump files that are gathered from a remote legacy v9.2 postgres server during the docker build phase:

```<code>RUN ssh $REMOTE_USER@$REMOTE_HOST "pg_dumpall -w -U $REMOTE_DB_USER -h localhost -p $REMOTE_DB_PORT --clean --globals-only -l $REMOTE_DB_NAME" >> dump/a_globals.sql

RUN ssh $REMOTE_USER@$REMOTE_HOST "pg_dump -w -U $REMOTE_DB_USER -h localhost -p $REMOTE_DB_PORT --clean --create $REMOTE_DB_NAME" >> dump/b_db.sql
</code>```

By placing both a_globals.sql and b_db.sql files into the docker image folder docker-entrypoint-initdb.d, then the database is initialised with the legacy SQL files when the v12 container starts (as described here). Docker is working correctly, the dump files are retrieved successfully. However I am running into problems initialising the container's database and require guidance:

When the container starts to initialise its DB, it stops with ERROR:  role $someDBRole does not exist. This is because the psql v9.2 dump SQL files DROP roles before reinstating them; the container DB does not like this. Unfortunately it is not until psql v9.4 that pg_dumpall and pg_dump have the option to --if-exists (see pg_dumpall v9.2 documentation). What would you suggest that I do in order to remedy this? I could manually edit the SQL dump files, but this would be impractical as the snapshots of the legacy DB need to be automated. Is there a way to suppress this error during container startup?

If I want to convert from ASCII to UTF-8, is it adequate to simply set the encoding option for pg_dumpall and pg_dump? Or do I need to take into consideration other issues when upgrading?

Is there a way to supress the removal and adding of the postgres super user which is in the dump SQL?

In general are there any other gotchas when containerising and/or updating a postgres DB.

答:
I'm not familiar with Docker so I don't know how straightforward it'll be do to these things, but in general, pg_dump/dumpall output, when it's in SQL format, will work just fine after having gone through some ugly string manipulation.

Pipe it through sed -e 's/DROP ROLE/DROP ROLE IF EXISTS/', ideally when writing the .sqls, but it's fine to just run sed -i -e <...> to munge the files in-place after they're created if you don't have a full shell available. Make it sed -r -e '/^DROP ROLE/DROP ROLE IF EXISTS/ if you're worried about strings containing DROP ROLE in your data, at the cost of portability (AFAIK -r is a GNU addition to sed).

Yes. It's worth checking the data in pg12 to make sure it got imported correctly, but in the general case, pg_dump has been aware of encoding considerations since time immemorial, and a dump->load is absolutely the best way to change your DB encoding.

Sure. Find the lines that do it in your .sql, copy enough of it to be unique, and pipe it through grep -v <what you copied> :D

I can't speak to the containerizing aspect of things, but - and this is more of a general practice, not even really PG-specific - if you're dealing with a large DB that's getting migrated, prepare a small one, as similar as possible to the real one but omitting any bulky data, to test with to get everything working so that doing the real migration is just a matter of changing some vars (I guess $REMOtE_HOST and $REMOTE_PORT in your case). If it's not large, then just be comfortable blowing away any pg12 containers that failed partway through the import, figure out & do whatever to fix the failure, and start from the top again until it works end-to-end.

Body:
I am using an official postgres v12 docker image that I want to initialise with two SQL dump files that are gathered from a remote legacy v9.2 postgres server during the docker build phase:

RUN ssh $REMOTE_USER@$REMOTE_HOST "pg_dumpall -w -U $REMOTE_DB_USER -h localhost -p $REMOTE_DB_PORT --clean --globals-only -l $REMOTE_DB_NAME" >> dump/a_globals.sql

RUN ssh $REMOTE_USER@$REMOTE_HOST "pg_dump -w -U $REMOTE_DB_USER -h localhost -p $REMOTE_DB_PORT --clean --create $REMOTE_DB_NAME" >> dump/b_db.sql

By placing both a_globals.sql and b_db.sql files into the docker image folder docker-entrypoint-initdb.d, then the database is initialised with the legacy SQL files when the v12 container starts (as described here). Docker is working correctly, the dump files are retrieved successfully. However I am running into problems initialising the container's database and require guidance:

When the container starts to initialise its DB, it stops with ERROR:  role $someDBRole does not exist. This is because the psql v9.2 dump SQL files DROP roles before reinstating them; the container DB does not like this. Unfortunately it is not until psql v9.4 that pg_dumpall and pg_dump have the option to --if-exists (see pg_dumpall v9.2 documentation). What would you suggest that I do in order to remedy this? I could manually edit the SQL dump files, but this would be impractical as the snapshots of the legacy DB need to be automated. Is there a way to suppress this error during container startup?

If I want to convert from ASCII to UTF-8, is it adequate to simply set the encoding option for pg_dumpall and pg_dump? Or do I need to take into consideration other issues when upgrading?

Is there a way to supress the removal and adding of the postgres super user which is in the dump SQL?

In general are there any other gotchas when containerising and/or updating a postgres DB.


问:
Need help in minecraft bukkit java development with kit command
I have made plugin that have 2 kits first with name Iron and the other with the name DProtect
so i want them to give items and i made everything and i made a cool down the problem is when i type /kit Iron or /kit DProtect it doesn't work i tried to do a lot of things and doesn't work this is the code can i have some help ?</p>

```<code>package Rivals.iSryMan.Kits.commands;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.UUID;

import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;

import Rivals.iSryMan.Kits.Main;

public class Kit implements CommandExecutor{
    private HashMap<UUID,Long> ironcooldown = new HashMap<UUID,Long>();
    private int ironcooldowntime = 300;

    private HashMap<UUID,Long> DProtectcooldown = new HashMap<UUID,Long>();
    private int DProtectcooldowntime = 5259487;

    @Override
    public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
        if(sender instanceof Player) {
            Player p = (Player)sender;
            if(args.length == 1) {
                //Kit Iron
                if(args[0].equals("Iron")) {
                if(ironcooldown.containsKey(p.getUniqueId())) {
                    long ironsecondsleft = ( (ironcooldown.get(p.getUniqueId())/ 1000) + ironcooldowntime) - (System.currentTimeMillis() / 1000);
                    if(ironsecondsleft > 0) {
                        p.sendMessage(Main.Color(Main.prefix + "You must wait " + ironsecondsleft + " before you take that kit again!"));
                    }else if(ironsecondsleft == 0) {
                        final ItemStack ironhelmet = new ItemStack(Material.IRON_HELMET);
                        final ItemStack ironchestplate = new ItemStack(Material.IRON_CHESTPLATE);
                        final ItemStack ironleggings = new ItemStack(Material.IRON_LEGGINGS);
                        final ItemStack ironboots = new ItemStack(Material.IRON_BOOTS);
                        p.getInventory().addItem(ironhelmet);
                        p.getInventory().addItem(ironchestplate);
                        p.getInventory().addItem(ironleggings);
                        p.getInventory().addItem(ironboots);

                        p.sendMessage(Main.Color(Main.prefix + " You've got your kit, Enjoy!"));
                    }
                }
                //Kit Iron

                //Kit DProtect
                } else if (args[0].equals("DProtect")) {
                if(DProtectcooldown.containsKey(p.getUniqueId())) {
                    long DProtectsecondsleft = ( (DProtectcooldown.get(p.getUniqueId()) / 1000) + DProtectcooldowntime) - (System.currentTimeMillis() / 1000);
                    if(DProtectsecondsleft > 0) {
                        p.sendMessage(Main.Color(Main.prefix + "You must wait " + DProtectsecondsleft + " before you take that kit again!"));
                    }else if(DProtectcooldowntime == 0) {

                        final ItemStack dphelmet = new ItemStack(Material.IRON_HELMET);
                        final ItemMeta dphelmetmeta = dphelmet.getItemMeta();
                        final ItemStack dpchestplate = new ItemStack(Material.IRON_CHESTPLATE);
                        final ItemMeta dpchestplatemetaa = dphelmet.getItemMeta();
                        final ItemStack dpleggings = new ItemStack(Material.IRON_LEGGINGS);
                        final ItemMeta dpleggingsmeta = dphelmet.getItemMeta();
                        final ItemStack dpboots = new ItemStack(Material.IRON_BOOTS);
                        final ItemMeta dpbootsmeta = dphelmet.getItemMeta();

                        ArrayList<String> dplore = new ArrayList<String>();

                        dplore.add(Main.Color("&bAuthentic Protection 4 Armor"));

                        //Set Meta
                        dphelmet.setItemMeta(dphelmetmeta);
                        dpchestplate.setItemMeta(dpchestplatemetaa);
                        dpleggings.setItemMeta(dpleggingsmeta);
                        dpboots.setItemMeta(dpbootsmeta);
                        //Set Meta

                        //Set Lore
                        dphelmetmeta.setLore(dplore);
                        dpchestplatemetaa.setLore(dplore);
                        dpleggingsmeta.setLore(dplore);
                        dpbootsmeta.setLore(dplore);
                        //Set Lore

                        //Adding Kit
                        p.getInventory().addItem(dphelmet);
                        p.getInventory().addItem(dpchestplate);
                        p.getInventory().addItem(dpleggings);
                        p.getInventory().addItem(dpboots);
                        //Adding Kit

                        p.sendMessage(Main.Color(Main.prefix + " You've got your kit, Enjoy!"));

                    }
                }
                //Kit DProtect
                }
                    return true;
                }

        }
        return false;
    }

}
</code>```

答:
It seems that you haven't added the player to the HashMap so it will return false so you might want to make your HashMaps public and static and inside your PlayerJoinEvent (if you have one) add

```<code>Kit.ironcooldown.put(p.getUniqueId(), 0);
</code>```

or if you don't have a PlayerJoinEvent and/or you don't want to do that, you can put before your args check

```<code>if (!ironcooldown.containsKey(p.getUniqueId()) {
    ironcooldown.put(p.getUniqueId(), 0);
}
</code>```

Do the same for Dprotectcooldown.

Hope this helped!

Body:
I have made plugin that have 2 kits first with name Iron and the other with the name DProtect
so i want them to give items and i made everything and i made a cool down the problem is when i type /kit Iron or /kit DProtect it doesn't work i tried to do a lot of things and doesn't work this is the code can i have some help ?

package Rivals.iSryMan.Kits.commands;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.UUID;

import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;

import Rivals.iSryMan.Kits.Main;

public class Kit implements CommandExecutor{
    private HashMap<UUID,Long> ironcooldown = new HashMap<UUID,Long>();
    private int ironcooldowntime = 300;

    private HashMap<UUID,Long> DProtectcooldown = new HashMap<UUID,Long>();
    private int DProtectcooldowntime = 5259487;

    @Override
    public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
        if(sender instanceof Player) {
            Player p = (Player)sender;
            if(args.length == 1) {
                //Kit Iron
                if(args[0].equals("Iron")) {
                if(ironcooldown.containsKey(p.getUniqueId())) {
                    long ironsecondsleft = ( (ironcooldown.get(p.getUniqueId())/ 1000) + ironcooldowntime) - (System.currentTimeMillis() / 1000);
                    if(ironsecondsleft > 0) {
                        p.sendMessage(Main.Color(Main.prefix + "You must wait " + ironsecondsleft + " before you take that kit again!"));
                    }else if(ironsecondsleft == 0) {
                        final ItemStack ironhelmet = new ItemStack(Material.IRON_HELMET);
                        final ItemStack ironchestplate = new ItemStack(Material.IRON_CHESTPLATE);
                        final ItemStack ironleggings = new ItemStack(Material.IRON_LEGGINGS);
                        final ItemStack ironboots = new ItemStack(Material.IRON_BOOTS);
                        p.getInventory().addItem(ironhelmet);
                        p.getInventory().addItem(ironchestplate);
                        p.getInventory().addItem(ironleggings);
                        p.getInventory().addItem(ironboots);

                        p.sendMessage(Main.Color(Main.prefix + " You've got your kit, Enjoy!"));
                    }
                }
                //Kit Iron

                //Kit DProtect
                } else if (args[0].equals("DProtect")) {
                if(DProtectcooldown.containsKey(p.getUniqueId())) {
                    long DProtectsecondsleft = ( (DProtectcooldown.get(p.getUniqueId()) / 1000) + DProtectcooldowntime) - (System.currentTimeMillis() / 1000);
                    if(DProtectsecondsleft > 0) {
                        p.sendMessage(Main.Color(Main.prefix + "You must wait " + DProtectsecondsleft + " before you take that kit again!"));
                    }else if(DProtectcooldowntime == 0) {

                        final ItemStack dphelmet = new ItemStack(Material.IRON_HELMET);
                        final ItemMeta dphelmetmeta = dphelmet.getItemMeta();
                        final ItemStack dpchestplate = new ItemStack(Material.IRON_CHESTPLATE);
                        final ItemMeta dpchestplatemetaa = dphelmet.getItemMeta();
                        final ItemStack dpleggings = new ItemStack(Material.IRON_LEGGINGS);
                        final ItemMeta dpleggingsmeta = dphelmet.getItemMeta();
                        final ItemStack dpboots = new ItemStack(Material.IRON_BOOTS);
                        final ItemMeta dpbootsmeta = dphelmet.getItemMeta();

                        ArrayList<String> dplore = new ArrayList<String>();

                        dplore.add(Main.Color("&bAuthentic Protection 4 Armor"));

                        //Set Meta
                        dphelmet.setItemMeta(dphelmetmeta);
                        dpchestplate.setItemMeta(dpchestplatemetaa);
                        dpleggings.setItemMeta(dpleggingsmeta);
                        dpboots.setItemMeta(dpbootsmeta);
                        //Set Meta

                        //Set Lore
                        dphelmetmeta.setLore(dplore);
                        dpchestplatemetaa.setLore(dplore);
                        dpleggingsmeta.setLore(dplore);
                        dpbootsmeta.setLore(dplore);
                        //Set Lore

                        //Adding Kit
                        p.getInventory().addItem(dphelmet);
                        p.getInventory().addItem(dpchestplate);
                        p.getInventory().addItem(dpleggings);
                        p.getInventory().addItem(dpboots);
                        //Adding Kit

                        p.sendMessage(Main.Color(Main.prefix + " You've got your kit, Enjoy!"));

                    }
                }
                //Kit DProtect
                }
                    return true;
                }

        }
        return false;
    }

}

Body:
It seems that you haven't added the player to the HashMap so it will return false so you might want to make your HashMaps public and static and inside your PlayerJoinEvent (if you have one) add

Kit.ironcooldown.put(p.getUniqueId(), 0);

or if you don't have a PlayerJoinEvent and/or you don't want to do that, you can put before your args check

if (!ironcooldown.containsKey(p.getUniqueId()) {
    ironcooldown.put(p.getUniqueId(), 0);
}

Do the same for Dprotectcooldown.

Hope this helped!


问:
< R > Sum elements of a column, based on dates and events in R
I am trying to calculate the lifespan in hours of different pieces in a machine. For that I have the following information:

Date.

Hours worked: Hours the machine was on.

Replacement: (1 or 0) to specify if a replacement took place or not.

Piece Replaced: Piece X or Y (This machine has different pieces).

Example dataset:

```<code>set.seed(89)
hoursWorked <- floor(runif(122, min=1, max=16))
Replacement <- floor(runif(122, min=0, max=2))

dt<- as.data.frame(cbind(hoursWorked, Replacement)) %>%
  mutate(PieceReplaced= ifelse(Replacement==1,cbind(c("X", "Y")) ,NA),
         datesample=seq(as.Date("2020-01-01"), as.Date("2020-05-01"), by="days"))%>%
  select(datesample, everything())

</code>```

So I want to sum the hours the machine was on since the last time the specific piece was replaced. The result would look like:

```<code>dt$averagetime[1:10] <- c(0,0,2+14, NA, 13+12, 14+12+13+15, 15+12, NA, NA, NA)
</code>```

The pieces are scheduled to be replaced at the start of the day so the hours worked on the replacement day are included for the next replacement

I really appreciate the help I've been stuck with this problem for a while. Thank you!!!

答:
Continuing with tidyverse, you could try the following.

First, use mutate and cumsum to calculate the cumulative hours for each day. Would not use group_by before this, as to include all hours recorded each day, independent of piece replacement.

Then, you can group by PieceReplaced and use the difference in the cumulative hours for each piece.

This provides similar results as to output suggested, except for first Y piece which could be considered at least 2 hours with unknown time prior to that point.

```<code>dt <- as.data.frame(cbind(hoursWorked, Replacement)) %>%
  mutate(PieceReplaced= ifelse(Replacement==1,cbind(c("X", "Y")) ,NA),
         datesample=seq(as.Date("2020-01-01"), as.Date("2020-05-01"), by="days"))%>%
  select(datesample, everything()) %>%
  mutate(CumHours = lag(cumsum(hoursWorked), default = 0)) %>%
  group_by(PieceReplaced) %>%
  mutate(TimeSinceReplaced = ifelse(Replacement == 1, CumHours - lag(CumHours, default = 0), NA))
</code>```

Output

```<code># A tibble: 122 x 6
# Groups:   PieceReplaced [3]
    datesample hoursWorked Replacement PieceReplaced CumHours TimeSinceReplaced
    <date>           <dbl>       <dbl> <chr>            <dbl>             <dbl>
  1 2020-01-01           2           1 X                    0                 0
  2 2020-01-02          14           1 Y                    2                 2
  3 2020-01-03          12           1 X                   16                16
  4 2020-01-04          13           0 NA                  28                NA
  5 2020-01-05          15           1 X                   41                25
  6 2020-01-06          12           1 Y                   56                54
  7 2020-01-07           4           1 X                   68                27
  8 2020-01-08           1           0 NA                  72                NA
  9 2020-01-09          15           0 NA                  73                NA
 10 2020-01-10           4           0 NA                  88                NA
 11 2020-01-11           2           0 NA                  92                NA
 12 2020-01-12           8           0 NA                  94                NA
</code>```

Body:
I am trying to calculate the lifespan in hours of different pieces in a machine. For that I have the following information:

Date.

Hours worked: Hours the machine was on.

Replacement: (1 or 0) to specify if a replacement took place or not.

Piece Replaced: Piece X or Y (This machine has different pieces).

Example dataset:

set.seed(89)
hoursWorked <- floor(runif(122, min=1, max=16))
Replacement <- floor(runif(122, min=0, max=2))

dt<- as.data.frame(cbind(hoursWorked, Replacement)) %>%
  mutate(PieceReplaced= ifelse(Replacement==1,cbind(c("X", "Y")) ,NA),
         datesample=seq(as.Date("2020-01-01"), as.Date("2020-05-01"), by="days"))%>%
  select(datesample, everything())

So I want to sum the hours the machine was on since the last time the specific piece was replaced. The result would look like:

dt$averagetime[1:10] <- c(0,0,2+14, NA, 13+12, 14+12+13+15, 15+12, NA, NA, NA)

The pieces are scheduled to be replaced at the start of the day so the hours worked on the replacement day are included for the next replacement

I really appreciate the help I've been stuck with this problem for a while. Thank you!!!

Body:
Continuing with tidyverse, you could try the following.

First, use mutate and cumsum to calculate the cumulative hours for each day. Would not use group_by before this, as to include all hours recorded each day, independent of piece replacement.

Then, you can group by PieceReplaced and use the difference in the cumulative hours for each piece.

This provides similar results as to output suggested, except for first Y piece which could be considered at least 2 hours with unknown time prior to that point.

dt <- as.data.frame(cbind(hoursWorked, Replacement)) %>%
  mutate(PieceReplaced= ifelse(Replacement==1,cbind(c("X", "Y")) ,NA),
         datesample=seq(as.Date("2020-01-01"), as.Date("2020-05-01"), by="days"))%>%
  select(datesample, everything()) %>%
  mutate(CumHours = lag(cumsum(hoursWorked), default = 0)) %>%
  group_by(PieceReplaced) %>%
  mutate(TimeSinceReplaced = ifelse(Replacement == 1, CumHours - lag(CumHours, default = 0), NA))

Output

# A tibble: 122 x 6
# Groups:   PieceReplaced [3]
    datesample hoursWorked Replacement PieceReplaced CumHours TimeSinceReplaced
    <date>           <dbl>       <dbl> <chr>            <dbl>             <dbl>
  1 2020-01-01           2           1 X                    0                 0
  2 2020-01-02          14           1 Y                    2                 2
  3 2020-01-03          12           1 X                   16                16
  4 2020-01-04          13           0 NA                  28                NA
  5 2020-01-05          15           1 X                   41                25
  6 2020-01-06          12           1 Y                   56                54
  7 2020-01-07           4           1 X                   68                27
  8 2020-01-08           1           0 NA                  72                NA
  9 2020-01-09          15           0 NA                  73                NA
 10 2020-01-10           4           0 NA                  88                NA
 11 2020-01-11           2           0 NA                  92                NA
 12 2020-01-12           8           0 NA                  94                NA


问:
Do I have to install numpy in PyCharm everytime I create a new project? (install and not import)
I installed numpy package in PyCharm, following the default way: File->Settings->Project Interpreter->Click on '+' sign->Type numpy in the search baar->Install. Now, when I am working on a new project and trying to import numpy, it says: "ModuleNotFoundError: No module named 'numpy'". Please help! Thanks in advance :)  </p>

答: Depends. Your first numpy module likely installed in a virtual environment. Therefore, unless you specify that same virtual environment for your new project, your new project will be unable to access a module installed in a virtual environment it doesn't use.


问:
printing array not working
hello everyone i am printing array from the database in the following format

```<code>Array ( [0] => 14
        [task_id] => 14
        [1] => 123
        [user_id] => 123
        [2] => 456
        [employee_id] => 456
        [3] => 2
        [service_id] => 2
        [4] => 2:00 AM
        [starttime] => 2:00 AM
        [5] => 4:00 AM
        [endtime] => 4:00 AM
        [6] => se a
        [servicename] => se a
        [7] => ddsdsd
        [servicedescription] => ddsdsd
        [8] => dsd
        [employeename] => dsd
        [9] => pictures/noimage.gif
        [employeepicture] => pictures/noimage.gif
        [10] => pictures/noimage.gif
        [pic_path] => pictures/noimage.gif )
</code>```

It is the result of

```<code>$rd = $this->executeQuery();
$recordsArray = array();
while (($row = mysqli_fetch_array($rd)) ){
$recordsArray[] = $row;
</code>```

problem is how can i pick the single record from it like this

```<code>echo $row[$task_id]; // not working
</code>```

Thanks

答: You would do that by limiting your SQL query using a where clause to get the correct record.</p>

Title: printing array not working

Body:
hello everyone i am printing array from the database in the following format

Array ( [0] => 14
        [task_id] => 14
        [1] => 123
        [user_id] => 123
        [2] => 456
        [employee_id] => 456
        [3] => 2
        [service_id] => 2
        [4] => 2:00 AM
        [starttime] => 2:00 AM
        [5] => 4:00 AM
        [endtime] => 4:00 AM
        [6] => se a
        [servicename] => se a
        [7] => ddsdsd
        [servicedescription] => ddsdsd
        [8] => dsd
        [employeename] => dsd
        [9] => pictures/noimage.gif
        [employeepicture] => pictures/noimage.gif
        [10] => pictures/noimage.gif
        [pic_path] => pictures/noimage.gif )

It is the result of

$rd = $this->executeQuery();
$recordsArray = array();
while (($row = mysqli_fetch_array($rd)) ){
$recordsArray[] = $row;

problem is how can i pick the single record from it like this

echo $row[$task_id]; // not working

Thanks


问:
while doing ng build --prod, jw-angular-pagination throwing error
I am using "jw-angular-pagination": "^1.1.0"

ERROR in
  node_modules/jw-angular-pagination/lib/jw-pagination.component.d.ts.JwPaginationComponent.html(8,9):
  : Property 'setPage' is private and only accessible within class
  'JwPaginationComponent'.

答:
I see a lot of people experiencing this but I found a way around it. If you are deploying to heroku like me, removing 'private' from setPage alone won't work as heroku will have to run npm install and ng build --prod all the time and this downloads fresh copy with same bug.

A PR has been made the repository here though but it hasn't been merged. While we hope it gets merged soon. Here's what I did:

I extracted the packages by moving them(jw-angular-pagination and jw-paginate) away from node_modules to a separate folder called 'packages'(name it anything you want). Mine is located at src/app/packages

In packages/jw-angular-pagination/lib/jw-angular-pagination.js on line 3, change jw-paginate line to var paginate = require("../../jw-paginate/lib/jw-paginate");

Go to your app.module.ts and change the import to: import { JwPaginationComponent } from "./packages/jw-angular-pagination/lib/jw-pagination.component";

Don't forget to run npm uninstall jw-angular-pagination so it doesn't conflict. And delete it from package.json


问:
Get parent VALUE on React-select grouped options
Im using react-select with grouped options, they are grouped like this:

```<code>{
  label: PARENT_NAME,
  value: PARENT_ID,
  options: [
    {
      label: CHILD_NAME,
      value: CHILD_ID,
    }
  ]
}
</code>```

I have an array with those options, and im passing it to the  component like this:

```<code><Select
  options={ARR_OF_OPTIONS}
  onChange={this.handleChange("name")}
/>
</code>```

My handleChange function is like this:

```<code>handleChange = name => selectedOption => {
  const value = selectedOption.value
  this.setState({ [name]: value, })
}
</code>```

My question is:
Is it possible to get the PARENT_ID when selecting the child option?

Hopefully I made myself clear.

Thanks in advance

答:
You can achieve this with pure JavaScript. On your handleChange method, you should filter out the grouped object from ARR_OF_OPTIONS that contains the selected child option.

```<code>const selectedParent = ARR_OF_OPTIONS
  .find((group) => group.options.find(({ value }) => value === selectedOption.value));

const { value } = selectedParent;  // this gives you the parent id
</code>```

Body:
Im using react-select with grouped options, they are grouped like this:

{
  label: PARENT_NAME,
  value: PARENT_ID,
  options: [
    {
      label: CHILD_NAME,
      value: CHILD_ID,
    }
  ]
}

I have an array with those options, and im passing it to the  component like this:

<Select
  options={ARR_OF_OPTIONS}
  onChange={this.handleChange("name")}
/>

My handleChange function is like this:

handleChange = name => selectedOption => {
  const value = selectedOption.value
  this.setState({ [name]: value, })
}

My question is:
Is it possible to get the PARENT_ID when selecting the child option?

Hopefully I made myself clear.

Thanks in advance

Body:
You can achieve this with pure JavaScript. On your handleChange method, you should filter out the grouped object from ARR_OF_OPTIONS that contains the selected child option.

const selectedParent = ARR_OF_OPTIONS
  .find((group) => group.options.find(({ value }) => value === selectedOption.value));

const { value } = selectedParent;  // this gives you the parent id


问:
How to use conditional statements/ternary inside a flutter widget
I need to know is it possible to use ternary/if else inside flutter widgets.

I'm trying to create a buttonCreator widget which will take few parameters, one of which will be the background. I need to check whether the widget has background enabled or not. What i have is this but i have no idea how to use it in real dart code.

```<code>Container buildButton(String text, bool bg){
  return new Container(
    decoration: new BoxDecoration(
      border: new Border.all(color: Colors.white),
      if (bg != true ? color: Colors.white : '')
    ),
    padding: new EdgeInsets.all(15.0),
    margin: new EdgeInsets.symmetric(horizontal: 10.0, vertical: 5.0),
    child: new Center(
      child: new Text(
        text, style: new TextStyle(color: Colors.white, fontFamily: 'Monsterrat')
      )
    ),
  );
};
</code>```

答:
```<code>decoration: new BoxDecoration(
    border: new Border.all(color: Colors.white),
    color: bg ? Colors.transparent : Colors.red, // you can use ternary operator here
),
</code>```

Modified from AleksTi's answer. color property cannot be null.

Body:
I need to know is it possible to use ternary/if else inside flutter widgets.

I'm trying to create a buttonCreator widget which will take few parameters, one of which will be the background. I need to check whether the widget has background enabled or not. What i have is this but i have no idea how to use it in real dart code.

Container buildButton(String text, bool bg){
  return new Container(
    decoration: new BoxDecoration(
      border: new Border.all(color: Colors.white),
      if (bg != true ? color: Colors.white : '')
    ),
    padding: new EdgeInsets.all(15.0),
    margin: new EdgeInsets.symmetric(horizontal: 10.0, vertical: 5.0),
    child: new Center(
      child: new Text(
        text, style: new TextStyle(color: Colors.white, fontFamily: 'Monsterrat')
      )
    ),
  );
};

Body:
decoration: new BoxDecoration(
    border: new Border.all(color: Colors.white),
    color: bg ? Colors.transparent : Colors.red, // you can use ternary operator here
),

Modified from AleksTi's answer. color property cannot be null.


答:
Sorry but Java or any JIT'ed language is not possible on the iPhone/iPad.

You might want to look at mono and use C#, it is closer to Java than Objective-C.

Mono Touch
- http://monotouch.net/

Or Unity 3d.
- http://unity3d.com/

Both use mono...

The mono group is re-grouping as a startup company and aims to be on par with novel's offering within a couple of months.   It still looks like a good piece of technology and well worth a look.

http://tirania.org/blog/

Title: Java for Iphone App Development?

Body:
I have been primarily using Java and have experience with it. I want to develop some iphone apps and wanted to know if there a way to develop iphone app using Java or iphone development can be only done using Objective-C?

Also if Objective-C is the only way to go then would really appreciate if you can recommend some books or links where I can get started on Iphone Development, my background is completely based on Java and I have not work with C or C++ professionally in the past.

Any recommendations/suggestions would highly help.

Can we have quick comparison of Objective-C vs Java or its like comparing oranges with Apple, am just trying to get some similarities in objective-c from java perspective so that I have some knowledge to leverage on while learning Objective-C, any suggestions?