问:
JCUDA cuda file not compiling
http://www.jcuda.org/tutorial/TutorialIndex.html

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package jcudavectoradd;

/**
 *
 * @author Sanjula
 */
/*
 * JCuda - Java bindings for NVIDIA CUDA driver and runtime API
 * http://www.jcuda.org
 *
 * Copyright 2011 Marco Hutter - http://www.jcuda.org
 */
import static jcuda.driver.JCudaDriver.*;

import java.io.*;

import jcuda.*;
import jcuda.driver.*;

/**
 * This is a sample class demonstrating how to use the JCuda driver
 * bindings to load and execute a CUDA vector addition kernel.
 * The sample reads a CUDA file, compiles it to a PTX file
 * using NVCC, loads the PTX file as a module and executes
 * the kernel function.

 */
public class JCudaVectorAdd
{
    /**
     * Entry point of this sample
     *
     * @param args Not used
     * @throws IOException If an IO error occurs
     */
    public static void main(String args[]) throws IOException
    {
        // Enable exceptions and omit all subsequent error checks
        JCudaDriver.setExceptionsEnabled(true);

        // Create the PTX file by calling the NVCC
        String ptxFileName = preparePtxFile("JCudaVectorAddKernel.cu");
        //String ptxFileName = "JCudaVectorAddKernel.ptx";

        // Initialize the driver and create a context for the first device.
        cuInit(0);
        CUdevice device = new CUdevice();
        cuDeviceGet(device, 0);
        CUcontext context = new CUcontext();
        cuCtxCreate(context, 0, device);

        // Load the ptx file.
        CUmodule module = new CUmodule();
        cuModuleLoad(module, ptxFileName);

        // Obtain a function pointer to the "add" function.
        CUfunction function = new CUfunction();
        cuModuleGetFunction(function, module, "add");

        int numElements = 100000;

        // Allocate and fill the host input data
        float hostInputA[] = new float[numElements];
        float hostInputB[] = new float[numElements];
        for(int i = 0; i < numElements; i++)
        {
            hostInputA[i] = (float)i;
            hostInputB[i] = (float)i;
        }

        // Allocate the device input data, and copy the
        // host input data to the device
        CUdeviceptr deviceInputA = new CUdeviceptr();
        cuMemAlloc(deviceInputA, numElements * Sizeof.FLOAT);
        cuMemcpyHtoD(deviceInputA, Pointer.to(hostInputA),
            numElements * Sizeof.FLOAT);
        CUdeviceptr deviceInputB = new CUdeviceptr();
        cuMemAlloc(deviceInputB, numElements * Sizeof.FLOAT);
        cuMemcpyHtoD(deviceInputB, Pointer.to(hostInputB),
            numElements * Sizeof.FLOAT);

        // Allocate device output memory
        CUdeviceptr deviceOutput = new CUdeviceptr();
        cuMemAlloc(deviceOutput, numElements * Sizeof.FLOAT);

        // Set up the kernel parameters: A pointer to an array
        // of pointers which point to the actual values.
        Pointer kernelParameters = Pointer.to(
            Pointer.to(new int[]{numElements}),
            Pointer.to(deviceInputA),
            Pointer.to(deviceInputB),
            Pointer.to(deviceOutput)
        );

        // Call the kernel function.
        int blockSizeX = 256;
        int gridSizeX = (int)Math.ceil((double)numElements / blockSizeX);
        cuLaunchKernel(function,
            gridSizeX,  1, 1,      // Grid dimension
            blockSizeX, 1, 1,      // Block dimension
            0, null,               // Shared memory size and stream
            kernelParameters, null // Kernel- and extra parameters
        );
        cuCtxSynchronize();

        // Allocate host output memory and copy the device output
        // to the host.
        float hostOutput[] = new float[numElements];
        cuMemcpyDtoH(Pointer.to(hostOutput), deviceOutput,
            numElements * Sizeof.FLOAT);

        // Verify the result
        boolean passed = true;
        for(int i = 0; i < numElements; i++)
        {
            float expected = i+i;
            if (Math.abs(hostOutput[i] - expected) > 1e-5)
            {
                System.out.println(
                    "At index "+i+ " found "+hostOutput[i]+
                    " but expected "+expected);
                passed = false;
                break;
            }
        }
        System.out.println("Test "+(passed?"PASSED":"FAILED"));

        // Clean up.
        cuMemFree(deviceInputA);
        cuMemFree(deviceInputB);
        cuMemFree(deviceOutput);
    }

    /**
     * The extension of the given file name is replaced with "ptx".
     * If the file with the resulting name does not exist, it is
     * compiled from the given file using NVCC. The name of the
     * PTX file is returned.
     *
     * @param cuFileName The name of the .CU file
     * @return The name of the PTX file
     * @throws IOException If an I/O error occurs
     */
    private static String preparePtxFile(String cuFileName) throws IOException
    {
        int endIndex = cuFileName.lastIndexOf('.');
        if (endIndex == -1)
        {
            endIndex = cuFileName.length()-1;
        }

        String ptxFileName = cuFileName.substring(0, endIndex+1)+"ptx";
        File ptxFile = new File(ptxFileName);
        if (ptxFile.exists())
        {
            return ptxFileName;
        }

        File cuFile = new File(cuFileName);
        if (!cuFile.exists())
        {
            throw new IOException("Input file not found: "+cuFileName);
        }
        String modelString = "-m"+System.getProperty("sun.arch.data.model");
        String command =
            "nvcc " + modelString + " -ptx "+
            cuFile.getPath()+" -o "+ptxFileName;

        System.out.println("Executing\n"+command);
        Process process = Runtime.getRuntime().exec(command);

        String errorMessage =
            new String(toByteArray(process.getErrorStream()));
        String outputMessage =
            new String(toByteArray(process.getInputStream()));
        int exitValue = 0;
        try
        {
            exitValue = process.waitFor();
        }
        catch (InterruptedException e)
        {
            Thread.currentThread().interrupt();
            throw new IOException(
                "Interrupted while waiting for nvcc output", e);
        }

        if (exitValue != 0)
        {
            System.out.println("nvcc process exitValue "+exitValue);
            System.out.println("errorMessage:\n"+errorMessage);
            System.out.println("outputMessage:\n"+outputMessage);
            throw new IOException(
                "Could not create .ptx file: "+errorMessage);
        }

        System.out.println("Finished creating PTX file");
        return ptxFileName;
    }

    /**
     * Fully reads the given InputStream and returns it as a byte array
     *
     * @param inputStream The input stream to read
     * @return The byte array containing the data from the input stream
     * @throws IOException If an I/O error occurs
     */
    private static byte[] toByteArray(InputStream inputStream)
        throws IOException
    {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte buffer[] = new byte[8192];
        while (true)
        {
            int read = inputStream.read(buffer);
            if (read == -1)
            {
                break;
            }
            baos.write(buffer, 0, read);
        }
        return baos.toByteArray();
    }

}```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>extern "C"
__global__ void add(int n, float *a, float *b, float *sum)
{
    int i = blockIdx.x * blockDim.x + threadIdx.x;
    if (i<n)
    {
        sum[i] = a[i] + b[i];
    }

}</code>```

when I compile this code I get this error. I am using the NetBeans 8.2 and I installed the Cuda. it is perfectly working in the visual studio 2015 . but it not working with java.

答:
i added visual studio cl.exe path to Environment Variables

C:\Program Files\Microsoft Visual Studio 10.0\VC\bin
 go to My Computer -> Properties -> Advanced System Settings -> Environment Variables. Here look for "PATH" in the list, and add the path above (or whatever is the location of your cl.exe).

Title: JCUDA cuda file not compiling

Body:
http://www.jcuda.org/tutorial/TutorialIndex.html

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package jcudavectoradd;

/**
 *
 * @author Sanjula
 */
/*
 * JCuda - Java bindings for NVIDIA CUDA driver and runtime API
 * http://www.jcuda.org
 *
 * Copyright 2011 Marco Hutter - http://www.jcuda.org
 */
import static jcuda.driver.JCudaDriver.*;

import java.io.*;

import jcuda.*;
import jcuda.driver.*;

/**
 * This is a sample class demonstrating how to use the JCuda driver
 * bindings to load and execute a CUDA vector addition kernel.
 * The sample reads a CUDA file, compiles it to a PTX file
 * using NVCC, loads the PTX file as a module and executes
 * the kernel function.

 */
public class JCudaVectorAdd
{
    /**
     * Entry point of this sample
     *
     * @param args Not used
     * @throws IOException If an IO error occurs
     */
    public static void main(String args[]) throws IOException
    {
        // Enable exceptions and omit all subsequent error checks
        JCudaDriver.setExceptionsEnabled(true);

        // Create the PTX file by calling the NVCC
        String ptxFileName = preparePtxFile("JCudaVectorAddKernel.cu");
        //String ptxFileName = "JCudaVectorAddKernel.ptx";

        // Initialize the driver and create a context for the first device.
        cuInit(0);
        CUdevice device = new CUdevice();
        cuDeviceGet(device, 0);
        CUcontext context = new CUcontext();
        cuCtxCreate(context, 0, device);

        // Load the ptx file.
        CUmodule module = new CUmodule();
        cuModuleLoad(module, ptxFileName);

        // Obtain a function pointer to the "add" function.
        CUfunction function = new CUfunction();
        cuModuleGetFunction(function, module, "add");

        int numElements = 100000;

        // Allocate and fill the host input data
        float hostInputA[] = new float[numElements];
        float hostInputB[] = new float[numElements];
        for(int i = 0; i < numElements; i++)
        {
            hostInputA[i] = (float)i;
            hostInputB[i] = (float)i;
        }

        // Allocate the device input data, and copy the
        // host input data to the device
        CUdeviceptr deviceInputA = new CUdeviceptr();
        cuMemAlloc(deviceInputA, numElements * Sizeof.FLOAT);
        cuMemcpyHtoD(deviceInputA, Pointer.to(hostInputA),
            numElements * Sizeof.FLOAT);
        CUdeviceptr deviceInputB = new CUdeviceptr();
        cuMemAlloc(deviceInputB, numElements * Sizeof.FLOAT);
        cuMemcpyHtoD(deviceInputB, Pointer.to(hostInputB),
            numElements * Sizeof.FLOAT);

        // Allocate device output memory
        CUdeviceptr deviceOutput = new CUdeviceptr();
        cuMemAlloc(deviceOutput, numElements * Sizeof.FLOAT);

        // Set up the kernel parameters: A pointer to an array
        // of pointers which point to the actual values.
        Pointer kernelParameters = Pointer.to(
            Pointer.to(new int[]{numElements}),
            Pointer.to(deviceInputA),
            Pointer.to(deviceInputB),
            Pointer.to(deviceOutput)
        );

        // Call the kernel function.
        int blockSizeX = 256;
        int gridSizeX = (int)Math.ceil((double)numElements / blockSizeX);
        cuLaunchKernel(function,
            gridSizeX,  1, 1,      // Grid dimension
            blockSizeX, 1, 1,      // Block dimension
            0, null,               // Shared memory size and stream
            kernelParameters, null // Kernel- and extra parameters
        );
        cuCtxSynchronize();

        // Allocate host output memory and copy the device output
        // to the host.
        float hostOutput[] = new float[numElements];
        cuMemcpyDtoH(Pointer.to(hostOutput), deviceOutput,
            numElements * Sizeof.FLOAT);

        // Verify the result
        boolean passed = true;
        for(int i = 0; i < numElements; i++)
        {
            float expected = i+i;
            if (Math.abs(hostOutput[i] - expected) > 1e-5)
            {
                System.out.println(
                    "At index "+i+ " found "+hostOutput[i]+
                    " but expected "+expected);
                passed = false;
                break;
            }
        }
        System.out.println("Test "+(passed?"PASSED":"FAILED"));

        // Clean up.
        cuMemFree(deviceInputA);
        cuMemFree(deviceInputB);
        cuMemFree(deviceOutput);
    }

    /**
     * The extension of the given file name is replaced with "ptx".
     * If the file with the resulting name does not exist, it is
     * compiled from the given file using NVCC. The name of the
     * PTX file is returned.
     *
     * @param cuFileName The name of the .CU file
     * @return The name of the PTX file
     * @throws IOException If an I/O error occurs
     */
    private static String preparePtxFile(String cuFileName) throws IOException
    {
        int endIndex = cuFileName.lastIndexOf('.');
        if (endIndex == -1)
        {
            endIndex = cuFileName.length()-1;
        }

        String ptxFileName = cuFileName.substring(0, endIndex+1)+"ptx";
        File ptxFile = new File(ptxFileName);
        if (ptxFile.exists())
        {
            return ptxFileName;
        }

        File cuFile = new File(cuFileName);
        if (!cuFile.exists())
        {
            throw new IOException("Input file not found: "+cuFileName);
        }
        String modelString = "-m"+System.getProperty("sun.arch.data.model");
        String command =
            "nvcc " + modelString + " -ptx "+
            cuFile.getPath()+" -o "+ptxFileName;

        System.out.println("Executing\n"+command);
        Process process = Runtime.getRuntime().exec(command);

        String errorMessage =
            new String(toByteArray(process.getErrorStream()));
        String outputMessage =
            new String(toByteArray(process.getInputStream()));
        int exitValue = 0;
        try
        {
            exitValue = process.waitFor();
        }
        catch (InterruptedException e)
        {
            Thread.currentThread().interrupt();
            throw new IOException(
                "Interrupted while waiting for nvcc output", e);
        }

        if (exitValue != 0)
        {
            System.out.println("nvcc process exitValue "+exitValue);
            System.out.println("errorMessage:\n"+errorMessage);
            System.out.println("outputMessage:\n"+outputMessage);
            throw new IOException(
                "Could not create .ptx file: "+errorMessage);
        }

        System.out.println("Finished creating PTX file");
        return ptxFileName;
    }

    /**
     * Fully reads the given InputStream and returns it as a byte array
     *
     * @param inputStream The input stream to read
     * @return The byte array containing the data from the input stream
     * @throws IOException If an I/O error occurs
     */
    private static byte[] toByteArray(InputStream inputStream)
        throws IOException
    {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte buffer[] = new byte[8192];
        while (true)
        {
            int read = inputStream.read(buffer);
            if (read == -1)
            {
                break;
            }
            baos.write(buffer, 0, read);
        }
        return baos.toByteArray();
    }

}

extern "C"
__global__ void add(int n, float *a, float *b, float *sum)
{
    int i = blockIdx.x * blockDim.x + threadIdx.x;
    if (i<n)
    {
        sum[i] = a[i] + b[i];
    }

}

when I compile this code I get this error. I am using the NetBeans 8.2 and I installed the Cuda. it is perfectly working in the visual studio 2015 . but it not working with java.


来源: stackexchange

问:
Reading JSON Array Values in Python / Flask
I have the following JSON data the I need to read in Flask:

```<code>{
"NewList":[
    {
        "key" : "myvalue1",
        "value" : "value1"
    },
    {
        "key" : "myvalue2",
        "value" : "value2"
    },
    {
        "key" : "myvalu3",
        "value" : "value4"
    }
]
}
</code>```

And I'm having trouble doing so. The code I currently have is as follows:

```<code>@app.route('/dataread', methods=['GET', 'POST'])
def dataread():
    if(request.json):
            myvalue1 = request.json['NewList']['myvalue1']
            return str(myvalue1)
        else:
            return 'nothing'
</code>```

But it isn't working. I'm getting the following error:

KeyError: 'NewList'

I know my syntax must be wrong but I can't figure how to fix it. I'm sorry for such a newb question. Please can you help.

Thanks.

答:
The value of newList is a list. You have to access an element of this list first before reading off "key" and "value".

```<code># print first item in the list
print(request.json['NewList'][0]['value']

# print them all
for item in request.json['NewList']
    print(item['key'])
    print(item['value'])
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have the following JSON data the I need to read in Flask:

{
"NewList":[
    {
        "key" : "myvalue1",
        "value" : "value1"
    },
    {
        "key" : "myvalue2",
        "value" : "value2"
    },
    {
        "key" : "myvalu3",
        "value" : "value4"
    }
]
}

And I'm having trouble doing so. The code I currently have is as follows:

@app.route('/dataread', methods=['GET', 'POST'])
def dataread():
    if(request.json):
            myvalue1 = request.json['NewList']['myvalue1']
            return str(myvalue1)
        else:
            return 'nothing'

But it isn't working. I'm getting the following error:

KeyError: 'NewList'

I know my syntax must be wrong but I can't figure how to fix it. I'm sorry for such a newb question. Please can you help.

Thanks.

Body:
The value of newList is a list. You have to access an element of this list first before reading off "key" and "value".

# print first item in the list
print(request.json['NewList'][0]['value']

# print them all
for item in request.json['NewList']
    print(item['key'])
    print(item['value'])


问:
Yii framework 2.0 ActiveRecord date not between two dates
Working with Yii framework 2.0 I have a database table with the columns 'from_date' and 'to_date'. I would like to select and count all records where:

today is NOT between from_date and to_date. And not even equal these dates (!($from_date <= $today) && !($today <= $to_date))).

OR

from_date is NULL and to_date is NULL. Because in some records these dates are empty, they need to be selected and counted as well.

I have a model which extends the ActiveRecord class, so I could use the following code to retrieve the data:

```<code>ModelClass::find()-where('big>small')->andWhere('1<2')->orWhere('3>1')->count();
</code>```

I tried to read the documentation of Yii 2.0 but could not figure out how to use NOT BETWEEN OR EQUAL NULL.

答:
You can try this</p>

```<code>  ->andWhere(['NOT',
        ['AND',
        ['>=', 'fromTime', (new \DateTime($from_date))->format('H:i:s')],
        ['<=', 'toTime', (new \DateTime($to_date))->format('H:i:s')]
        ]
    ]);
</code>```

Body:
Working with Yii framework 2.0 I have a database table with the columns 'from_date' and 'to_date'. I would like to select and count all records where:

today is NOT between from_date and to_date. And not even equal these dates (!($from_date <= $today) && !($today <= $to_date))).

OR

from_date is NULL and to_date is NULL. Because in some records these dates are empty, they need to be selected and counted as well.

I have a model which extends the ActiveRecord class, so I could use the following code to retrieve the data:

ModelClass::find()-where('big>small')->andWhere('1<2')->orWhere('3>1')->count();

I tried to read the documentation of Yii 2.0 but could not figure out how to use NOT BETWEEN OR EQUAL NULL.

Body:
You can try this

  ->andWhere(['NOT',
        ['AND',
        ['>=', 'fromTime', (new \DateTime($from_date))->format('H:i:s')],
        ['<=', 'toTime', (new \DateTime($to_date))->format('H:i:s')]
        ]
    ]);


问:
Simple Firebase validation rule (isNumber) not working
Database structure (Firebase Console - Data):

```<code>{
"competitors": {
    0: {
        "name": "Arnold",
        "position": 1
    },
    1: ...
}
</code>```

Rules:

```<code>{
    "rules": {
        ".read": true,
        ".write": true,

        "competitors": {
            "$competitor": {
                "position": {
                    ".validate": "newData.isNumber()"
                }
            }
        }
    }
}
</code>```

When I try to simulate adding a string value from the console simulator, the rule works fine - a violation of the rule is reported. But when I really add or change the position's value as a string (from Firebase console) the value is added without error.

How to correctly set up a validation rule permitting only number values?

UPDATE (based on Oussema's comment)

The following alternative form gives the same result:

```<code>{
    "rules": {
        ".read": true,
        ".write": true,

        "competitors": {
            "$competitor": {
                ".validate": "newData.child('position').isNumber()"
            }
        }
    }
}
</code>```

答:
you need to read the value by using val() like this :

```<code>".validate": "newData.val().isNumber()"
</code>```

Body:
Database structure (Firebase Console - Data):

{
"competitors": {
    0: {
        "name": "Arnold",
        "position": 1
    },
    1: ...
}

Rules:

{
    "rules": {
        ".read": true,
        ".write": true,

        "competitors": {
            "$competitor": {
                "position": {
                    ".validate": "newData.isNumber()"
                }
            }
        }
    }
}

When I try to simulate adding a string value from the console simulator, the rule works fine - a violation of the rule is reported. But when I really add or change the position's value as a string (from Firebase console) the value is added without error.

How to correctly set up a validation rule permitting only number values?

UPDATE (based on Oussema's comment)

The following alternative form gives the same result:

{
    "rules": {
        ".read": true,
        ".write": true,

        "competitors": {
            "$competitor": {
                ".validate": "newData.child('position').isNumber()"
            }
        }
    }
}

Body:
you need to read the value by using val() like this :

".validate": "newData.val().isNumber()"


问:
Pointer_stringify is returning garbled text
I have have the following lib.jslib file

```<code>mergeInto(LibraryManager.library, {
  IsGuestUser: function (objectName, objectMethodName) {
    gamesmart.user.isGuest(function (result) {
      console.log(Pointer_stringify(objectName), Pointer_stringify(objectMethodName), result);
      gameSmartGameInstance.SendMessage(Pointer_stringify(objectName), Pointer_stringify(objectMethodName), result);
    });
  }
});
</code>```

Which gets called from here:

```<code>namespace GameSmart {
  public class User : API {
    [DllImport("__Internal")]
    public static extern void IsGuestUser(string objectName, string objectMethodName);

    public static void IsGuest(string objectName, string objectMethodName) {
      IsGuestUser(objectName, objectMethodName);
    }
  }
}
</code>```

And is initiated like so:

```<code>public class Test : MonoBehaviour {
  void Start() {
    GameSmart.User.IsGuest("GameSmart", "OnIsGuest");
  }
}
</code>```

As seen above I pass GameSmart and OnIsGuest to the JavaScript, and when it gets to the JavaScript I call Pointer_stringify() on both of the values.

When converted and logged, I get the following output: 0Zހ and ﳀ� I should have gotten GameSmart and OnIsGuest back but I didn't what is causing this to happen?

答:
So the fix for this was to move Pointer_stringify outside of the anonymous function so It looks like this:

```<code>mergeInto(LibraryManager.library, {
  IsGuestUser: function (objectName, objectMethodName) {
    var jsObjectName = Pointer_stringify(objectName);
    var jsObjectMethodName = Pointer_stringify(objectMethodName);
    gamesmart.user.isGuest(function (result) {
      gameSmartGameInstance.SendMessage(jsObjectName, jsObjectMethodName, result);
    });
  }
});
</code>```

Body:
I have have the following lib.jslib file

mergeInto(LibraryManager.library, {
  IsGuestUser: function (objectName, objectMethodName) {
    gamesmart.user.isGuest(function (result) {
      console.log(Pointer_stringify(objectName), Pointer_stringify(objectMethodName), result);
      gameSmartGameInstance.SendMessage(Pointer_stringify(objectName), Pointer_stringify(objectMethodName), result);
    });
  }
});

Which gets called from here:

namespace GameSmart {
  public class User : API {
    [DllImport("__Internal")]
    public static extern void IsGuestUser(string objectName, string objectMethodName);

    public static void IsGuest(string objectName, string objectMethodName) {
      IsGuestUser(objectName, objectMethodName);
    }
  }
}

And is initiated like so:

public class Test : MonoBehaviour {
  void Start() {
    GameSmart.User.IsGuest("GameSmart", "OnIsGuest");
  }
}

As seen above I pass GameSmart and OnIsGuest to the JavaScript, and when it gets to the JavaScript I call Pointer_stringify() on both of the values.

When converted and logged, I get the following output: 0Zހ and ﳀ� I should have gotten GameSmart and OnIsGuest back but I didn't what is causing this to happen?

Body:
So the fix for this was to move Pointer_stringify outside of the anonymous function so It looks like this:

mergeInto(LibraryManager.library, {
  IsGuestUser: function (objectName, objectMethodName) {
    var jsObjectName = Pointer_stringify(objectName);
    var jsObjectMethodName = Pointer_stringify(objectMethodName);
    gamesmart.user.isGuest(function (result) {
      gameSmartGameInstance.SendMessage(jsObjectName, jsObjectMethodName, result);
    });
  }
});


问:
Check if an array is empty hence disable a button
Am trying to disable a button if an array isemty but fails

```<code><button [disabled]="(users.length ==0 )?true:false">Send mass emails</button>
</code>```

IN the ts file

```<code>users: UsersModel[];
</code>```

THe above throws an error

```<code>Bindings cannot contain assignments at column
</code>```

How do i disable that button if the array is emty

答:
```<code><button [disabled]="users.length===0?true:false">Send mass emails</button>
</code>```

You can add you condition to the disabled tag like the following. even you can check for the users array then check the length like

```<code><button [disabled]="!user || users.length===0?true:false">Send mass emails</button>
</code>```

Body:
Am trying to disable a button if an array isemty but fails

<button [disabled]="(users.length ==0 )?true:false">Send mass emails</button>

IN the ts file

users: UsersModel[];

THe above throws an error

Bindings cannot contain assignments at column

How do i disable that button if the array is emty

Body:
<button [disabled]="users.length===0?true:false">Send mass emails</button>

You can add you condition to the disabled tag like the following. even you can check for the users array then check the length like

<button [disabled]="!user || users.length===0?true:false">Send mass emails</button>


问:
Linq OrderBy last n values
Lets say i have array of ints:

```<code>int[] values = new int[]{1,2,7,9,8,0};
</code>```

How to OrderBy last 2 values?

```<code>int[] values = new int[]{1,2,7,9,0,8};
</code>```

答:
Using the Generic Enumerable extensions, I came up with this. Don't think its the prettiest thing. Evk's solution looks much cleaner.

```<code>values = values.TakeWhile((n, index) => index < values.Length -2)
        .Concat(
             values.SkipWhile((n, index) => index < values.Length - 2).OrderBy(value => value)
         ).ToArray();
</code>```

Title: Linq OrderBy last n values

Body:
Lets say i have array of ints:

int[] values = new int[]{1,2,7,9,8,0};

How to OrderBy last 2 values?

int[] values = new int[]{1,2,7,9,0,8};

Body:
Using the Generic Enumerable extensions, I came up with this. Don't think its the prettiest thing. Evk's solution looks much cleaner.

values = values.TakeWhile((n, index) => index < values.Length -2)
        .Concat(
             values.SkipWhile((n, index) => index < values.Length - 2).OrderBy(value => value)
         ).ToArray();


问:
Android Data Binding: missing DataBinderMapper class
```<code>java.lang.NoClassDefFoundError: android.databinding.DataBinderMapper
        at android.databinding.DataBindingUtil.<clinit>(DataBindingUtil.java:31)
        at com.example.MainActivity.onCreate(MainActivity.java:13)
        at android.app.Activity.performCreate(Activity.java:5231)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
        at android.app.ActivityThread.access$800(ActivityThread.java:135)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5001)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
        at dalvik.system.NativeStart.main(Native Method)
</code>```

I hope this is a bug, does anyone face a similar problem? I unzipped classes.jar under the exploded-arr folder, but couldn't find the DataBinderMapper class.

Any workarounds / fixes would be appreciated.

答:
I was having this issue this last week, and was having a hard time figuring it out, but finally I discovered that I had two layouts with the same name in different libraries that each use databinding. I'm guessing this was causing the generated binding classes to end up in some kind of bad state at runtime.

I was able to troubleshoot it into a situation where, instead of getting this error on one Fragment, I got a ClassCastException to happen on the Fragment that had a layout with the same name. The generated Binding class was trying to cast a LinearLayout into a RelativeLayout. The only way it could be doing this is if it were trying to use a layout file from a completely different module that had the same name.

After making sure there were no layouts that share the same name -- even across different library modules -- it cleared up.

Body:
java.lang.NoClassDefFoundError: android.databinding.DataBinderMapper
        at android.databinding.DataBindingUtil.<clinit>(DataBindingUtil.java:31)
        at com.example.MainActivity.onCreate(MainActivity.java:13)
        at android.app.Activity.performCreate(Activity.java:5231)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
        at android.app.ActivityThread.access$800(ActivityThread.java:135)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5001)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
        at dalvik.system.NativeStart.main(Native Method)

I hope this is a bug, does anyone face a similar problem? I unzipped classes.jar under the exploded-arr folder, but couldn't find the DataBinderMapper class.

Any workarounds / fixes would be appreciated.


问:
How to attach a jQuery event to a grid view that is not visible on document ready?
I am trying to hook into a link in a gridview with jquery but the grid is in an update panel and not visible until the user runs a report. If I add the class ".myLink" to any other "a" tag it works fine, but as the gridview is not there at document.ready I am not sure where to call this from</p>

```<code>              $(document).ready(function(){
                $('a .myLink').click(function(){
                  var link = $(this).attr('href');
                  alert(link);
                  return false;
                });
              });
</code>```

答:
You can use .live() to handle events on element created at any time, like this:

```<code>$(document).ready(function(){
  $('a .myLink').live('click', function(){
    var link = $(this).attr('href');
    alert(link);
    return false;
  });
});
</code>```

If you have the container that it'll appear in, and it doesn't get replaced, you can use .delegate() to be more efficient, like this:

```<code>$(document).ready(function(){
  $('#containerID').delegate('a .myLink', 'click', function(){
    var link = $(this).attr('href');
    alert(link);
    return false;
  });
});
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am trying to hook into a link in a gridview with jquery but the grid is in an update panel and not visible until the user runs a report. If I add the class ".myLink" to any other "a" tag it works fine, but as the gridview is not there at document.ready I am not sure where to call this from

              $(document).ready(function(){
                $('a .myLink').click(function(){
                  var link = $(this).attr('href');
                  alert(link);
                  return false;
                });
              });

Body:
You can use .live() to handle events on element created at any time, like this:

$(document).ready(function(){
  $('a .myLink').live('click', function(){
    var link = $(this).attr('href');
    alert(link);
    return false;
  });
});

If you have the container that it'll appear in, and it doesn't get replaced, you can use .delegate() to be more efficient, like this:

$(document).ready(function(){
  $('#containerID').delegate('a .myLink', 'click', function(){
    var link = $(this).attr('href');
    alert(link);
    return false;
  });
});


问:
Lua - how to simulate "multithreading"?
I have 2 functions:

```<code>function func1()
   while true do
       -- listen on connection
   end
end

function func2()
   while true do
       -- execute other code
   end
end
</code>```

I want to run both functions "simultaneously" while sharing variables between them. I have tried to create a dispatcher that makes a coroutine with the two functions but I can't think of a way to schedule them to quickly alternate their execution. (func1 runs for a second, func2 runs for a second, func1 runs for a second, and so on)

答:
Lua does not support asynchronous multithreading. It only supports cooperative threading. That means the two "threads" have to be designed to give the other thread time to execute. Such designs are usually highly dependent on what you're trying to accomplish.

Your example talks about one thread listening for a connection and the other thread doing something (either with data from that connection or not; it's not exactly clear). In such a system, it would be a good idea to have func1 invoke the thread for func2 when the connection hasn't provided new data. And func2 would return control back to func1 only when it has finished processing something.

But there is no one-size-fits-all solution to cooperative multithreading.

Title: Lua - how to simulate "multithreading"?

Body:
I have 2 functions:

function func1()
   while true do
       -- listen on connection
   end
end

function func2()
   while true do
       -- execute other code
   end
end

I want to run both functions "simultaneously" while sharing variables between them. I have tried to create a dispatcher that makes a coroutine with the two functions but I can't think of a way to schedule them to quickly alternate their execution. (func1 runs for a second, func2 runs for a second, func1 runs for a second, and so on)


问:
Tags are appearing in left of the document in embedded Signing using template

``code`       DocuSignTK.Recipient recipient = new DocuSignTK.Recipient();
        recipient.Email = signer_email; // This person will use embedded signing. If you have his
            // email, supply it. If you don't, use a fake email that includes your
            // ClientUserID. Eg embedded_signer_{ClientUserID}@your_company.com
        recipient.UserName = signer_name;
        recipient.ID = 1;
        recipient.Type_x = 'Signer';
        recipient.RoutingOrder = 1;
        recipient.RoleName = 'Signer1';
        // We want this signer to be "captive" so we can use embedded signing with him
        recipient.CaptiveInfo = new DocuSignTK.RecipientCaptiveInfo();
        recipient.CaptiveInfo.ClientUserID = signer_user_id; // Must uniquely identify the

        // Create the recipient information
        DocuSignTK.ArrayOfRecipient1 recipients = new DocuSignTK.ArrayOfRecipient1();
        recipients.Recipient = new DocuSignTK.Recipient[1];
        recipients.Recipient[0] = recipient;

        DocuSignTK.ArrayOfTemplateReferenceRoleAssignment Roles = new DocuSignTK.ArrayOfTemplateReferenceRoleAssignment();
        Roles.RoleAssignment = new DocuSignTK.TemplateReferenceRoleAssignment[1];
        DocuSignTK.TemplateReferenceRoleAssignment role = new DocuSignTK.TemplateReferenceRoleAssignment();
        role.RoleName = 'Signer1';
        role.RecipientID = 1;
        Roles.RoleAssignment[0] = role;

        // Create the template reference from a server-side template ID
        DocuSignTK.TemplateReference templateReference = new DocuSignTK.TemplateReference();
        templateReference.Template = 'd0d80082-612b-4a04-b2a1-0672eb720491';
        templateReference.TemplateLocation = 'Server';

        templateReference.RoleAssignments = Roles;

        // Construct the envelope information
        DocuSignTK.EnvelopeInformation envelopeInfo = new DocuSignTK.EnvelopeInformation();
        envelopeInfo.AccountId = account_Id;
        envelopeInfo.Subject = 'Subject';
        envelopeInfo.EmailBlurb = 'Email content';

        // Make the call
        try {
            //DocuSignTK.EnvelopeStatus result = api_sender.CreateAndSendEnvelope(envelope);
            // Create draft with all the template information
            DocuSignTK.ArrayOfTemplateReference TemplateReferenceArray = new DocuSignTK.ArrayOfTemplateReference();
            TemplateReferenceArray.TemplateReference = new DocuSignTK.TemplateReference[1];
            TemplateReferenceArray.TemplateReference[0] = templateReference;
            DocuSignTK.EnvelopeStatus result = api_sender.CreateEnvelopeFromTemplates( TemplateReferenceArray, recipients, envelopeInfo, true);
            envelope_id = result.EnvelopeID;
            System.debug('Returned successfully, envelope_id = ' + envelope_id );
        } catch ( CalloutException e) {
            System.debug('Exception - ' + e );
            error_code = 'Problem: ' + e;
            error_message = error_code;
        }  `code`````

I am integrating Docusign for embedded signing. I am using SOAP API and used method CreateEnvelopeFromTemplates . Template I created is having some fields/Tabs. But once I open signing url these fields are located on side of the document instead of the location which I sent in template.

I have also assigned Role name for recipient but it is not working. Please help.

Click here to see screenshot

答: I downloaded a template from production and uploaded in sandbox but once I recreated similar template in Sandbox only and used it's template ID in code then it is working perfectly. Apparently, There seems to be some issue with import template utility of Docusign.  </p>

Body:
``code`       DocuSignTK.Recipient recipient = new DocuSignTK.Recipient();
        recipient.Email = signer_email; // This person will use embedded signing. If you have his
            // email, supply it. If you don't, use a fake email that includes your
            // ClientUserID. Eg embedded_signer_{ClientUserID}@your_company.com
        recipient.UserName = signer_name;
        recipient.ID = 1;
        recipient.Type_x = 'Signer';
        recipient.RoutingOrder = 1;
        recipient.RoleName = 'Signer1';
        // We want this signer to be "captive" so we can use embedded signing with him
        recipient.CaptiveInfo = new DocuSignTK.RecipientCaptiveInfo();
        recipient.CaptiveInfo.ClientUserID = signer_user_id; // Must uniquely identify the

        // Create the recipient information
        DocuSignTK.ArrayOfRecipient1 recipients = new DocuSignTK.ArrayOfRecipient1();
        recipients.Recipient = new DocuSignTK.Recipient[1];
        recipients.Recipient[0] = recipient;

        DocuSignTK.ArrayOfTemplateReferenceRoleAssignment Roles = new DocuSignTK.ArrayOfTemplateReferenceRoleAssignment();
        Roles.RoleAssignment = new DocuSignTK.TemplateReferenceRoleAssignment[1];
        DocuSignTK.TemplateReferenceRoleAssignment role = new DocuSignTK.TemplateReferenceRoleAssignment();
        role.RoleName = 'Signer1';
        role.RecipientID = 1;
        Roles.RoleAssignment[0] = role;

        // Create the template reference from a server-side template ID
        DocuSignTK.TemplateReference templateReference = new DocuSignTK.TemplateReference();
        templateReference.Template = 'd0d80082-612b-4a04-b2a1-0672eb720491';
        templateReference.TemplateLocation = 'Server';

        templateReference.RoleAssignments = Roles;

        // Construct the envelope information
        DocuSignTK.EnvelopeInformation envelopeInfo = new DocuSignTK.EnvelopeInformation();
        envelopeInfo.AccountId = account_Id;
        envelopeInfo.Subject = 'Subject';
        envelopeInfo.EmailBlurb = 'Email content';

        // Make the call
        try {
            //DocuSignTK.EnvelopeStatus result = api_sender.CreateAndSendEnvelope(envelope);
            // Create draft with all the template information
            DocuSignTK.ArrayOfTemplateReference TemplateReferenceArray = new DocuSignTK.ArrayOfTemplateReference();
            TemplateReferenceArray.TemplateReference = new DocuSignTK.TemplateReference[1];
            TemplateReferenceArray.TemplateReference[0] = templateReference;
            DocuSignTK.EnvelopeStatus result = api_sender.CreateEnvelopeFromTemplates( TemplateReferenceArray, recipients, envelopeInfo, true);
            envelope_id = result.EnvelopeID;
            System.debug('Returned successfully, envelope_id = ' + envelope_id );
        } catch ( CalloutException e) {
            System.debug('Exception - ' + e );
            error_code = 'Problem: ' + e;
            error_message = error_code;
        }  `code``

I am integrating Docusign for embedded signing. I am using SOAP API and used method CreateEnvelopeFromTemplates . Template I created is having some fields/Tabs. But once I open signing url these fields are located on side of the document instead of the location which I sent in template.

I have also assigned Role name for recipient but it is not working. Please help.

Click here to see screenshot


问:
Deedle: Setting header names when using SaveCsv
I'm trying to use Deedle to save .csv files

```<code>type all_trades_schema = CsvProvider<"/trading/backtesting/strategy logs/all_trades.csv">

(new_trades |> Frame.ofRecords).SaveCsv(log_dirname+"/new_trades.csv")
</code>```

the problem I have is that the original (template) file has column names,
but the new file doesn't have any column names.

How can i fix my (little) problem ? thanks

(of note, my first column is DateTime, the others are float, but if this is important i'd like to know the right syntax when there are other types)

答:
When you create Deedle frame from rows returned by the CSV provider using Frame.ofRecords, it unfortunately does not automatically get the column names, because the CSV provider represents those as a tuple - so the names are just Item1, Item2 and so on, matching the property names of standard .NET tuple type.

To fix this, you can use Frame.indexColsWith which lets you replace the column names:

```<code>let headers = match csv.Headers with Some v -> v | _ -> failwith "No headers!"
let df =
  csv.Rows
  |> Frame.ofRecords
  |> Frame.indexColsWith headers

df.SaveCsv(log_dirname+"/new_trades.csv")
</code>```

You can specify keyNames if you want to include the row keys - those are just ordinal numbers by default, in which case, you probably don't want to include them:

```<code>df.SaveCsv(log_dirname+"/new_trades.csv", includeRowKeys=false)
</code>```

If you index your data so that e.g. the date is the index, then you can use:

```<code>df.SaveCsv(log_dirname+"/new_trades.csv", includeRowKeys=true,keyNames=["Date"])
</code>```

Note that the name keyNames slightly misleadingly suggests that that you need to specify multiple names - this is only the case when you have multi-level indices, but that's somewhat odd and rarely used Deedle feature.

Body:
I'm trying to use Deedle to save .csv files

type all_trades_schema = CsvProvider<"/trading/backtesting/strategy logs/all_trades.csv">

(new_trades |> Frame.ofRecords).SaveCsv(log_dirname+"/new_trades.csv")

the problem I have is that the original (template) file has column names,
but the new file doesn't have any column names.

How can i fix my (little) problem ? thanks

(of note, my first column is DateTime, the others are float, but if this is important i'd like to know the right syntax when there are other types)

Body:
When you create Deedle frame from rows returned by the CSV provider using Frame.ofRecords, it unfortunately does not automatically get the column names, because the CSV provider represents those as a tuple - so the names are just Item1, Item2 and so on, matching the property names of standard .NET tuple type.

To fix this, you can use Frame.indexColsWith which lets you replace the column names:

let headers = match csv.Headers with Some v -> v | _ -> failwith "No headers!"
let df =
  csv.Rows
  |> Frame.ofRecords
  |> Frame.indexColsWith headers

df.SaveCsv(log_dirname+"/new_trades.csv")

You can specify keyNames if you want to include the row keys - those are just ordinal numbers by default, in which case, you probably don't want to include them:

df.SaveCsv(log_dirname+"/new_trades.csv", includeRowKeys=false)

If you index your data so that e.g. the date is the index, then you can use:

df.SaveCsv(log_dirname+"/new_trades.csv", includeRowKeys=true,keyNames=["Date"])

Note that the name keyNames slightly misleadingly suggests that that you need to specify multiple names - this is only the case when you have multi-level indices, but that's somewhat odd and rarely used Deedle feature.


问:
How to link React.js file to html
I just installed this Create React Apps program from here https://github.com/facebookincubator/create-react-app and I have all the files downloaded and I am able to edit the App.js file, but I already have made some html files for a website, I want to know how to link the App.js file to my current files. The html on the given Index.html, shows no

答: I'm not entirely sure what you are asking, but you can have normal html/css on the same page as React. React is rendering the App component in the div id="root" section of the page. Elsewhere, you can just paste your old html stuff and it should work.

Title: How to link React.js file to html


问:
Android ble device is not disconnecting sometime

After doing disconnecte ble device i am getting disconnect callback . but some time still it is not disconnected . in some layer connection state is maintaining . so that i am not able to do reconnect.

i have tested in android 5   & android 6.
in HTC One A9, Moto x play, Moto G4

If i do bluetooth turn on off. then again disconnect callback is coming and device is disconnecting actually.
-Please give some suggestion for resolve issue.

I am doing below steps for ble operation

1.Discover ble device.

Connect  to device.

onConnectionStateChange (connected) i am doing  gatt.discoverServices()

onServicesDiscovered callback i am reading characteristics
5.onCharacteristicRead callback  i am doing write characteristics.
6.onCharacteristicWrite call back i am doing gatt.disconnect()

onConnectionStateChange (disconnected) i am doing gatt.close()

In this full process in background device scanning is going on.

答:
this problem can be connected with not calling stopScan() method.
see comment from SoroushA
Totally Disconnect a Bluetooth Low Energy Device</p>


问:
C# - Selecting nested model property using a dynamic name
I have a variable this will be dynamic.

```<code>string Property_Name = "Email";
</code>```

I have a model for example.

```<code>AccountModel Model = new AccountModel();
</code>```

Which has a property called...

```<code>string Email { get; set;}
</code>```

I want to select a property in the Model using the dynamic name.

```<code>Model.Property_Name
</code>```

Is this possible ? Thanks

答:
You can achieve that by using reflection

```<code>var value = Model.GetType().GetProperty(Property_Name).GetValue(Model, null);
</code>```

don't forget using System.Reflection;

Body:
I have a variable this will be dynamic.

string Property_Name = "Email";

I have a model for example.

AccountModel Model = new AccountModel();

Which has a property called...

string Email { get; set;}

I want to select a property in the Model using the dynamic name.

Model.Property_Name

Is this possible ? Thanks

Body:
You can achieve that by using reflection

var value = Model.GetType().GetProperty(Property_Name).GetValue(Model, null);

don't forget using System.Reflection;


问:
Work with keyboard via Win Api
How I can work with keyboard via Win Api? I need check specific keyboard key for these things: hold, press, release. I can't use Windows Message, just only Win API function. I already done check hold:

```<code>bool result;
result=false;
if(GetAsyncKeyState(MapVirtualKey(code,MAPVK_VSC_TO_VK))==-32767) result=true;
return result;
</code>```

How I can check press and check release?

Press is just single key down. Release is key up after key press

答:
A normal application should use the key and char messages when dealing with input in its own window.

If you need to track keyboard events outside of your thread or even system-wide then you should use a low-level keyboard hook.

GetAsyncKeyState is not the best API to use to track key states over time, it just reports what the state is right now. You cannot poll it in a tight loop and guarantee that you never miss a key event. You should also use a < 0 check (or & 0x8000) to see if the key is down, not ==.

GetKeyState is useful if you need to check the state of Ctrl/Shift/Alt when processing a input message.

Title: Work with keyboard via Win Api

Body:
How I can work with keyboard via Win Api? I need check specific keyboard key for these things: hold, press, release. I can't use Windows Message, just only Win API function. I already done check hold:

bool result;
result=false;
if(GetAsyncKeyState(MapVirtualKey(code,MAPVK_VSC_TO_VK))==-32767) result=true;
return result;

How I can check press and check release?

Press is just single key down. Release is key up after key press


问:
PHP performance question
Wondering which would be better for performance. The site will be viewed by people that are logged in and people that are not. The site is almost the same for the users that are logged in except they have more privledges. So I am wondering what would be more efficient.

//OPTION ONE

```<code>if(isLoggedIn()){
Write the whole web site plus the content the logged in user can access
}
else {
Write the whole website again, minus the content the logged in users can access.
}

//OPTION TWO
Write the website content and inset the login function wherever i need to restrict the access, so the function would be called a few different times.
</code>```

I am wondering if it would be better for performance using option one because the function would first be checked once, and wouldn't need to be checked again, if the user is logged in the first chunk would be loaded, if the user is not logged in, it would ignore the first chunk and load the second chunk.

答: Neither. The best option is to check for isLoggedIn once, save the result, and do ifs inside the source to swap in each place.</p>

Title: PHP performance question

Body:
Wondering which would be better for performance. The site will be viewed by people that are logged in and people that are not. The site is almost the same for the users that are logged in except they have more privledges. So I am wondering what would be more efficient.

//OPTION ONE

if(isLoggedIn()){
Write the whole web site plus the content the logged in user can access
}
else {
Write the whole website again, minus the content the logged in users can access.
}

//OPTION TWO
Write the website content and inset the login function wherever i need to restrict the access, so the function would be called a few different times.

I am wondering if it would be better for performance using option one because the function would first be checked once, and wouldn't need to be checked again, if the user is logged in the first chunk would be loaded, if the user is not logged in, it would ignore the first chunk and load the second chunk.


问:
PHP protected file access
I am using Martin Barker's code/answer from ( PHP to protect PDF and DOC ) almost verbatum, only difference is the file I am protecting is in my user folder above the public_html folder

Folder structure

```<code>/users/websupport
/public_html
</code>```

File to download is at:

```<code>/users/websupport/FileToDownload.pdf
</code>```

The download.php file is at

```<code>/public_html/download.php
</code>```

but Firefox tells me it cannot find the file at Firefox can't find the file at download.php.

I have verified that the file is there via ftp.

If placing the file outside the webroot do I need to add something to the sites .htaccess ? Just not sure where I am going wrong with this. Below is the code within download.php

```<code>//check users is loged in and valid for download if not redirect them out
// YOU NEED TO ADD CODE HERE FOR THAT CHECK
// array of support file types for download script and there mimetype
$mimeTypes = array(
    'doc' => 'application/msword',
    'pdf' => 'application/pdf',
);
// set the file here (best of using a $_GET[])
$file = "../users/websupport/2011cv.pdf";

// gets the extension of the file to be loaded for searching array above
$ext = explode('.', $file);
$ext = end($ext);

// gets the file name to send to the browser to force download of file
$fileName = explode("/", $file);
$fileName = end($fileName);

// opens the file for reading and sends headers to browser
$fp = fopen($file,"r") ;
header("Content-Type: ".$mimeTypes[$ext]);
header('Content-Disposition: attachment; filename="'.$fileName.'"');

// reads file and send the raw code to browser
while (! feof($fp)) {
    $buff = fread($fp,4096);
    echo $buff;
}
// closes file after whe have finished reading it
fclose($fp);
</code>```

答:
I had the same issue recently where readfile() and fpassthru() just would not work on my server.

What I ended up doing was creating symlinks for the files as needed and passing those to the user. You can learn how to create symlinks here.

I used

exec("ln -s source_file_full_path full_path_to_fake_file");

if you wanted your user to have a link like 'http://somesite.com/folder/fake_file.pdf' then the full path would be to where 'folder' lives on your server and you would include 'fake_file.pdf' in your fake file path.

then to expire the links I made another call to find all of the symlinks with a creation date older than x minutes. You can see how to do that in this answer. (That could be a cron job to ensure they expire on time.)

Title: PHP protected file access

Body:
I am using Martin Barker's code/answer from ( PHP to protect PDF and DOC ) almost verbatum, only difference is the file I am protecting is in my user folder above the public_html folder

Folder structure

/users/websupport
/public_html

File to download is at:

/users/websupport/FileToDownload.pdf

The download.php file is at

/public_html/download.php

but Firefox tells me it cannot find the file at Firefox can't find the file at download.php.

I have verified that the file is there via ftp.

If placing the file outside the webroot do I need to add something to the sites .htaccess ? Just not sure where I am going wrong with this. Below is the code within download.php

//check users is loged in and valid for download if not redirect them out
// YOU NEED TO ADD CODE HERE FOR THAT CHECK
// array of support file types for download script and there mimetype
$mimeTypes = array(
    'doc' => 'application/msword',
    'pdf' => 'application/pdf',
);
// set the file here (best of using a $_GET[])
$file = "../users/websupport/2011cv.pdf";

// gets the extension of the file to be loaded for searching array above
$ext = explode('.', $file);
$ext = end($ext);

// gets the file name to send to the browser to force download of file
$fileName = explode("/", $file);
$fileName = end($fileName);

// opens the file for reading and sends headers to browser
$fp = fopen($file,"r") ;
header("Content-Type: ".$mimeTypes[$ext]);
header('Content-Disposition: attachment; filename="'.$fileName.'"');

// reads file and send the raw code to browser
while (! feof($fp)) {
    $buff = fread($fp,4096);
    echo $buff;
}
// closes file after whe have finished reading it
fclose($fp);


问:
Log4Net.Async issue in ASP.NET MVC
I keep receiving following error:

```<code>log4net:ERROR Could not create Appender [AsyncLog4NetAppender] of type [Log4Net.Async.ParallelForwardingAppender]. Reported error follows.
System.TypeLoadException: Could not load type [Log4Net.Async.ParallelForwardingAppender]. Tried assembly [log4net, Version=2.0.8.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a] and all loaded assemblies
   at log4net.Util.SystemInfo.GetTypeFromString(Assembly relativeAssembly, String typeName, Boolean throwOnError, Boolean ignoreCase)
   at log4net.Util.SystemInfo.GetTypeFromString(String typeName, Boolean throwOnError, Boolean ignoreCase)
   at log4net.Repository.Hierarchy.XmlHierarchyConfigurator.ParseAppender(XmlElement appenderElement)
log4net:ERROR Appender named [AsyncLog4NetAppender] not found.
</code>```

Packages config

```<code><package id="log4net" version="2.0.8" targetFramework="net451" />
<package id="Log4Net.Async" version="2.0.4" targetFramework="net451" />
</code>```

Web config

```<code>  <dependentAssembly>
    <assemblyIdentity name="log4net" publicKeyToken="669e0ddf0bb1aa2a" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-2.0.8.0" newVersion="2.0.8.0"/>
  </dependentAssembly>
</code>```

When I remove the log4net.async nuget package and add it again it works. But after some time I get this error again.

答:
You (probably) need to add the assembly name to your appender reference.

```<code><appender name="AsyncLog4NetAppender" type="Log4Net.Async.ParallelForwardingAppender,Log4Net.Async">
</code>```

Note the part after the comma, Log4Net.Async.

Adding the name of the reference assembly should tell .Net how to find the class in the appropriate assembly.

Title: Log4Net.Async issue in ASP.NET MVC

Body:
I keep receiving following error:

log4net:ERROR Could not create Appender [AsyncLog4NetAppender] of type [Log4Net.Async.ParallelForwardingAppender]. Reported error follows.
System.TypeLoadException: Could not load type [Log4Net.Async.ParallelForwardingAppender]. Tried assembly [log4net, Version=2.0.8.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a] and all loaded assemblies
   at log4net.Util.SystemInfo.GetTypeFromString(Assembly relativeAssembly, String typeName, Boolean throwOnError, Boolean ignoreCase)
   at log4net.Util.SystemInfo.GetTypeFromString(String typeName, Boolean throwOnError, Boolean ignoreCase)
   at log4net.Repository.Hierarchy.XmlHierarchyConfigurator.ParseAppender(XmlElement appenderElement)
log4net:ERROR Appender named [AsyncLog4NetAppender] not found.

Packages config

<package id="log4net" version="2.0.8" targetFramework="net451" />
<package id="Log4Net.Async" version="2.0.4" targetFramework="net451" />

Web config

  <dependentAssembly>
    <assemblyIdentity name="log4net" publicKeyToken="669e0ddf0bb1aa2a" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-2.0.8.0" newVersion="2.0.8.0"/>
  </dependentAssembly>

When I remove the log4net.async nuget package and add it again it works. But after some time I get this error again.

Body:
You (probably) need to add the assembly name to your appender reference.

<appender name="AsyncLog4NetAppender" type="Log4Net.Async.ParallelForwardingAppender,Log4Net.Async">

Note the part after the comma, Log4Net.Async.

Adding the name of the reference assembly should tell .Net how to find the class in the appropriate assembly.


问:
Sed only with specific place
For example;

I'd love to replace /test src path only within  tag.

However
test
 should not be touched.

```<code>$ cat test.html
<img src="/test" width="18" alt="" /><br>
<p>test</p>
</code>```

For now I could execute something like;

```<code>sed -i '/test'|/hoge|g' test.html
</code>```

However it changes the word globally.

答:
Another approach with sed:

```<code>sed -i 's|\(<img *src="/\)test|\1hoge|'  test.html
</code>```

<img *src="/ is captured and backreferenced using \1 in substitution string.
Following string(test) is replaced with hoge.

Title: Sed only with specific place

Body:
For example;

I'd love to replace /test src path only within  tag.

However
test
 should not be touched.

$ cat test.html

test

For now I could execute something like;

sed -i '/test'|/hoge|g' test.html

However it changes the word globally.

Body:
Another approach with sed:

sed -i 's|\(<img *src="/\)test|\1hoge|'  test.html

<img *src="/ is captured and backreferenced using \1 in substitution string.
Following string(test) is replaced with hoge.


问:
Red5 changing the default location of storing media files
I've just started playing with Red5 and am developing an app using which users can record video messages.
Now by default the video files are being saved in

C:\Program Files\Red5\webapps\webcam_recorder\streams

I am trying to figure out how I can change the default location and say be able to save it in c:\streams instead

Secondly once I deploy to prod, my idea is to save these video files on Amazon S3 and have red5 stream from there. Is that possible. If so where in the config will I specify this change.

Thanks a lot for your responses.

答:
I was able to follow the instructions on this links and change the default location
Hope it helps others:

http://www.red5tutorials.net/index.php/Tutorials:Streaming_from_custom_directories


问:
How to load mock data from JSON file in Angular 2 karma jasmine test?
I am writing karma jasmine test case for angular 2,

And we came across requirement to mock data in separate JSON file as data is huge (want to make sure code cleanness). For this I searched a lot but didn't find proper solution.

We already mocking HTTP service using MockBackend, So we can't use HTTP service of angular to load JSON as it eventually request will go to MockBackend.

So is there any another way without using any third party lib like
jasmine-jquery or   Karma-jasmine-preprocessor ? More kind of Angular JS 2 way.

答:
I had the same issue!

Finally, I realized that just using the require() function directly in TypeScript works just fine. It is supported by Node and @types/node, otherwise some need to declare require types.

So to load mock data from JSON file in Angular 2 Karma Jasmine test, go for:

```<code>const data: any = require('../../assets/mock-data.json');
</code>```

PS: credits to Artur Ampilogov

ContentLicense: CC BY-SA 4.0

Body:
I had the same issue!

Finally, I realized that just using the require() function directly in TypeScript works just fine. It is supported by Node and @types/node, otherwise some need to declare require types.

So to load mock data from JSON file in Angular 2 Karma Jasmine test, go for:

const data: any = require('../../assets/mock-data.json');

PS: credits to Artur Ampilogov