问:
Python handling column levels of dataframe
I am getting out put like:

```<code>    Job Family  Mean Total Benefits Mean Total Compensation Percent_Total_Benefits
29  Public Service Aide 13650.231154    38340.873187    35.602
33  Park & Zoo  24215.619429    72228.710857    33.526
43  Museum & Cultural Affairs   26548.462000    79514.714000    33.388
</code>```

But I am expecting out column should come like:

```<code>        Mean Total Benefits Mean Total Compensation Percent_Total_Benefits
Job Family
Public Service Aide 13650.231154           38340.873187            35.602
Park & Zoo          24215.619429           72228.710857            33.526
Museum & Cultural Affairs   26548.462000   79514.714000            33.388
</code>```

The Job Family should come to next level rather than in the same level.
Please provide solution.

Thank you.

答:
You should set this column as the new index:</p>

```<code>df.set_index("Job Family", inplace=True)
</code>```

Body:
I am getting out put like:

    Job Family  Mean Total Benefits Mean Total Compensation Percent_Total_Benefits
29  Public Service Aide 13650.231154    38340.873187    35.602
33  Park & Zoo  24215.619429    72228.710857    33.526
43  Museum & Cultural Affairs   26548.462000    79514.714000    33.388

But I am expecting out column should come like:

        Mean Total Benefits Mean Total Compensation Percent_Total_Benefits
Job Family
Public Service Aide 13650.231154           38340.873187            35.602
Park & Zoo          24215.619429           72228.710857            33.526
Museum & Cultural Affairs   26548.462000   79514.714000            33.388

The Job Family should come to next level rather than in the same level.
Please provide solution.

Thank you.

Body:
You should set this column as the new index:

df.set_index("Job Family", inplace=True)


来源: stackexchange

问:
ESAPI encryption and decryption
I am using ESAPI Base64 encryption and decryption shown as is in:
http://www.programcreek.com/java-api-examples/index.php?api=org.owasp.esapi.codecs.Base64

This  is how my code looks:

```<code>import org.owasp.esapi.crypto.CipherText;
import org.owasp.esapi.crypto.PlainText;
import org.owasp.esapi.errors.EncryptionException;
import org.owasp.esapi.reference.crypto.JavaEncryptor;
import javax.crypto.EncryptedPrivateKeyInfo
import org.owasp.esapi.ESAPI
import org.owasp.esapi.ValidationErrorList
import org.owasp.esapi.Validator
import org.apache.commons.codec.binary.Base64;
class SampleMain {
public String decrypt2(String cryptedText){
    String clearText=null;
    try {
        CipherText cipherText=CipherText.fromPortableSerializedBytes(Base64.decodeBase64(cryptedText));
        clearText=ESAPI.encryptor().decrypt(cipherText).toString();
    }
    catch (  EncryptionException e) {
        System.out.println("EsapiEncryptor.decrypt: " + e.getMessage(),e);
    }
    return clearText.toString();
}

public String encrypt2(String clearText){
    String cryptedText=null;
    try {
        CipherText cipherText=ESAPI.encryptor().encrypt(new PlainText(clearText));
        cryptedText=Base64.encodeBase64(cipherText.asPortableSerializedByteArray());
    }
    catch (  EncryptionException e) {
        System.out.println("EsapiEncryptor.encrypt: " + e.getMessage(),e);
    }
    return cryptedText;
}

public static void main(String[] args) throws EncryptionException{

            String myplaintext = "MyPlaintext";
            SampleMain sample = new SampleMain();

            String enString = sample.encrypt2(myplaintext);
            System.out.println("-----------enString-----------: " + enString);

            String deString = sample.decrypt2(enString);
            System.out.println("-----------deString-----------: " + deString);

        }

}
</code>```

But when I try to run this simple program i get the following exception:

```<code>Apr 01, 2017 12:43:30 PM org.owasp.esapi.reference.JavaLogFactory$JavaLogger log
WARNING: [SECURITY FAILURE Anonymous:null@unknown -> /DefaultName/IntrusionDetector] Likely tampering with KDF version on serialized ciphertext.KDF version read from serialized ciphertext (123190483) is out of range. Valid range for KDF version is [20110203, 99991231].
org.owasp.esapi.errors.EncryptionException: Version info from serialized ciphertext not in valid range.
    at org.owasp.esapi.crypto.CipherTextSerializer.convertToCipherText(CipherTextSerializer.java:299)
    at org.owasp.esapi.crypto.CipherTextSerializer.<init>(CipherTextSerializer.java:80)
    at org.owasp.esapi.crypto.CipherText.fromPortableSerializedBytes(CipherText.java:176)
    at org.owasp.esapi.crypto.CipherText$fromPortableSerializedBytes$0.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:125)
    at gov.gsa.dss.test.SampleMain.decrypt2(SampleMain.groovy:30)
    at gov.gsa.dss.test.SampleMain$decrypt2$0.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:125)
    at gov.gsa.dss.test.SampleMain.main(SampleMain.groovy:59)
</code>```

Any ideas why I would be getting this error or such a simple program.    Thanks.

答:
This works for me:

```<code>public String decrypt2(String encryptedText) {
    byte[] encryptedTextTextAsBytes = encryptedText.getBytes(StandardCharsets.UTF_8)
    CipherText cipherText = CipherText.fromPortableSerializedBytes(Base64.decodeBase64(encryptedTextTextAsBytes))
    ESAPI.encryptor().decrypt(cipherText).toString()
}

public String encrypt2(String clearText) {
    CipherText cipherText = ESAPI.encryptor().encrypt(new PlainText(clearText))
    new String(Base64.encodeBase64(cipherText.asPortableSerializedByteArray()), StandardCharsets.UTF_8)
}
</code>```

You are passing a String to Base64.decodeBase64(), it might compile but I'm not sure of what Groovy does with that. You should pass a bytes[] (see how I obtain encryptedTextTextAsBytes). It might explain your error, it might not. I guess you did not post the exact code that produces the error you mention.

ContentLicense: CC BY-SA 3.0

Title: ESAPI encryption and decryption

Body:
I am using ESAPI Base64 encryption and decryption shown as is in:
http://www.programcreek.com/java-api-examples/index.php?api=org.owasp.esapi.codecs.Base64

This  is how my code looks:

import org.owasp.esapi.crypto.CipherText;
import org.owasp.esapi.crypto.PlainText;
import org.owasp.esapi.errors.EncryptionException;
import org.owasp.esapi.reference.crypto.JavaEncryptor;
import javax.crypto.EncryptedPrivateKeyInfo
import org.owasp.esapi.ESAPI
import org.owasp.esapi.ValidationErrorList
import org.owasp.esapi.Validator
import org.apache.commons.codec.binary.Base64;
class SampleMain {
public String decrypt2(String cryptedText){
    String clearText=null;
    try {
        CipherText cipherText=CipherText.fromPortableSerializedBytes(Base64.decodeBase64(cryptedText));
        clearText=ESAPI.encryptor().decrypt(cipherText).toString();
    }
    catch (  EncryptionException e) {
        System.out.println("EsapiEncryptor.decrypt: " + e.getMessage(),e);
    }
    return clearText.toString();
}

public String encrypt2(String clearText){
    String cryptedText=null;
    try {
        CipherText cipherText=ESAPI.encryptor().encrypt(new PlainText(clearText));
        cryptedText=Base64.encodeBase64(cipherText.asPortableSerializedByteArray());
    }
    catch (  EncryptionException e) {
        System.out.println("EsapiEncryptor.encrypt: " + e.getMessage(),e);
    }
    return cryptedText;
}

public static void main(String[] args) throws EncryptionException{

            String myplaintext = "MyPlaintext";
            SampleMain sample = new SampleMain();

            String enString = sample.encrypt2(myplaintext);
            System.out.println("-----------enString-----------: " + enString);

            String deString = sample.decrypt2(enString);
            System.out.println("-----------deString-----------: " + deString);

        }

}

But when I try to run this simple program i get the following exception:

Apr 01, 2017 12:43:30 PM org.owasp.esapi.reference.JavaLogFactory$JavaLogger log
WARNING: [SECURITY FAILURE Anonymous:null@unknown -> /DefaultName/IntrusionDetector] Likely tampering with KDF version on serialized ciphertext.KDF version read from serialized ciphertext (123190483) is out of range. Valid range for KDF version is [20110203, 99991231].
org.owasp.esapi.errors.EncryptionException: Version info from serialized ciphertext not in valid range.
    at org.owasp.esapi.crypto.CipherTextSerializer.convertToCipherText(CipherTextSerializer.java:299)
    at org.owasp.esapi.crypto.CipherTextSerializer.<init>(CipherTextSerializer.java:80)
    at org.owasp.esapi.crypto.CipherText.fromPortableSerializedBytes(CipherText.java:176)
    at org.owasp.esapi.crypto.CipherText$fromPortableSerializedBytes$0.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:125)
    at gov.gsa.dss.test.SampleMain.decrypt2(SampleMain.groovy:30)
    at gov.gsa.dss.test.SampleMain$decrypt2$0.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:125)
    at gov.gsa.dss.test.SampleMain.main(SampleMain.groovy:59)

Any ideas why I would be getting this error or such a simple program.    Thanks.

Body:
This works for me:

public String decrypt2(String encryptedText) {
    byte[] encryptedTextTextAsBytes = encryptedText.getBytes(StandardCharsets.UTF_8)
    CipherText cipherText = CipherText.fromPortableSerializedBytes(Base64.decodeBase64(encryptedTextTextAsBytes))
    ESAPI.encryptor().decrypt(cipherText).toString()
}

public String encrypt2(String clearText) {
    CipherText cipherText = ESAPI.encryptor().encrypt(new PlainText(clearText))
    new String(Base64.encodeBase64(cipherText.asPortableSerializedByteArray()), StandardCharsets.UTF_8)
}

You are passing a String to Base64.decodeBase64(), it might compile but I'm not sure of what Groovy does with that. You should pass a bytes[] (see how I obtain encryptedTextTextAsBytes). It might explain your error, it might not. I guess you did not post the exact code that produces the error you mention.


问:
Trick to loop/autorefresh docker ps view like top/htop in bash
Is it possible - and if yes, how - to have a self-refreshing view of current Docker containers printed by "docker ps" alike top/htop utilities?</p>

答:
As alternative to watch, there is an alias shown to loop docker stats (watch: might not be always available by default)

This creates a bash alias "ds"

```<code>alias ds='while true; do TEXT=$(docker stats --no-stream $(docker ps --format={{.Names}})); sleep 0.1; clear; echo "$TEXT"; done'
</code>```

from: https://github.com/docker/docker/issues/20973

Body:
As alternative to watch, there is an alias shown to loop docker stats (watch: might not be always available by default)

This creates a bash alias "ds"

alias ds='while true; do TEXT=$(docker stats --no-stream $(docker ps --format={{.Names}})); sleep 0.1; clear; echo "$TEXT"; done'

from: https://github.com/docker/docker/issues/20973


问:
NSMetaDataQuery does not complete
I’m trying to explore the files available to my app in iCloud using NSMetaDataQuery.  I’m able to start the query, but it never finishes.  Here’s my code.

```<code>func report1() {
    let filemgr = FileManager.default
    let url = filemgr.url(forUbiquityContainerIdentifier: nil)
    guard url != nil else {
        print("url is nil")
        return
    }
    let metaDataQuery = NSMetadataQuery()
    metaDataQuery.predicate =
        NSPredicate(format: "%K like '*'", NSMetadataItemFSNameKey)
    metaDataQuery.searchScopes = [NSMetadataQueryUbiquitousDocumentsScope]
    NotificationCenter.default.addObserver(self,
                                           selector: #selector(didFinish),
                                           name: NSNotification.Name.NSMetadataQueryDidFinishGathering,
                                           object: nil)
    NotificationCenter.default.addObserver(self,
                                           selector: #selector(didStart),
                                           name: NSNotification.Name.NSMetadataQueryDidStartGathering,
                                           object: nil)
    NotificationCenter.default.addObserver(self,
                                           selector: #selector(didUpdate),
                                           name: NSNotification.Name.NSMetadataQueryDidUpdate,
                                           object: nil)
    let result = metaDataQuery.start()
    print("metaDataQuery.start() returned \(result)")
}

@objc func didStart(notification: NSNotification) {
    let query: NSMetadataQuery = notification.object as! NSMetadataQuery
    print("didStart found \(query.results.count) items")
}

@objc func didFinish(notification: NSNotification) {
    print("didFinish")
}

@objc func didUpdate(notification: NSNotification) {
    print("didUpdate")
}
</code>```

This prints the following:

```<code>didStart found 0 items
metaDataQuery.start() returned true
</code>```

didStart is getting called, but didFinish and didUpdate are never called.  I get the same results if I substitute == or ==[cd] for like in the predicate.  Changing NSMetadataQueryUbiquitousDocumentsScope to NSMetadataQueryUbiquitousDataScope has no effect. What am I missing?

The same issue seems to have been posed several times on this forum, but I'm not finding any satisfactory answers.

答:
I think I found what is the reason.
Your code

```<code>let metaDataQuery = NSMetadataQuery()
</code>```

This actually makes the metaDataQuery as local object, its lifecycle is in the function scope, and will be destroyed when the function ends. Then how can it work?
Please make it as a member field.

Title: NSMetaDataQuery does not complete

Body:
I’m trying to explore the files available to my app in iCloud using NSMetaDataQuery.  I’m able to start the query, but it never finishes.  Here’s my code.

func report1() {
    let filemgr = FileManager.default
    let url = filemgr.url(forUbiquityContainerIdentifier: nil)
    guard url != nil else {
        print("url is nil")
        return
    }
    let metaDataQuery = NSMetadataQuery()
    metaDataQuery.predicate =
        NSPredicate(format: "%K like '*'", NSMetadataItemFSNameKey)
    metaDataQuery.searchScopes = [NSMetadataQueryUbiquitousDocumentsScope]
    NotificationCenter.default.addObserver(self,
                                           selector: #selector(didFinish),
                                           name: NSNotification.Name.NSMetadataQueryDidFinishGathering,
                                           object: nil)
    NotificationCenter.default.addObserver(self,
                                           selector: #selector(didStart),
                                           name: NSNotification.Name.NSMetadataQueryDidStartGathering,
                                           object: nil)
    NotificationCenter.default.addObserver(self,
                                           selector: #selector(didUpdate),
                                           name: NSNotification.Name.NSMetadataQueryDidUpdate,
                                           object: nil)
    let result = metaDataQuery.start()
    print("metaDataQuery.start() returned \(result)")
}

@objc func didStart(notification: NSNotification) {
    let query: NSMetadataQuery = notification.object as! NSMetadataQuery
    print("didStart found \(query.results.count) items")
}

@objc func didFinish(notification: NSNotification) {
    print("didFinish")
}

@objc func didUpdate(notification: NSNotification) {
    print("didUpdate")
}

This prints the following:

didStart found 0 items
metaDataQuery.start() returned true

didStart is getting called, but didFinish and didUpdate are never called.  I get the same results if I substitute == or ==[cd] for like in the predicate.  Changing NSMetadataQueryUbiquitousDocumentsScope to NSMetadataQueryUbiquitousDataScope has no effect. What am I missing?

The same issue seems to have been posed several times on this forum, but I'm not finding any satisfactory answers.

Body:
I think I found what is the reason.
Your code

let metaDataQuery = NSMetadataQuery()

This actually makes the metaDataQuery as local object, its lifecycle is in the function scope, and will be destroyed when the function ends. Then how can it work?
Please make it as a member field.


问:
Using AWS for SQL and REST frontend
I'm trying to set up a PostgreSQL db with a REST(php) gate. I want to access this database the standard REST way (using GET and Headers), from a C# application.

Currently I am using a standard web hoster that has a MySQL database, but I want to jump ship to PostgreSQL.

Am I right in thinking Amazon's EC2 servers a good choice to do this? I just need a server with PostgreSQL installed and a bunch of php scripts (for REST).

Thanks

答:
Check out restSQL. It's an open-source, ultra-lightweight persistence layer, with out of the box PostgreSQL support.

It's written in Java but you can use its HTTP API by deploying the service in a standard JEE container, e.g. Tomcat, or as a Docker container. The latest versions are on bundled as images on docker hub.

You can take it for a spin using the sandboxed instance and explore the docs at http://restsql.org.

Title: Using AWS for SQL and REST frontend


问:
Rails returning validation error message from model method
I am calling an import method in my controller that imports a file. If in the import it tries to save the object and fails a model validation, how would I return the validation error messages to the project_data_path (or some other way of getting back to the index view)?

I tried an if statement in the controller, but it just gives me a validation failed error

Controller

```<code>def import
  if Datum.import(params[:file],params[:project_id])
    redirect_to project_data_path, notice: "data imported."
  else
    redirect_to project_data_path #if import fails, need to send errors
  end
end
</code>```

Model

```<code>def self.import(file, proj_id)
    ##.. working logic that imports file into datum..##

    ## below works fine if there are no validation errors
    datum.save! ##model validation error happens here

  end
end
</code>```

答: save! throws an exception, while save just returns true or false. Just remove the exclamation mark.

Body:
I am calling an import method in my controller that imports a file. If in the import it tries to save the object and fails a model validation, how would I return the validation error messages to the project_data_path (or some other way of getting back to the index view)?

I tried an if statement in the controller, but it just gives me a validation failed error

Controller

def import
  if Datum.import(params[:file],params[:project_id])
    redirect_to project_data_path, notice: "data imported."
  else
    redirect_to project_data_path #if import fails, need to send errors
  end
end

Model

def self.import(file, proj_id)
    ##.. working logic that imports file into datum..##

    ## below works fine if there are no validation errors
    datum.save! ##model validation error happens here

  end
end


问:
azure function powershell read from storage queue and write to storage table
So I'm trying to develop a function that would read data from an Azure Storage queue and write it to an Azure storage table. I can't seem to find anything relevant. I found the code to read the queue:

```<code>$in = Get-Content $triggerInput
Write-Output "PowerShell script processed queue message '$in'"
</code>```

But there are no examples to write to the table, so I'm not sure how to do that.

答:
As detailed in the PowerShell storage documentation, in order to write entities to table storage you need to provide a unique PartitionKey and RowKey value.  Because of this, unless you're managing RowKeys outside in whatever's calling your Function, I found a datetime stamp to be useful.  With this in mind, an incoming json body like this:

```<code>{
  "room": "Boardroom",
  "temp": "21.24"
}
</code>```

feeds into your PowerShell function (both WebHook and Queue trigger examples provided):

```<code># WebHook example
$requestBody = Get-Content $req -Raw | ConvertFrom-Json

# Queue example
$requestBody = Get-Content $triggerInput | ConvertFrom-Json

Write-Output "PowerShell message body '$requestBody'"
$entity = [PSObject]@{
  PartitionKey = $requestBody.room
  RowKey = get-date -Format "yyyy-MM-dd H:m:s.ms"
  Temp = $requestBody.temp
}

$entity | ConvertTo-Json | Out-File -Encoding UTF8 $outputTable
</code>```

This results in one new entity (can be thought of as a row in database terms); assuming you've configured an Azure Table Storage output object in the Function and called it outputTable.

Body:
So I'm trying to develop a function that would read data from an Azure Storage queue and write it to an Azure storage table. I can't seem to find anything relevant. I found the code to read the queue:

$in = Get-Content $triggerInput
Write-Output "PowerShell script processed queue message '$in'"

But there are no examples to write to the table, so I'm not sure how to do that.

Body:
As detailed in the PowerShell storage documentation, in order to write entities to table storage you need to provide a unique PartitionKey and RowKey value.  Because of this, unless you're managing RowKeys outside in whatever's calling your Function, I found a datetime stamp to be useful.  With this in mind, an incoming json body like this:

{
  "room": "Boardroom",
  "temp": "21.24"
}

feeds into your PowerShell function (both WebHook and Queue trigger examples provided):

# WebHook example
$requestBody = Get-Content $req -Raw | ConvertFrom-Json

# Queue example
$requestBody = Get-Content $triggerInput | ConvertFrom-Json

Write-Output "PowerShell message body '$requestBody'"
$entity = [PSObject]@{
  PartitionKey = $requestBody.room
  RowKey = get-date -Format "yyyy-MM-dd H:m:s.ms"
  Temp = $requestBody.temp
}

$entity | ConvertTo-Json | Out-File -Encoding UTF8 $outputTable

This results in one new entity (can be thought of as a row in database terms); assuming you've configured an Azure Table Storage output object in the Function and called it outputTable.


问:
STM32F0 discovery I2C transfer using DMA
I'm trying to get data from an I2C sensor (BNO055) using DMA, but I can't start DMA transmission. I've found plenty of examples for F1, F3 adn F4 STM microcontrollers, but nothing helpful for F0.
What I do is:

I initialize sensor using poll method and it works fine.

I initialize DMA using this code:

`

```<code>void I2C1_DMA_Init(uint8_t *BNO055_DMA_buffer)
{
    RCC->AHBENR |= (RCC_AHBPeriph_DMA1);#
    DMA_InitTypeDef DMA_str;
    DMA_StructInit(&DMA_str);
    DMA_str.DMA_PeripheralBaseAddr = (uint32_t)I2C1->RXDR;
    DMA_str.DMA_MemoryBaseAddr = (uint32_t)BNO055_DMA_buffer;
    DMA_str.DMA_DIR = DMA_DIR_PeripheralSRC;
    DMA_str.DMA_BufferSize = 32;
    DMA_str.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
    DMA_str.DMA_MemoryInc = DMA_MemoryInc_Enable;
    DMA_str.DMA_PeripheralDataSize = DMA_PeripheralDataSize_Byte;
    DMA_str.DMA_MemoryDataSize = DMA_MemoryDataSize_Byte;
    DMA_str.DMA_Mode = DMA_Mode_Normal;
    DMA_str.DMA_Priority = DMA_Priority_VeryHigh;
    DMA_str.DMA_M2M = DMA_M2M_Disable;
    DMA_Init(DMA1_Channel3, &DMA_str);
}
</code>```

`

I set proper address of sensor memory to be read from using poll method.

Now I'd like to read 32 bytes using DMA. Do I have to send sensor address using I2C_TransferHandling() function? What other parameters should be sent then? What have I missed in DMA initialization that after executing:

I2C_DMACmd(I2C1, I2C_DMAReq_Rx, ENABLE);
 DMA_Cmd(DMA1_Channel3, ENABLE);

Nothing happens on the bus (I check it using logic analyzer).

答:
You can generate code using STMCubeMx. Also there are some DMA example codes for STM32F0 in STMCubeF0. I generated an I2C code for STM32F0 discovery board.

Your I2C init function can be as follow

```<code>    static void MX_I2C1_Init(void)
    {

      hi2c1.Instance = I2C1;
      hi2c1.Init.Timing = 0x2000090E;
      hi2c1.Init.OwnAddress1 = 0;
      hi2c1.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT;
      hi2c1.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE;
      hi2c1.Init.OwnAddress2 = 0;
      hi2c1.Init.OwnAddress2Masks = I2C_OA2_NOMASK;
      hi2c1.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE;
      hi2c1.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE;
      if (HAL_I2C_Init(&hi2c1) != HAL_OK)
      {
        Error_Handler();
      }

        /**Configure Analogue filter
        */
      if (HAL_I2CEx_ConfigAnalogFilter(&hi2c1, I2C_ANALOGFILTER_ENABLE) != HAL_OK)
      {
        Error_Handler();
      }

    }
</code>```

And DMA_Init function as follow

```<code>void HAL_I2C_MspInit(I2C_HandleTypeDef* hi2c)
{

  GPIO_InitTypeDef GPIO_InitStruct;
  if(hi2c->Instance==I2C1)
  {
  /* USER CODE BEGIN I2C1_MspInit 0 */

  /* USER CODE END I2C1_MspInit 0 */

    /**I2C1 GPIO Configuration
    PB6     ------> I2C1_SCL
    PB7     ------> I2C1_SDA
    */
    GPIO_InitStruct.Pin = GPIO_PIN_6|GPIO_PIN_7;
    GPIO_InitStruct.Mode = GPIO_MODE_AF_OD;
    GPIO_InitStruct.Pull = GPIO_PULLUP;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
    GPIO_InitStruct.Alternate = GPIO_AF1_I2C1;
    HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);

    /* Peripheral clock enable */
    __HAL_RCC_I2C1_CLK_ENABLE();

    /* Peripheral DMA init*/

    hdma_i2c1_rx.Instance = DMA1_Channel3;
    hdma_i2c1_rx.Init.Direction = DMA_PERIPH_TO_MEMORY;
    hdma_i2c1_rx.Init.PeriphInc = DMA_PINC_DISABLE;
    hdma_i2c1_rx.Init.MemInc = DMA_MINC_ENABLE;
    hdma_i2c1_rx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE;
    hdma_i2c1_rx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE;
    hdma_i2c1_rx.Init.Mode = DMA_NORMAL;
    hdma_i2c1_rx.Init.Priority = DMA_PRIORITY_LOW;
    if (HAL_DMA_Init(&hdma_i2c1_rx) != HAL_OK)
    {
      Error_Handler();
    }

    __HAL_LINKDMA(hi2c,hdmarx,hdma_i2c1_rx);

    hdma_i2c1_tx.Instance = DMA1_Channel2;
    hdma_i2c1_tx.Init.Direction = DMA_MEMORY_TO_PERIPH;
    hdma_i2c1_tx.Init.PeriphInc = DMA_PINC_DISABLE;
    hdma_i2c1_tx.Init.MemInc = DMA_MINC_ENABLE;
    hdma_i2c1_tx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE;
    hdma_i2c1_tx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE;
    hdma_i2c1_tx.Init.Mode = DMA_NORMAL;
    hdma_i2c1_tx.Init.Priority = DMA_PRIORITY_LOW;
    if (HAL_DMA_Init(&hdma_i2c1_tx) != HAL_OK)
    {
      Error_Handler();
    }

    __HAL_LINKDMA(hi2c,hdmatx,hdma_i2c1_tx);

  /* USER CODE BEGIN I2C1_MspInit 1 */

  /* USER CODE END I2C1_MspInit 1 */
  }

}
</code>```

After init functions you should call HAL_DMA_Start_IT.

Body:
I'm trying to get data from an I2C sensor (BNO055) using DMA, but I can't start DMA transmission. I've found plenty of examples for F1, F3 adn F4 STM microcontrollers, but nothing helpful for F0.
What I do is:

I initialize sensor using poll method and it works fine.

I initialize DMA using this code:

`

void I2C1_DMA_Init(uint8_t *BNO055_DMA_buffer)
{
    RCC->AHBENR |= (RCC_AHBPeriph_DMA1);#
    DMA_InitTypeDef DMA_str;
    DMA_StructInit(&DMA_str);
    DMA_str.DMA_PeripheralBaseAddr = (uint32_t)I2C1->RXDR;
    DMA_str.DMA_MemoryBaseAddr = (uint32_t)BNO055_DMA_buffer;
    DMA_str.DMA_DIR = DMA_DIR_PeripheralSRC;
    DMA_str.DMA_BufferSize = 32;
    DMA_str.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
    DMA_str.DMA_MemoryInc = DMA_MemoryInc_Enable;
    DMA_str.DMA_PeripheralDataSize = DMA_PeripheralDataSize_Byte;
    DMA_str.DMA_MemoryDataSize = DMA_MemoryDataSize_Byte;
    DMA_str.DMA_Mode = DMA_Mode_Normal;
    DMA_str.DMA_Priority = DMA_Priority_VeryHigh;
    DMA_str.DMA_M2M = DMA_M2M_Disable;
    DMA_Init(DMA1_Channel3, &DMA_str);
}

`

I set proper address of sensor memory to be read from using poll method.

Now I'd like to read 32 bytes using DMA. Do I have to send sensor address using I2C_TransferHandling() function? What other parameters should be sent then? What have I missed in DMA initialization that after executing:

I2C_DMACmd(I2C1, I2C_DMAReq_Rx, ENABLE);
 DMA_Cmd(DMA1_Channel3, ENABLE);

Nothing happens on the bus (I check it using logic analyzer).

Body:
You can generate code using STMCubeMx. Also there are some DMA example codes for STM32F0 in STMCubeF0. I generated an I2C code for STM32F0 discovery board.

Your I2C init function can be as follow

    static void MX_I2C1_Init(void)
    {

      hi2c1.Instance = I2C1;
      hi2c1.Init.Timing = 0x2000090E;
      hi2c1.Init.OwnAddress1 = 0;
      hi2c1.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT;
      hi2c1.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE;
      hi2c1.Init.OwnAddress2 = 0;
      hi2c1.Init.OwnAddress2Masks = I2C_OA2_NOMASK;
      hi2c1.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE;
      hi2c1.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE;
      if (HAL_I2C_Init(&hi2c1) != HAL_OK)
      {
        Error_Handler();
      }

        /**Configure Analogue filter
        */
      if (HAL_I2CEx_ConfigAnalogFilter(&hi2c1, I2C_ANALOGFILTER_ENABLE) != HAL_OK)
      {
        Error_Handler();
      }

    }

And DMA_Init function as follow

void HAL_I2C_MspInit(I2C_HandleTypeDef* hi2c)
{

  GPIO_InitTypeDef GPIO_InitStruct;
  if(hi2c->Instance==I2C1)
  {
  /* USER CODE BEGIN I2C1_MspInit 0 */

  /* USER CODE END I2C1_MspInit 0 */

    /**I2C1 GPIO Configuration
    PB6     ------> I2C1_SCL
    PB7     ------> I2C1_SDA
    */
    GPIO_InitStruct.Pin = GPIO_PIN_6|GPIO_PIN_7;
    GPIO_InitStruct.Mode = GPIO_MODE_AF_OD;
    GPIO_InitStruct.Pull = GPIO_PULLUP;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
    GPIO_InitStruct.Alternate = GPIO_AF1_I2C1;
    HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);

    /* Peripheral clock enable */
    __HAL_RCC_I2C1_CLK_ENABLE();

    /* Peripheral DMA init*/

    hdma_i2c1_rx.Instance = DMA1_Channel3;
    hdma_i2c1_rx.Init.Direction = DMA_PERIPH_TO_MEMORY;
    hdma_i2c1_rx.Init.PeriphInc = DMA_PINC_DISABLE;
    hdma_i2c1_rx.Init.MemInc = DMA_MINC_ENABLE;
    hdma_i2c1_rx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE;
    hdma_i2c1_rx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE;
    hdma_i2c1_rx.Init.Mode = DMA_NORMAL;
    hdma_i2c1_rx.Init.Priority = DMA_PRIORITY_LOW;
    if (HAL_DMA_Init(&hdma_i2c1_rx) != HAL_OK)
    {
      Error_Handler();
    }

    __HAL_LINKDMA(hi2c,hdmarx,hdma_i2c1_rx);

    hdma_i2c1_tx.Instance = DMA1_Channel2;
    hdma_i2c1_tx.Init.Direction = DMA_MEMORY_TO_PERIPH;
    hdma_i2c1_tx.Init.PeriphInc = DMA_PINC_DISABLE;
    hdma_i2c1_tx.Init.MemInc = DMA_MINC_ENABLE;
    hdma_i2c1_tx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE;
    hdma_i2c1_tx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE;
    hdma_i2c1_tx.Init.Mode = DMA_NORMAL;
    hdma_i2c1_tx.Init.Priority = DMA_PRIORITY_LOW;
    if (HAL_DMA_Init(&hdma_i2c1_tx) != HAL_OK)
    {
      Error_Handler();
    }

    __HAL_LINKDMA(hi2c,hdmatx,hdma_i2c1_tx);

  /* USER CODE BEGIN I2C1_MspInit 1 */

  /* USER CODE END I2C1_MspInit 1 */
  }

}

After init functions you should call HAL_DMA_Start_IT.


问:
DOMContentLoaded vs window.onload. What is the real difference between these two?
guys. I've been doing some research into these two functions for my javascript exercises and I'm pondering on what seems to be the clear difference between them. I know for some that might come across as kind of "duhish" but I'm still learning the ropes on programming in general. If you guys could help a guy out and give me some details on what each accomplishes and how it accomplishes what they set out, that might help me out in the future for other little projects I come across. </p>

答:
The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. A very different event load should be used only to detect a fully-loaded page. It is an incredibly popular mistake to use load where DOMContentLoaded would be much more appropriate, so be cautious.

Source


答:
Since you were asking about a numpy solution:

```<code>import pandas as pd
import numpy as np

df=pd.DataFrame({'A':[0,2,2],'B':[3,1,3],'C':[2,0,1],'D':[1,3,0],
                  'listVal':[[0.0,0.1,0.2,0.3],[0.5,0.6,0.7,0.8],[0.15,0.25,0.35,0.45]]})

a = df[range(4)].values
b = np.array(list(df["listVal"].values))
c = b[:,a].diagonal(0,0,1).T

newdf = pd.DataFrame(c, columns=df.columns[:-1])
newdf["listVal"] = df["listVal"]
print newdf
</code>```

Mind that this creates a large overhead, since the indexing b[:,a] adds another dimension.

Title: Replace indices with values from a list in a data frame

Body:
I have the following data frame:

A | B | C | D | ListVal
---------------------------------
0 | 3 | 2 | 1 | [0.0,0.1,0.2,0.3]
---------------------------------
2 | 1 | 0 | 3 | [0.5,0.6,0.7,0.8]
---------------------------------
2 | 3 | 1 | 0 | [0.15,0.25,0.35,0.45]

For each row, I would like to use the numbers in columns A-D as indices to the list in column ListVal, and fill the values in the respective columns. So for the above data frame, I want to convert it to:

A   |  B  |  C  |  D  | ListVal
-----------------------------------------
0.0 | 0.3 | 0.2 | 0.1 | [0.0,0.1,0.2,0.3]
-----------------------------------------
0.7 | 0.6 | 0.5 | 0.8 | [0.5,0.6,0.7,0.8]
-----------------------------------------
0.35| 0.45| 0.25| 0.15| [0.15,0.25,0.35,0.45]

Note that indices per row are non-repeating.

I tried to do this using numpy by converting last column into a matrix and the first four columns to another matrix. But stuck there, as well!

Body:
Since you were asking about a numpy solution:

import pandas as pd
import numpy as np

df=pd.DataFrame({'A':[0,2,2],'B':[3,1,3],'C':[2,0,1],'D':[1,3,0],
                  'listVal':[[0.0,0.1,0.2,0.3],[0.5,0.6,0.7,0.8],[0.15,0.25,0.35,0.45]]})

a = df[range(4)].values
b = np.array(list(df["listVal"].values))
c = b[:,a].diagonal(0,0,1).T

newdf = pd.DataFrame(c, columns=df.columns[:-1])
newdf["listVal"] = df["listVal"]
print newdf

Mind that this creates a large overhead, since the indexing b[:,a] adds another dimension.


问:
Using XMLHttpRequest, reading XML data
i am trying to read the xml file but somehow i am getting this error: Invalid number of parameters.

```<code><script type="text/javascript">
//<![CDATA[
    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    }
    else {
        // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.open("GET", "employee.XML", false);
    xmlhttp.send();
    xmlDoc = xmlhttp.responseXML;

    var empid= xmlDoc.getElementsByTagName("empid");
    var total = placeMarks.length;
    var names = xmlDoc.getElementsByTagName("Name");
    var designation= xmlDoc.getElementsByTagName("designation");
    var phone= xmlDoc.getElementsByTagName("phone");
    .....
</script>
</code>```

XML data:

```<code><employee>
<emp id="1007">
<name>John Chamber</name>
<designation>Web Expert1</designation>
<phone>555-55-555</phone>
<name>John D</name>
<designation>Web123123</designation>
<phone>555-55-555</phone>
<name>Chamber</name>
<designation>Web Expert</designation>
<phone>555-55-555</phone>
<name>Thomas</name>
<designation>TESTTEST</designation>
<phone>555-55-555</phone>

</emp>
</employee>
</code>```

答:
Firstly branch out your code as shown below to see if the server is responding with the correct 200 response.

```<code>            xmlhttp.open("GET", "employee.XML", false);
            xmlhttp.send(null);
         if (xmlhttp.status==200) {

                      xmlDoc = xmlhttp.responseXML;
                     var empid= xmlDoc.getElementsByTagName("emp");
                     var total = placeMarks.length;
                     var names = xmlDoc.getElementsByTagName("Name");
                     var designation= xmlDoc.getElementsByTagName("designation");
                     var phone= xmlDoc.getElementsByTagName("phone");
                     ..... ;
          }

                else if (xmlhttp.status==404) {
          alert("XML could not be found");
         }
</code>```

Also my suggestion is to use a javascript library like jQuery which does much of the heavy lifting for your. The whole code for creating the XHR object simply reduces to one line

```<code>$.get(url,function(data){
                     xmlDoc = data;
                     var empid= xmlDoc.getElementsByTagName("emp");
                     var total = placeMarks.length;
                     var names = xmlDoc.getElementsByTagName("Name");
                     var designation= xmlDoc.getElementsByTagName("designation");
                     var phone= xmlDoc.getElementsByTagName("phone");
});
</code>```

Finally whichever modern browser that you are using should easily be able to point out which line in the script is throwing the error. If you still face the issue please confirm which line is throwing the error.

EDIT
The problem scope has changed. The OP now wants to loop through the xml.
First of all the xml needs to be designed keeping the requirements in mind. Hence it should look like this

```<code><employees>
 <emp id="006">
   <name>John Chamber</name>
   <designation>Web Expert1</designation>
   <phone>555-55-555</phone>
 </emp>
 <emp id="007">
  <name>John D</name>
  <designation>Web123123</designation>
  <phone>555-55-555</phone>
 </emp>
 <emp id="008">
  <name>Chamber</name>
  <designation>Web Expert</designation>
  <phone>555-55-555</phone>
 </emp>
 <emp id="009">
   <name>Thomas</name>
   <designation>TESTTEST</designation>
   <phone>555-55-555</phone>
 </emp>
</employees>
</code>```

Now the javascript for parsing the xml

```<code>var emp=xmlDoc.getElementsByTagName("emp");
for (i=0;i<emp.length;i++) {
   var names=emp[i].childNodes[0].text;
   var designation= emp[i].childNodes[1].text;
   ......
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Using XMLHttpRequest, reading XML data

Body:
i am trying to read the xml file but somehow i am getting this error: Invalid number of parameters.

XML data:

<employee>
<emp id="1007">
<name>John Chamber</name>
<designation>Web Expert1</designation>
<phone>555-55-555</phone>
<name>John D</name>
<designation>Web123123</designation>
<phone>555-55-555</phone>
<name>Chamber</name>
<designation>Web Expert</designation>
<phone>555-55-555</phone>
<name>Thomas</name>
<designation>TESTTEST</designation>
<phone>555-55-555</phone>

</emp>
</employee>

Body:
Firstly branch out your code as shown below to see if the server is responding with the correct 200 response.

            xmlhttp.open("GET", "employee.XML", false);
            xmlhttp.send(null);
         if (xmlhttp.status==200) {

                      xmlDoc = xmlhttp.responseXML;
                     var empid= xmlDoc.getElementsByTagName("emp");
                     var total = placeMarks.length;
                     var names = xmlDoc.getElementsByTagName("Name");
                     var designation= xmlDoc.getElementsByTagName("designation");
                     var phone= xmlDoc.getElementsByTagName("phone");
                     ..... ;
          }

                else if (xmlhttp.status==404) {
          alert("XML could not be found");
         }

Also my suggestion is to use a javascript library like jQuery which does much of the heavy lifting for your. The whole code for creating the XHR object simply reduces to one line

$.get(url,function(data){
                     xmlDoc = data;
                     var empid= xmlDoc.getElementsByTagName("emp");
                     var total = placeMarks.length;
                     var names = xmlDoc.getElementsByTagName("Name");
                     var designation= xmlDoc.getElementsByTagName("designation");
                     var phone= xmlDoc.getElementsByTagName("phone");
});

Finally whichever modern browser that you are using should easily be able to point out which line in the script is throwing the error. If you still face the issue please confirm which line is throwing the error.

EDIT
The problem scope has changed. The OP now wants to loop through the xml.
First of all the xml needs to be designed keeping the requirements in mind. Hence it should look like this

<employees>
 <emp id="006">
   <name>John Chamber</name>
   <designation>Web Expert1</designation>
   <phone>555-55-555</phone>
 </emp>
 <emp id="007">
  <name>John D</name>
  <designation>Web123123</designation>
  <phone>555-55-555</phone>
 </emp>
 <emp id="008">
  <name>Chamber</name>
  <designation>Web Expert</designation>
  <phone>555-55-555</phone>
 </emp>
 <emp id="009">
   <name>Thomas</name>
   <designation>TESTTEST</designation>
   <phone>555-55-555</phone>
 </emp>
</employees>

Now the javascript for parsing the xml

var emp=xmlDoc.getElementsByTagName("emp");
for (i=0;i<emp.length;i++) {
   var names=emp[i].childNodes[0].text;
   var designation= emp[i].childNodes[1].text;
   ......
}


问:
Xcode build not showing up on iTunes Connect
I am trying to upload my app to TestFlight. I have created new provisioning profiles and have code signed the app as following:

In Xcode, the app successfully uploads to iTunes Connect, and soon after, I see the "processing build" screen on the Activity tab on iTunes Connect:

A few minutes later, the processing build disappears and there are no builds on the screen. I am unable to select a build as it simply says, Submit your builds using Xcode 6 or later, or Application Loader 3.0 or later.. How can I find the build on iTunes Connect? Thanks!

答:
My solution... is terrible, but I have found success uploading builds until they show up. It sometimes takes like 30 uploads, and other times it only takes one. This problem is affecting every build I have tried since I switched to Xcode 8 in December. It's horribly inefficient but it's the only thing I have found that works.

EDIT: Right after I sent this answer, I got my build processed at upload 13. Good luck, buddy.


问:
oauth2-server-php not returning refresh token
Using this oauth2 library for PHP, I am validating a user via client_credentials like this:

server.php

```<code>$server = new OAuth2\Server($storage, [
'access_lifetime' => 3600, // 1 hour
'refresh_token_lifetime' => 50400, // 14 days
]);

$server->addGrantType(new OAuth2\GrantType\ClientCredentials($server->getStorage('client_credentials'), ['always_issue_new_refresh_token' => true])));
</code>```

Then in my endpoint (token.php):

```<code>require_once __DIR__.'/server.php';
$request = OAuth2\Request::createFromGlobals();
$server->handleTokenRequest($request)->send(); //returns the token object
</code>```

Although a new access_token is returned, no refresh_token is returned:

```<code>{"access_token":"501a3d087db7532d4e4350402f9a5da332d71dfc","expires_in":3600,"token_type":"Bearer","scope":null}
</code>```

How do you get the refresh_token?

答: You must specify accessType: 'offline' in the OAuth2 options to receive a refresh token. If the former does not work try access_type: 'offline'.

Body:
Using this oauth2 library for PHP, I am validating a user via client_credentials like this:

server.php

$server = new OAuth2\Server($storage, [
'access_lifetime' => 3600, // 1 hour
'refresh_token_lifetime' => 50400, // 14 days
]);

$server->addGrantType(new OAuth2\GrantType\ClientCredentials($server->getStorage('client_credentials'), ['always_issue_new_refresh_token' => true])));

Then in my endpoint (token.php):

require_once __DIR__.'/server.php';
$request = OAuth2\Request::createFromGlobals();
$server->handleTokenRequest($request)->send(); //returns the token object

Although a new access_token is returned, no refresh_token is returned:

{"access_token":"501a3d087db7532d4e4350402f9a5da332d71dfc","expires_in":3600,"token_type":"Bearer","scope":null}

How do you get the refresh_token?


问:
How do I write a Firefox Addon?
What are some resources for getting started writing a Firefox Addon?  Is there an API guide somewhere?  Is there a getting started tutorial somewhere?  Is there a developer discussion board somewhere?</p>

答:
This has the best solutions:
https://developer.mozilla.org/en/Extensions
but you can try greasemonkey script compiler</p>

OwnerDisplayName: Nick

Title: How do I write a Firefox Addon?


问:
Android studio, My server to client interaction get me a null pointer exception. java.lang.NullPointerException: Attempt to invoke virtual method
I have a null point exception but I am not sure why.
I am writing a code that is trying to recive an output from the server and then change something in my app. However I am getting the null pointer and not sure why. My update method seems to be giving the error and "if(test.result())" seems to be the line of code that is giving me the problem.
Here are the part of my code that I think would be relevant. If I need to give me code, I have no problem giving it.

```<code>public class SpaceInvadersActivity extends Activity{
InvaderClass InvaderListen;
Map game2 = new Map(spaceInvadersView,InvaderListen);
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    InvaderListen = new InvaderClass(hostName, portnum,response);
    spaceInvadersView = new SpaceInvadersView(this, size.x,size.y,InvaderListen.returned());
    InvaderListen.execute();
    game2 = new Map (spaceInvadersView, InvaderListen);
    setContentView(game2.getView());
}
</code>```

}

```<code>SpaceInvadersView extends SurfaceView implements Runnable{
InvadersListener testListen;
public SpaceInvadersView(Context context, int x, int y,InvadersListener testing) {
    super(context);
    this.testListen = testing;
}
private void update(){
if(testListen.result()){   //So I guess the value returned by .result is
//null when it should not be
*does the changes I want*
}
}
</code>```

l

```<code>public class InvaderClass extends AsyncTask<Void, Void, Void> {
*instance variables*

InvaderClass(String addr, int port,TextView textResponse) {
    dstAddress = addr;
    dstPort = port;
    this.textResponse = textResponse;
}
public InvaderClass(String hostname) {
    // Try and connect to the server.
    System.out.println(hostname + portnum);
    try {
        socket = new Socket(hostname, portnum);
    } catch (IOException ioe) {
        System.out.println("There was an error connecting to the server: " + ioe);
        System.exit(-1);
    }
    try {
        output = new ObjectOutputStream(socket.getOutputStream());
        input = new ObjectInputStream(socket.getInputStream());

    } catch (IOException ioe) {
        System.out.println("Exception creating I/O streams: " + ioe);
    }
    listener = new InvadersListener(input);
    listener.start();
}
public boolean  reader(){
    return listener.result();
}
public InvadersListener returned(){return listener;}

@Override
protected Void doInBackground(Void... arg0) {
    InvaderClass chat = new InvaderClass(hostName);
    return null;
}
</code>```

Console

```<code>04/02 14:37:11: Launching app
Cold swapped changes.
$ adb shell am start -n
"com.example.lbillym.space/com.example.lbillym.space.SpaceInvadersActivity"
-a android.intent.action.MAIN -c android.intent.category.LAUNCHER
 Connected to process 15135 on device Nexus_5X_API_25 [emulator-5554]
 I/art: Not late-enabling -Xcheck:jni (already on)
 W/art: Unexpected CPU variant for X86 using defaults: x86

   [ 04-01 20:14:06.974  1539: 1564 D/         ]
   HostConnection::get() New Host Connection established 0x8b9df380, tid
   1564
   W/System: ClassLoader referenced unknown path:
   /data/app/com.example.lbillym.space-1/lib/x86
   I/InstantRun: Instant Run Runtime started. Android package is
   com.example.lbillym.space, real application class is null.
   W/System: ClassLoader referenced unknown path:
   /data/app/com.example.lbillym.space-1/lib/x86
   W/art: Suspending all threads took: 5.328ms

   [ 04-01 20:14:07.877 15135:15160 D/         ]
   HostConnection::get() New Host Connection established 0x9d8e5040, tid
   15160
   I/OpenGLRenderer: Initialized EGL, version 1.4
   D/OpenGLRenderer: Swap behavior 1
   I/art: Background sticky concurrent mark sweep GC freed 9050(1149KB)
   AllocSpace objects, 4(2MB) LOS objects, 47% free, 4MB/8MB, paused 8.249ms
   total 120.767ms

   [ 04-01 20:14:07.914 15135:15159 D/         ]
   HostConnection::get() New Host Connection established 0xa409d580, tid
   15159
   E/EGL_emulation: tid 15160: eglSurfaceAttrib(1174): error 0x3009
   (EGL_BAD_MATCH)
   W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x919a0ca0,
   error=EGL_BAD_MATCH
   D/gralloc_ranchu: gralloc_unregister_buffer: exiting HostConnection (is
   buffer-handling thread)
   E/AndroidRuntime: FATAL EXCEPTION: Thread-4
              Process: com.example.lbillym.space, PID: 15135
              java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.example.lbillym.space.InvadersListener.result()' on a null object reference
                  at com.example.lbillym.space.SpaceInvadersView.update(SpaceInvadersView.java:159)
                  at com.example.lbillym.space.SpaceInvadersView.run(SpaceInvadersView.java:131)
                  at java.lang.Thread.run(Thread.java:761)
</code>```

答:
Quite simply, InvaderListen.returned() in your new SpaceInvadersView(this, size.x,size.y,InvaderListen.returned()); call is probably returning null. The reason is that you never set a value here:

```<code>public InvadersListener returned(){return listener;}
</code>```

Body:
I have a null point exception but I am not sure why.
I am writing a code that is trying to recive an output from the server and then change something in my app. However I am getting the null pointer and not sure why. My update method seems to be giving the error and "if(test.result())" seems to be the line of code that is giving me the problem.
Here are the part of my code that I think would be relevant. If I need to give me code, I have no problem giving it.

public class SpaceInvadersActivity extends Activity{
InvaderClass InvaderListen;
Map game2 = new Map(spaceInvadersView,InvaderListen);
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    InvaderListen = new InvaderClass(hostName, portnum,response);
    spaceInvadersView = new SpaceInvadersView(this, size.x,size.y,InvaderListen.returned());
    InvaderListen.execute();
    game2 = new Map (spaceInvadersView, InvaderListen);
    setContentView(game2.getView());
}

}

SpaceInvadersView extends SurfaceView implements Runnable{
InvadersListener testListen;
public SpaceInvadersView(Context context, int x, int y,InvadersListener testing) {
    super(context);
    this.testListen = testing;
}
private void update(){
if(testListen.result()){   //So I guess the value returned by .result is
//null when it should not be
*does the changes I want*
}
}

l

public class InvaderClass extends AsyncTask<Void, Void, Void> {
*instance variables*

InvaderClass(String addr, int port,TextView textResponse) {
    dstAddress = addr;
    dstPort = port;
    this.textResponse = textResponse;
}
public InvaderClass(String hostname) {
    // Try and connect to the server.
    System.out.println(hostname + portnum);
    try {
        socket = new Socket(hostname, portnum);
    } catch (IOException ioe) {
        System.out.println("There was an error connecting to the server: " + ioe);
        System.exit(-1);
    }
    try {
        output = new ObjectOutputStream(socket.getOutputStream());
        input = new ObjectInputStream(socket.getInputStream());

    } catch (IOException ioe) {
        System.out.println("Exception creating I/O streams: " + ioe);
    }
    listener = new InvadersListener(input);
    listener.start();
}
public boolean  reader(){
    return listener.result();
}
public InvadersListener returned(){return listener;}

@Override
protected Void doInBackground(Void... arg0) {
    InvaderClass chat = new InvaderClass(hostName);
    return null;
}

Console

04/02 14:37:11: Launching app
Cold swapped changes.
$ adb shell am start -n
"com.example.lbillym.space/com.example.lbillym.space.SpaceInvadersActivity"
-a android.intent.action.MAIN -c android.intent.category.LAUNCHER
 Connected to process 15135 on device Nexus_5X_API_25 [emulator-5554]
 I/art: Not late-enabling -Xcheck:jni (already on)
 W/art: Unexpected CPU variant for X86 using defaults: x86

   [ 04-01 20:14:06.974  1539: 1564 D/         ]
   HostConnection::get() New Host Connection established 0x8b9df380, tid
   1564
   W/System: ClassLoader referenced unknown path:
   /data/app/com.example.lbillym.space-1/lib/x86
   I/InstantRun: Instant Run Runtime started. Android package is
   com.example.lbillym.space, real application class is null.
   W/System: ClassLoader referenced unknown path:
   /data/app/com.example.lbillym.space-1/lib/x86
   W/art: Suspending all threads took: 5.328ms

   [ 04-01 20:14:07.877 15135:15160 D/         ]
   HostConnection::get() New Host Connection established 0x9d8e5040, tid
   15160
   I/OpenGLRenderer: Initialized EGL, version 1.4
   D/OpenGLRenderer: Swap behavior 1
   I/art: Background sticky concurrent mark sweep GC freed 9050(1149KB)
   AllocSpace objects, 4(2MB) LOS objects, 47% free, 4MB/8MB, paused 8.249ms
   total 120.767ms

   [ 04-01 20:14:07.914 15135:15159 D/         ]
   HostConnection::get() New Host Connection established 0xa409d580, tid
   15159
   E/EGL_emulation: tid 15160: eglSurfaceAttrib(1174): error 0x3009
   (EGL_BAD_MATCH)
   W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x919a0ca0,
   error=EGL_BAD_MATCH
   D/gralloc_ranchu: gralloc_unregister_buffer: exiting HostConnection (is
   buffer-handling thread)
   E/AndroidRuntime: FATAL EXCEPTION: Thread-4
              Process: com.example.lbillym.space, PID: 15135
              java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.example.lbillym.space.InvadersListener.result()' on a null object reference
                  at com.example.lbillym.space.SpaceInvadersView.update(SpaceInvadersView.java:159)
                  at com.example.lbillym.space.SpaceInvadersView.run(SpaceInvadersView.java:131)
                  at java.lang.Thread.run(Thread.java:761)

Body:
Quite simply, InvaderListen.returned() in your new SpaceInvadersView(this, size.x,size.y,InvaderListen.returned()); call is probably returning null. The reason is that you never set a value here:

public InvadersListener returned(){return listener;}


问:
Why does "git svn fetch" command seem to be stuck and does nothing?
EDIT: Workaround.
Now we understand the issue, here is the solution: do

```<code>git svn fetch -r REVISION:HEAD
</code>```

where REVISION is the number of the svn commit of the branch creation.

I've been happy using git svn to work on the trunk of my project for a while, but now I need to track branches also.

I've tried to initialize a new repository to do that with

```<code>git init
git svn init https://svnserver/svn/repository
</code>```

Then I edit the local configuration file to reflect the structure of my svn repository:

```<code>[svn-remote "svn"]
    url = https://svnserver/svn/repository
    fetch = path/to/trunk:refs/remotes/trunk
    branches = path/to/branches/*:refs/remotes/branches/*
</code>```

Then I run

```<code>git svn fetch
</code>```

And this command just does nothing:

It does not terminates

It does not write anything in the console output

It does not use any CPU, nor create files

I gave up after 10 minutes

I've checked that the svn repository is working, because git svn fetch works perfectly on my git repository where I track only the trunk.

Is this a bug or am I missing something here ?

答:
Try adding the --log-window-size=5000 parameter.

If the repo has a large number of commits, git-svn will go through them 100 at a time by default. Bumping that up can increase its speed tremendously.

Body:
EDIT: Workaround.
Now we understand the issue, here is the solution: do

git svn fetch -r REVISION:HEAD

where REVISION is the number of the svn commit of the branch creation.

I've been happy using git svn to work on the trunk of my project for a while, but now I need to track branches also.

I've tried to initialize a new repository to do that with

git init
git svn init https://svnserver/svn/repository

Then I edit the local configuration file to reflect the structure of my svn repository:

[svn-remote "svn"]
    url = https://svnserver/svn/repository
    fetch = path/to/trunk:refs/remotes/trunk
    branches = path/to/branches/*:refs/remotes/branches/*

Then I run

git svn fetch

And this command just does nothing:

It does not terminates

It does not write anything in the console output

It does not use any CPU, nor create files

I gave up after 10 minutes

I've checked that the svn repository is working, because git svn fetch works perfectly on my git repository where I track only the trunk.

Is this a bug or am I missing something here ?


问:
How to push nested Objects into individual elements in an array?
The following API returns some JSON data:

https://en.wikipedia.org/w/api.php?format=json&action=query&generator=search&gsrnamespace=0&gsrlimit=10&prop=pageimages|extracts&pilimit=max&exintro&explaintext&exsentences=1&exlimit=max&gsrsearch=bananas

I am trying to push the properties (also objects) of the Pages object into a single array. Each object should be its own element in the array.

For example query.pages should be pushed into an array like [38940{}, 284306{}, ...]

Im doing this so that I can run through the array using ForEach and populate the DOM with the required data.

Thanks in advance!

答:
Seems that it is all you need if you have ES6:

```<code>var pages = Object.values(response.query.pages);
</code>```

Or you can use this variant to get it work in older browsers:

```<code>var pages = Object.keys(response.query.pages).map(function (key) {
    return response.query.pages[key];
});
</code>```

More detailed answer can be found here.

Body:
Seems that it is all you need if you have ES6:

var pages = Object.values(response.query.pages);

Or you can use this variant to get it work in older browsers:

var pages = Object.keys(response.query.pages).map(function (key) {
    return response.query.pages[key];
});

More detailed answer can be found here.


问:
How to make this HTML5 canvas script to full screen?
I am having trouble trying to set the canvas to fill the whole window. It is currently set to 500x500.. I am new to coding and would really appreciate any help! Thank you.

Here is the code:

<!DOCTYPE html>

    <title>Starfield effect done in HTML 5</title>

    <canvas width="500" height="500" id="starfieldCanvas"></canvas>

```

Original code and credit to: https://www.timewasters-place.com/starfield-animation-done-in-html-5/

答:
I assume you mean that you want your script to determine the screen size automatically, and then to set the canvas to be the full screen instead of the hardcoded 500 x 500 currently.

You can determine the viewport size programatically using the following where the width and height are as follows respectively. (Source):

```<code>var width = window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;

var height = window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;
</code>```

Then you can set the dimensions of your canvas as follows:

```<code>canvas.width  = width;
canvas.height = height;
</code>```

So, this would be the full code in your case:

```<code><!DOCTYPE html>
<html>
<head>
    <title>Starfield effect done in HTML 5</title>
    <script>
        window.onload = function() {

            /* --- config start --- */

            var starfieldCanvasId     = "starfieldCanvas", // id of the canvas to use
                framerate             = 60,                // frames per second this animation runs at (this is not exact)
                numberOfStarsModifier = 0.15,               // Number of stars, higher numbers have performance impact
                flightSpeed           = 0.003;              // speed of the flight, the higher this number the faster

            var width = window.innerWidth
            || document.documentElement.clientWidth
            || document.body.clientWidth;

            var height = window.innerHeight
            || document.documentElement.clientHeight
            || document.body.clientHeight;

            /* ---- config end ---- */

            var canvas        = document.getElementById(starfieldCanvasId),
                context       = canvas.getContext("2d"),
                stars         = [],
                TWO_PI        = Math.PI * 2;

                canvas.width  = width;
                canvas.height = height;

                numberOfStars = width * height / 1000 * numberOfStarsModifier;
                dirX          = width / 2;
                dirY          = height / 2;

            // initialize starfield
            for(var x = 0; x < numberOfStars; x++) {
                stars[x] = {
                    x: range(0, width),
                    y: range(0, height),
                    size: range(0, 1)
                };
            }

            // when mouse moves over canvas change middle point of animation
            canvas.onmousemove = function(event) {
                dirX = event.offsetX,
                dirY = event.offsetY;
            }

            // start tick at specified fps
            window.setInterval(tick, Math.floor(1000 / framerate));

            // main routine
            function tick() {
                var oldX,
                    oldY;

                // reset canvas for next frame
                context.clearRect(0, 0, width, height);

                for(var x = 0; x < numberOfStars; x++) {
                    // save old status
                    oldX = stars[x].x;
                    oldY = stars[x].y;

                    // calculate changes to star
                    stars[x].x += (stars[x].x - dirX) * stars[x].size * flightSpeed;
                    stars[x].y += (stars[x].y - dirY) * stars[x].size * flightSpeed;
                    stars[x].size += flightSpeed;

                    // if star is out of bounds, reset
                    if(stars[x].x < 0 || stars[x].x > width || stars[x].y < 0 || stars[x].y > height) {
                        stars[x] = {
                            x: range(0, width),
                            y: range(0, height),
                            size: 0
                        };
                    }

                    // draw star
                    context.strokeStyle = "rgba(255, 255, 255, " + Math.min(stars[x].size, 1) + ")";
                    context.lineWidth = stars[x].size;
                    context.beginPath();
                    context.moveTo(oldX, oldY);
                    context.lineTo(stars[x].x, stars[x].y);
                    context.stroke();
                }
            }

            // get a random number inside a range
            function range(start, end) {
                return Math.random() * (end - start) + start;
            }
        };
    </script>
</head>
<body style="background:#000;">
    <canvas id="starfieldCanvas"></canvas>
</body>
</html>
</code>```

I also tested this on Fiddle. Here's the link: Fiddle

Hope this helps! Let me know if it works.

Body:
I am having trouble trying to set the canvas to fill the whole window. It is currently set to 500x500.. I am new to coding and would really appreciate any help! Thank you.

Here is the code:

<!DOCTYPE html>

    <title>Starfield effect done in HTML 5</title>

    <canvas width="500" height="500" id="starfieldCanvas"></canvas>

Original code and credit to: https://www.timewasters-place.com/starfield-animation-done-in-html-5/

Body:
I assume you mean that you want your script to determine the screen size automatically, and then to set the canvas to be the full screen instead of the hardcoded 500 x 500 currently.

You can determine the viewport size programatically using the following where the width and height are as follows respectively. (Source):

var width = window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;

var height = window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;

Then you can set the dimensions of your canvas as follows:

canvas.width  = width;
canvas.height = height;

So, this would be the full code in your case:

<!DOCTYPE html>
<html>
<head>
    <title>Starfield effect done in HTML 5</title>
    <script>
        window.onload = function() {

            /* --- config start --- */

            var starfieldCanvasId     = "starfieldCanvas", // id of the canvas to use
                framerate             = 60,                // frames per second this animation runs at (this is not exact)
                numberOfStarsModifier = 0.15,               // Number of stars, higher numbers have performance impact
                flightSpeed           = 0.003;              // speed of the flight, the higher this number the faster

            var width = window.innerWidth
            || document.documentElement.clientWidth
            || document.body.clientWidth;

            var height = window.innerHeight
            || document.documentElement.clientHeight
            || document.body.clientHeight;

            /* ---- config end ---- */

            var canvas        = document.getElementById(starfieldCanvasId),
                context       = canvas.getContext("2d"),
                stars         = [],
                TWO_PI        = Math.PI * 2;

                canvas.width  = width;
                canvas.height = height;

                numberOfStars = width * height / 1000 * numberOfStarsModifier;
                dirX          = width / 2;
                dirY          = height / 2;

            // initialize starfield
            for(var x = 0; x < numberOfStars; x++) {
                stars[x] = {
                    x: range(0, width),
                    y: range(0, height),
                    size: range(0, 1)
                };
            }

            // when mouse moves over canvas change middle point of animation
            canvas.onmousemove = function(event) {
                dirX = event.offsetX,
                dirY = event.offsetY;
            }

            // start tick at specified fps
            window.setInterval(tick, Math.floor(1000 / framerate));

            // main routine
            function tick() {
                var oldX,
                    oldY;

                // reset canvas for next frame
                context.clearRect(0, 0, width, height);

                for(var x = 0; x < numberOfStars; x++) {
                    // save old status
                    oldX = stars[x].x;
                    oldY = stars[x].y;

                    // calculate changes to star
                    stars[x].x += (stars[x].x - dirX) * stars[x].size * flightSpeed;
                    stars[x].y += (stars[x].y - dirY) * stars[x].size * flightSpeed;
                    stars[x].size += flightSpeed;

                    // if star is out of bounds, reset
                    if(stars[x].x < 0 || stars[x].x > width || stars[x].y < 0 || stars[x].y > height) {
                        stars[x] = {
                            x: range(0, width),
                            y: range(0, height),
                            size: 0
                        };
                    }

                    // draw star
                    context.strokeStyle = "rgba(255, 255, 255, " + Math.min(stars[x].size, 1) + ")";
                    context.lineWidth = stars[x].size;
                    context.beginPath();
                    context.moveTo(oldX, oldY);
                    context.lineTo(stars[x].x, stars[x].y);
                    context.stroke();
                }
            }

            // get a random number inside a range
            function range(start, end) {
                return Math.random() * (end - start) + start;
            }
        };
    </script>
</head>
<body style="background:#000;">
    <canvas id="starfieldCanvas"></canvas>
</body>
</html>

I also tested this on Fiddle. Here's the link: Fiddle

Hope this helps! Let me know if it works.


问:
Automated Accordion
I am trying to make an accordion menu automatically cycle through, and every thing I keep finding is very vague about instructions.  I have found a couple of answers that said I could use the cycle plugin to cycle through, so that's it what I've attempted.  I'm not able to get the cycle function working properly though.  Am I going about it the right way, and if so what have I missed in my code?

I am very new at jQuery, so all of this is a little overwhelming for me.  Thanks.

```<code><script type="text/javascript" >
$(document).ready(function(){
lastBlock = $("#a1");
maxWidth = 380;
minWidth = 50;

$("#slide ul li a").hover(
  function(){
    $(lastBlock).animate({width: minWidth+"px"}, { queue:false, duration:400 });
$(this).animate({width: maxWidth+"px"}, { queue:false, duration:400});
lastBlock = this;
  }
);
});
 $(function() {
$('#slide').cycle({
  fx:     'slideY',
  easing: 'bounceout',
  delay:  -4000
});
});
  </script>

<div id="slide" class="cycle">
<ul>
  <li>
    <a id="a1">
      <img src="image" />
    </a>
  </li>
  <li>
    <a>
       <img src="image" />
    </a>
  </li>
  <li>
    <a>
      <img src="image" />
    </a>
  </li>
  <li>
    <a>
      <img src="image" />
    </a>
  </li>
</ul>
</div>
</code>```

答:
So I'm not sure if this is exactly what you are looking for, but I wrote a quick solution to hopefully help you get to your solution:

HTML

```<code><div id="slide" class="cycle">
    <ul>
        <li>
            <a id="a1">
                <img src="image" />
            </a>
        </li>
        <li>
            <a id="a2">
                <img src="image" />
            </a>
        </li>
        <li>
            <a id="a3">
                <img src="image" />
            </a>
        </li>
        <li>
            <a id="a4">
                <img src="image" />
            </a>
        </li>
    </ul>
</div>
</code>```

jQuery

```<code>var lastBlock = $("#a1");
var maxWidth = 166;
var minWidth = 35;
var counter = 0;
var myInterval = 0;

$("#slide ul li a").mouseenter(

function() {
    $(lastBlock).animate({
        width: minWidth + "px"
    }, {
        queue: false,
        duration: 400
    });
    $(this).animate({
        width: maxWidth + "px"
    }, {
        queue: false,
        duration: 400
    });
    lastBlock = this;
    clearInterval(myInterval);
}).mouseleave(function() {
    myInterval = setInterval(doSomething, 4000);
});

function doSomething() {
    var i = counter++ % 4 + 1;
    $("#a" + i).trigger("mouseenter");
    $("#a" + i).trigger("mouseleave");
}

myInterval = setInterval(doSomething, 4000);
</code>```

So in this solution, an interval is set to cycle through and trigger the events mouseenter() and mouseleave(). Since you might not want the images cycling while your mouse is over an element the interval is cleared upon mouseenter() and set up again during mouseleave(). A confusing part that could be refactored is the way it cycles through the images using a counter with a modulus operation. Note that I added an ID to each  with an incremental change to the number at the end.

See it working here: http://jsfiddle.net/Ck3aZ/

Title: Automated Accordion

Body:
So I'm not sure if this is exactly what you are looking for, but I wrote a quick solution to hopefully help you get to your solution:

HTML

<div id="slide" class="cycle">
    <ul>
        <li>
            <a id="a1">
                <img src="image" />
            </a>
        </li>
        <li>
            <a id="a2">
                <img src="image" />
            </a>
        </li>
        <li>
            <a id="a3">
                <img src="image" />
            </a>
        </li>
        <li>
            <a id="a4">
                <img src="image" />
            </a>
        </li>
    </ul>
</div>

jQuery

var lastBlock = $("#a1");
var maxWidth = 166;
var minWidth = 35;
var counter = 0;
var myInterval = 0;

$("#slide ul li a").mouseenter(

function() {
    $(lastBlock).animate({
        width: minWidth + "px"
    }, {
        queue: false,
        duration: 400
    });
    $(this).animate({
        width: maxWidth + "px"
    }, {
        queue: false,
        duration: 400
    });
    lastBlock = this;
    clearInterval(myInterval);
}).mouseleave(function() {
    myInterval = setInterval(doSomething, 4000);
});

function doSomething() {
    var i = counter++ % 4 + 1;
    $("#a" + i).trigger("mouseenter");
    $("#a" + i).trigger("mouseleave");
}

myInterval = setInterval(doSomething, 4000);

So in this solution, an interval is set to cycle through and trigger the events mouseenter() and mouseleave(). Since you might not want the images cycling while your mouse is over an element the interval is cleared upon mouseenter() and set up again during mouseleave(). A confusing part that could be refactored is the way it cycles through the images using a counter with a modulus operation. Note that I added an ID to each <a> with an incremental change to the number at the end.

See it working here: http://jsfiddle.net/Ck3aZ/


问:
Save test case properties if any of the assertions fail
How to save the test case properties if any of the assertions fail within this groovy script step?

Below is example code:

```<code>// define properties required for the script to run.
def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context)
def dataFolder = groovyUtils.projectPath

def vTIDAPI = testRunner.testCase.getPropertyValue("vTIDAPI")
def vTIDDB = testRunner.testCase.getPropertyValue("vTIDDB")
def RefAPI = testRunner.testCase.getPropertyValue("RefAPI")
def RefDB = testRunner.testCase.getPropertyValue("RefDB")
def AmountAPI = testRunner.testCase.getPropertyValue("AmountAPI")
def AmountDB = testRunner.testCase.getPropertyValue("AmountDB")
def CurrencyAPI = testRunner.testCase.getPropertyValue("CurrencyAPI")
def CurrencyDB = testRunner.testCase.getPropertyValue("CurrencyDB")

assert vTIDAPI == vTIDDB
assert RefAPI == RefDB
assert AmountAPI == AmountDB
assert CurrencyAPI == CurrencyDB
</code>```

答:
Here is the Groovy Script which does compare the given set of properties and on any of the assertion failure, writes the properties to a given file.

You need to change the value of property file name to be stored for variable propFileName variable.

Add more properties to be asserted in the form of key:value pairs format if needed

//Provide / edit the file name to store properties
def propFileName = '/tmp/testCase.properties'

//Define the properties to be matched or asserted ; add more properties if needed
def props = [ 'vTIDAPI':'vTIDDB', 'RefAPI':'RefDB', 'AmountAPI': 'AmountDB', 'CurrencyAPI': 'CurrencyDB']

/**
 * Do not edit beyond this point
 */
def writeTestCasePropertiesToFile = {
    //Get the test case properties as Properties object
    def properties =  context.testCase.properties.keySet().inject([:]){map, key ->  map[key] = context.testCase.getPropertyValue(key); map as Properties}
    log.info properties
    assert properties instanceof Properties
    properties?.store(new File(propFileName).newWriter(), null)
}

def myAssert = { arg1, arg2 ->
    context.testCase.getPropertyValue(arg1) == context.testCase.getPropertyValue(arg2) ? null : "${arg1} value does not match with ${arg2}"
}
def failureMessage = new StringBuffer()
props.collect{ null == myAssert(it.key, it.value) ?: failureMessage.append(myAssert(it.key, it.value)).append('\n')}
if(failureMessage.toString()) {
    log.error "Assertion failures:\n ${failureMessage.toString()}"
    writeTestCasePropertiesToFile()
    throw new Error(failureMessage.toString())
} else {
    log.info 'Assertions passed'
}
```

<p><strong>EDIT: Based on the OP comments</strong></p>

<p>Replace <code>def myAssert = ...</code> with below code fragment.</p>

```def myAssert = { arg1, arg2 ->
    def actual = context.testCase.getPropertyValue(arg1)
    def expected = context.testCase.getPropertyValue(arg2)
    actual == expected ? null : "${arg1} value does not match with ${arg2} - api ${actual} vs db ${expected}"
}
```

Body:
How to save the test case properties if any of the assertions fail within this groovy script step?

Below is example code:

// define properties required for the script to run.
def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context)
def dataFolder = groovyUtils.projectPath

def vTIDAPI = testRunner.testCase.getPropertyValue("vTIDAPI")
def vTIDDB = testRunner.testCase.getPropertyValue("vTIDDB")
def RefAPI = testRunner.testCase.getPropertyValue("RefAPI")
def RefDB = testRunner.testCase.getPropertyValue("RefDB")
def AmountAPI = testRunner.testCase.getPropertyValue("AmountAPI")
def AmountDB = testRunner.testCase.getPropertyValue("AmountDB")
def CurrencyAPI = testRunner.testCase.getPropertyValue("CurrencyAPI")
def CurrencyDB = testRunner.testCase.getPropertyValue("CurrencyDB")

assert vTIDAPI == vTIDDB
assert RefAPI == RefDB
assert AmountAPI == AmountDB
assert CurrencyAPI == CurrencyDB

Body:
Here is the Groovy Script which does compare the given set of properties and on any of the assertion failure, writes the properties to a given file.

You need to change the value of property file name to be stored for variable propFileName variable.

Add more properties to be asserted in the form of key:value pairs format if needed

//Provide / edit the file name to store properties
def propFileName = '/tmp/testCase.properties'

//Define the properties to be matched or asserted ; add more properties if needed
def props = [ 'vTIDAPI':'vTIDDB', 'RefAPI':'RefDB', 'AmountAPI': 'AmountDB', 'CurrencyAPI': 'CurrencyDB']

/**
 * Do not edit beyond this point
 */
def writeTestCasePropertiesToFile = {
    //Get the test case properties as Properties object
    def properties =  context.testCase.properties.keySet().inject([:]){map, key ->  map[key] = context.testCase.getPropertyValue(key); map as Properties}
    log.info properties
    assert properties instanceof Properties
    properties?.store(new File(propFileName).newWriter(), null)
}

def myAssert = { arg1, arg2 ->
    context.testCase.getPropertyValue(arg1) == context.testCase.getPropertyValue(arg2) ? null : "${arg1} value does not match with ${arg2}"
}
def failureMessage = new StringBuffer()
props.collect{ null == myAssert(it.key, it.value) ?: failureMessage.append(myAssert(it.key, it.value)).append('\n')}
if(failureMessage.toString()) {
    log.error "Assertion failures:\n ${failureMessage.toString()}"
    writeTestCasePropertiesToFile()
    throw new Error(failureMessage.toString())
} else {
    log.info 'Assertions passed'
}

EDIT: Based on the OP comments

Replace def myAssert = ... with below code fragment.

def myAssert = { arg1, arg2 ->
    def actual = context.testCase.getPropertyValue(arg1)
    def expected = context.testCase.getPropertyValue(arg2)
    actual == expected ? null : "${arg1} value does not match with ${arg2} - api ${actual} vs db ${expected}"
}


问:
Facebook share functionality is not working in iOS8
I have implemented Facebook sharing functionality using social framework. I have configured the Facebook account using device setting. When I installed the Facebook app on device, sharing is not working as expected.

When share window appears, it only has the image for sharing and no initial text and URL.

iOS8 - Share functionality is working properly if I remove the Facebook app from device.

iOS7 - Share functionality is working properly even the Facebook app is on device.

I am not sure where it is a framework issue or something is missing?

```<code>SLComposeViewController *facebookShareVC = [SLComposeViewController  composeViewControllerForServiceType:SLServiceTypeFacebook];

NSString *imagePath = [NSString stringWithFormat:@"%@/%@_%@_%@.gif", [[STInteractionManager sharedManager] getAppLibraryCacheDirectory], article.journalID, article.volume, article.issueNumber];

UIImage* img = [[STInteractionManager sharedManager] imageNamedFromDocuments:imagePath];

[facebookShareVC setInitialText:self.articleTitle];

[facebookShareVC addURL:[NSURL URLWithString:[self.url   stringByReplacingOccurrencesOfString:@"?dispform=ios-device" withString:@""]]];

[facebookShareVC addImage:img];

[self presentViewController:facebookShareVC animated:YES completion:nil];
</code>```

答: If you want to pre-fill the fields, you shouldn't use the Facebook SDK at all. Instead, use the Social framework provided by Apple. With only a few lines of code, you can trigger the SLComposeViewController. </p>

Body:
I have implemented Facebook sharing functionality using social framework. I have configured the Facebook account using device setting. When I installed the Facebook app on device, sharing is not working as expected.

When share window appears, it only has the image for sharing and no initial text and URL.

iOS8 - Share functionality is working properly if I remove the Facebook app from device.

iOS7 - Share functionality is working properly even the Facebook app is on device.

I am not sure where it is a framework issue or something is missing?

SLComposeViewController *facebookShareVC = [SLComposeViewController  composeViewControllerForServiceType:SLServiceTypeFacebook];

NSString *imagePath = [NSString stringWithFormat:@"%@/%@_%@_%@.gif", [[STInteractionManager sharedManager] getAppLibraryCacheDirectory], article.journalID, article.volume, article.issueNumber];

UIImage* img = [[STInteractionManager sharedManager] imageNamedFromDocuments:imagePath];

[facebookShareVC setInitialText:self.articleTitle];

[facebookShareVC addURL:[NSURL URLWithString:[self.url   stringByReplacingOccurrencesOfString:@"?dispform=ios-device" withString:@""]]];

[facebookShareVC addImage:img];

[self presentViewController:facebookShareVC animated:YES completion:nil];


问:
How to access individual elements in a 2d array c++
Basically, I have a 2d array and I would like to fill those elements using a for loop. Here is a rough set up (that is not working):

```<code>int grid[rows][columns];
for (int i=0; i < rows; i++){
    grid[rows][i] = 0;
    for (int j=0; j < columns; j++){
        grid[columns][j] = 0;
    }
}
</code>```

I have a working grid that the user determines. So basically if the user inputs a row and column that is x by x it'll work. The issue comes because it prints out random numbers at time in the formant of the grid. So sometimes it'll print out:

4 4 4 4

4 4 4 4

4 4 4 4

I am trying to get a grid that looks like:

0 0 0 0

0 0 0 0

0 0 0 0

I am making the 2d array first and then I am trying to fill the elements with 0. That is why I am using the for loop. The outcome is to fill every element with 0. It's just not working for some reason. I have no idea...

Any suggestions will help! Thank you

答:
You are accessing the 2D array incorrectly.  Try this instead:

```<code>int grid[rows][columns];

for (int i=0; i < rows; i++)
{
    for (int j=0; j < columns; j++)
    {
        grid[i][j] = 0;
    }
}
</code>```

As for why you are getting non zero data, it could be because there is random data in the 2D array, either leftover from your code or there because it was never initialized.

Body:
Basically, I have a 2d array and I would like to fill those elements using a for loop. Here is a rough set up (that is not working):

int grid[rows][columns];
for (int i=0; i < rows; i++){
    grid[rows][i] = 0;
    for (int j=0; j < columns; j++){
        grid[columns][j] = 0;
    }
}

I have a working grid that the user determines. So basically if the user inputs a row and column that is x by x it'll work. The issue comes because it prints out random numbers at time in the formant of the grid. So sometimes it'll print out:

4 4 4 4

4 4 4 4

4 4 4 4

I am trying to get a grid that looks like:

0 0 0 0

0 0 0 0

0 0 0 0

I am making the 2d array first and then I am trying to fill the elements with 0. That is why I am using the for loop. The outcome is to fill every element with 0. It's just not working for some reason. I have no idea...

Any suggestions will help! Thank you

Body:
You are accessing the 2D array incorrectly.  Try this instead:

int grid[rows][columns];

for (int i=0; i < rows; i++)
{
    for (int j=0; j < columns; j++)
    {
        grid[i][j] = 0;
    }
}

As for why you are getting non zero data, it could be because there is random data in the 2D array, either leftover from your code or there because it was never initialized.


问:
How to create this Search function
I need to create a search function in my website, but actually I don't know where to start looking for.

In my website I have a search form and need to let the users search items like this example:

"Craft beer in Atlanta"

How to separate "Craft beer" from "Atlanta" to make the corresponding
 query?

Thanks a lot.

Edit:

Solved with This:

```<code>if (strpos($search, ' in ') !== false){
    $search  = $search;
    $separate = explode(" in ", $search);
    $product = $separate[0];
    $place = $separate[1];
    $query = "SELECT * from catalog WHERE (`title` LIKE '%$product%' AND `status` = 'active' AND `coverage` LIKE '%$place%') OR (`tags` LIKE '%$product%' AND `status` = 'active' AND `coverage` LIKE '%$place%') OR (`description` LIKE '%$product%' AND `status` = 'active' AND `coverage` LIKE '%$place%') order BY titulo ASC";

}
</code>```

答:
Solved with this:</p>

```<code>if (strpos($search, ' in ') !== false){
    $search  = $search;
    $separate = explode(" in ", $search);
    $product = $separate[0];
    $place = $separate[1];
    $query = "SELECT * from catalog WHERE (`title` LIKE '%$product%' AND `status` = 'active' AND `coverage` LIKE '%$place%') OR (`tags` LIKE '%$product%' AND `status` = 'active' AND `coverage` LIKE '%$place%') OR (`description` LIKE '%$product%' AND `status` = 'active' AND `coverage` LIKE '%$place%') order BY titulo ASC";

}
</code>```

Title: How to create this Search function

Body:
I need to create a search function in my website, but actually I don't know where to start looking for.

In my website I have a search form and need to let the users search items like this example:

"Craft beer in Atlanta"

How to separate "Craft beer" from "Atlanta" to make the corresponding
 query?

Thanks a lot.

Edit:

Solved with This:

if (strpos($search, ' in ') !== false){
    $search  = $search;
    $separate = explode(" in ", $search);
    $product = $separate[0];
    $place = $separate[1];
    $query = "SELECT * from catalog WHERE (`title` LIKE '%$product%' AND `status` = 'active' AND `coverage` LIKE '%$place%') OR (`tags` LIKE '%$product%' AND `status` = 'active' AND `coverage` LIKE '%$place%') OR (`description` LIKE '%$product%' AND `status` = 'active' AND `coverage` LIKE '%$place%') order BY titulo ASC";

}

Body:
Solved with this:

if (strpos($search, ' in ') !== false){
    $search  = $search;
    $separate = explode(" in ", $search);
    $product = $separate[0];
    $place = $separate[1];
    $query = "SELECT * from catalog WHERE (`title` LIKE '%$product%' AND `status` = 'active' AND `coverage` LIKE '%$place%') OR (`tags` LIKE '%$product%' AND `status` = 'active' AND `coverage` LIKE '%$place%') OR (`description` LIKE '%$product%' AND `status` = 'active' AND `coverage` LIKE '%$place%') order BY titulo ASC";

}


问:
Append to Select not working in Chrome?
How to make this simple code work in chrome?

```<code> $('#teser').append(new Option('6','OptSix' ,true));
</code>```

https://jsfiddle.net/77c92wyv/

Its working fine in IE and FFX

答:
Change it to

```<code>$('#teser').append(new Option('OptSix','6' ,true, true));
</code>```

and it should work.

See https://developer.mozilla.org/en-US/docs/Web/API/HTMLOptionElement/Option for correct usage of Option()

Notice the third argument

defaultSelected
  A boolean that sets the selected attribute, the default is false. A value of true does not set the option to selected.

Title: Append to Select not working in Chrome?

Body:
How to make this simple code work in chrome?

 $('#teser').append(new Option('6','OptSix' ,true));

https://jsfiddle.net/77c92wyv/

Its working fine in IE and FFX

Body:
Change it to

$('#teser').append(new Option('OptSix','6' ,true, true));

and it should work.

See https://developer.mozilla.org/en-US/docs/Web/API/HTMLOptionElement/Option for correct usage of Option()

Notice the third argument

defaultSelected
  A boolean that sets the selected attribute, the default is false. A value of true does not set the option to selected.


问:
How does this for loop on consecutive integers work?
This seems like an embarrassingly easy concept but I can't understand why this for loop is working the way it is. The question is simply asking "Given a binary array, find the maximum number of consecutive 1s in this array."

```<code>def main(nums):
 count = 0
 for num in nums:
   if num == 1:
    count+=1
   else:
    count = 0
main([1,1,0,1,1,1,0,0,1,1,1,1,1])
</code>```

My question is, why does this for loop work? I expected the loop to print out the total count of 1's.

答:
It just doesn't work.

You can't expect to have the sum of all the 1s because when the loop find a zero it reset the counter (the "else" part).

However, your code doesn't do what it was expected to do, add a zero at the end of the list and you will easily see that the code fails.

To do what you asked, without changing your code too much, try this

```<code>def main(nums):
    count = maxcount = 0
    for num in nums:
        if num == 1:
            count+=1
        else:
            maxcount=max(maxcount, count)
            count = 0
    return maxcount
print(main([1,1,0,1,1,1,1,1,1,0,0,1,1,1,1,0,1]))
</code>```

Dave

Body:
This seems like an embarrassingly easy concept but I can't understand why this for loop is working the way it is. The question is simply asking "Given a binary array, find the maximum number of consecutive 1s in this array."

def main(nums):
 count = 0
 for num in nums:
   if num == 1:
    count+=1
   else:
    count = 0
main([1,1,0,1,1,1,0,0,1,1,1,1,1])

My question is, why does this for loop work? I expected the loop to print out the total count of 1's.

Body:
It just doesn't work.

You can't expect to have the sum of all the 1s because when the loop find a zero it reset the counter (the "else" part).

However, your code doesn't do what it was expected to do, add a zero at the end of the list and you will easily see that the code fails.

To do what you asked, without changing your code too much, try this

def main(nums):
    count = maxcount = 0
    for num in nums:
        if num == 1:
            count+=1
        else:
            maxcount=max(maxcount, count)
            count = 0
    return maxcount
print(main([1,1,0,1,1,1,1,1,1,0,0,1,1,1,1,0,1]))

Dave


问:
managedObjectContext in Other View
I have finally managed to get core data working and beginning to understand it. So far I have just been playing in a window based app with core data enabled, playing inside the app delegate files.

But how can I access my managedObjectContext from outside the app delegate, for example if I had a UIView subclass?

答:
Try using

```<code>[[[UIApplication sharedApplication] delegate] managedObjectContext];
</code>```

To get rid of warnings, cast the delegate as your actual AppDelegate; for example,

```<code>NSManagedObjectContext *context = [(YourAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
</code>```

EDIT:

After you change up any data, you'll need to save it. Here's the method I use:

```<code>NSManagedObjectContext *moc = [self managedObjectContext];

NSError *error;
if (![moc save:&error]) {
    NSLog(@"Couldn't save current data in current method.");
}
</code>```

Change up the log statement as you see fit.

ContentLicense: CC BY-SA 4.0

Title: managedObjectContext in Other View

Body:
Try using

[[[UIApplication sharedApplication] delegate] managedObjectContext];

To get rid of warnings, cast the delegate as your actual AppDelegate; for example,

NSManagedObjectContext *context = [(YourAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];

EDIT:

After you change up any data, you'll need to save it. Here's the method I use:

NSManagedObjectContext *moc = [self managedObjectContext];

NSError *error;
if (![moc save:&error]) {
    NSLog(@"Couldn't save current data in current method.");
}

Change up the log statement as you see fit.


问:
How to check airplane seat reservation in C++
I am new to C++ and I am trying to reserve a seat in airplane with an two dimensional array; everything work except it won't check if the seat is already taken.

```<code>for example:
 1  A B C D
 2  A B C D
 3  A B C D
 4  A B C D
 5  A B C D
</code>```

if the user choose row 1 letter A then it will be:

```<code> 1  X B C D
 2  A B C D
 3  A B C D
 4  A B C D
 5  A B C D
</code>```

Then if the user choose row 1 letter A again it should display message says the seat is already taken.This is my code

```<code>void reserveSeat(char seatChart[ROW][COLUM]){

    int row;
    char colum;

    cout<<"Enter the row number with colum letter ex(0 A): ";
    cin>>row>>colum;
    colum = toupper(colum);

    for(int r = 0; r<ROW;r++){

        for(int c = 0; c<COLUM;c++){

            if(seatChart[row][c] == colum){

                //check if the seat is taken
                if( seatChart[row][c] == 'X'){

                    cout<<"seat is already taken\n\n";
                }else
                    seatChart[row][c] = 'X';
            }
        }//end of inner for loop
    }//end of outer for loop
}
</code>```

答:
Try this code:  http://ideone.com/WfFsX9</p>

```<code>    #include <iostream>
    using namespace std;

    void reserveSeat(int x, int y, char **tab)
    {
        if(tab[x][y]=='X')
        cout<<"Already Reserved"<<endl;
        else
        tab[x][y]='X';

    }

    int main() {

//setup
    char **tab = new char *[5];
    for(int i = 0; i<5; i++)
    {
        tab[i] = new char[4];
    }
        for (int i = 0; i<5; i++)
            for (int j = 0; j<4; j++)
            {
                tab[i][j] = 65 + j;
            }

//Lets try to reserve

    reserveSeat(0,0,tab);
    reserveSeat(0,0,tab);

//printing
            for (int i = 0; i<5; i++)
            {
                cout<<i+1<<" ";
            for (int j = 0; j<4; j++)
            {
                cout<<tab[i][j]<<" ";
            }
                cout<<endl;
            }

        return 0;
    }
</code>```

Body:
I am new to C++ and I am trying to reserve a seat in airplane with an two dimensional array; everything work except it won't check if the seat is already taken.

for example:
 1  A B C D
 2  A B C D
 3  A B C D
 4  A B C D
 5  A B C D

if the user choose row 1 letter A then it will be:

 1  X B C D
 2  A B C D
 3  A B C D
 4  A B C D
 5  A B C D

Then if the user choose row 1 letter A again it should display message says the seat is already taken.This is my code

void reserveSeat(char seatChart[ROW][COLUM]){

    int row;
    char colum;

    cout<<"Enter the row number with colum letter ex(0 A): ";
    cin>>row>>colum;
    colum = toupper(colum);

    for(int r = 0; r<ROW;r++){

        for(int c = 0; c<COLUM;c++){

            if(seatChart[row][c] == colum){

                //check if the seat is taken
                if( seatChart[row][c] == 'X'){

                    cout<<"seat is already taken\n\n";
                }else
                    seatChart[row][c] = 'X';
            }
        }//end of inner for loop
    }//end of outer for loop
}

Body:
Try this code:  http://ideone.com/WfFsX9

    #include <iostream>
    using namespace std;

    void reserveSeat(int x, int y, char **tab)
    {
        if(tab[x][y]=='X')
        cout<<"Already Reserved"<<endl;
        else
        tab[x][y]='X';

    }

    int main() {

//setup
    char **tab = new char *[5];
    for(int i = 0; i<5; i++)
    {
        tab[i] = new char[4];
    }
        for (int i = 0; i<5; i++)
            for (int j = 0; j<4; j++)
            {
                tab[i][j] = 65 + j;
            }

//Lets try to reserve

    reserveSeat(0,0,tab);
    reserveSeat(0,0,tab);

//printing
            for (int i = 0; i<5; i++)
            {
                cout<<i+1<<" ";
            for (int j = 0; j<4; j++)
            {
                cout<<tab[i][j]<<" ";
            }
                cout<<endl;
            }

        return 0;
    }