问:
Flask is not importing even though I installed it
I'm on Windows 10 and I am using PyCharm to run my application. I'm pretty new to Python and just coding in general.

I typed:

```<code>pip install flask
</code>```

in the cmd prompt but forgot to open cmd prompt under administrator privileges. Could this be the problem? I ended up re-opening the cmd prompt with administrator rights and typed

```<code>pip install flask
</code>```

again and it showed that it was already installed. I'm pretty sure I have flask installed on my system.

When I try to run the python file below which I named test_webapp.py I get the following error:

```<code>from flask import Flask

app = Flask(__name__)

@app.route("/")

def hello():

    return "Hello World!"

if __name__ == "__main__":

    app.run()
</code>```

I get an error:

ModuleNotFoundError: No module named 'flask'

when i type in python --version into the command prompt i get version 3.6.3.

When i type the same code into the Python 3.6 (32-bit) command line, the code works! However, when i try to run it using the IDLE I get a SyntaxError and the number 6 in Python 3.6.3 gets highlighted in red.

Any ideas as to what's going on?

答:
Sounds like the pip you are using is not installing for the same python you are using.

try which pip and which python

the they should be in the same folder. Might want to make an alias or two if you have a bunch of pythons (sys, 2, 3, conda etc) or just start with a fresh virtual env for your project. <- best imo.

Body:
I'm on Windows 10 and I am using PyCharm to run my application. I'm pretty new to Python and just coding in general.

I typed:

pip install flask

in the cmd prompt but forgot to open cmd prompt under administrator privileges. Could this be the problem? I ended up re-opening the cmd prompt with administrator rights and typed

pip install flask

again and it showed that it was already installed. I'm pretty sure I have flask installed on my system.

When I try to run the python file below which I named test_webapp.py I get the following error:

from flask import Flask

app = Flask(__name__)

@app.route("/")

def hello():

    return "Hello World!"

if __name__ == "__main__":

    app.run()

I get an error:

ModuleNotFoundError: No module named 'flask'

when i type in python --version into the command prompt i get version 3.6.3.

When i type the same code into the Python 3.6 (32-bit) command line, the code works! However, when i try to run it using the IDLE I get a SyntaxError and the number 6 in Python 3.6.3 gets highlighted in red.

Any ideas as to what's going on?


来源: stackexchange

问:
Angular async not resolving timeouts
It looks like Angular's async from @angular/core/testing isn't resolving timeouts in tests with async when there's a beforeEach with async as well.
 Unfortunately, I haven't been able to reproduce this bug on any kind of Plunkr or JSFiddle.

The easiest way to recreate it is to simple create a fresh new Angular CLI app and paste this code into the app.component.spec.ts:

```<code>import { async } from "@angular/core/testing";

describe("test async", () => {

   let count: number = 0;

   beforeEach(async(() => {
       count++;
       console.log('async before test ' + count);
       setTimeout(() => {
           console.log('timeout before test ' + count);
       }, 1000);
   }))

   it("async test 1", async(() => {
       console.log('starting test 1');
       setTimeout(() => {
           console.log('test 1 finished');
           console.log('expected count: 1, actual count: ' + count);
           expect(count).toBe(1, "should be test 1");
       }, 2000);
   }));

   it("async test 2", async(() => {
       console.log('starting test 2');
       setTimeout(() => {
           console.log('test 2 finished');
           console.log('expected count: 2, actual count: ' + count);
           expect(count).toBe(2, "should be test 2");
       }, 2000);
   }));

   it("async test 3", async(() => {
       console.log('starting test 3');
       setTimeout(() => {
           console.log('test 3 finished');
           console.log('expected count: 3, actual count: ' + count);
           expect(count).toBe(3, "should be test 3");
       }, 2000);
   }));
});
</code>```

If you then run this test, you should see the output as follows:

```<code>async before test 1
timeout before test 1
starting test 1
async before test 2
timeout before test 2
starting test 2
async before test 3
test 1 finished
expected count: 1, actual count: 3
timeout before test 3
starting test 3
test 2 finished
expected count: 2, actual count: 3
test 3 finished
expected count: 3, actual count: 3
</code>```

But that is incorrect from my understanding because the timeouts in the tests should complete before the next test starts, which is the whole point of async.

This is what the output would look like if it was working correctly:

```<code>async before test 1
timeout before test 1
starting test 1
test 1 finished
expected count: 1, actual count: 1
async before test 2
timeout before test 2
starting test 2
test 2 finished
expected count: 2, actual count: 2
async before test 3
timeout before test 3
starting test 3
test 3 finished
expected count: 3, actual count: 3
</code>```

Any help would be greatly appreciated, thanks!

答:
async from @angular/core/testing isn't resolving timeouts in tests with async when there's a beforeEach with async as well

async only resolves Promises not setTimeout. You can wrap setTimeout in a delay function

```<code>const delay = (ms) => new Promise(res => setTimeout(res,ms));
</code>```

ContentLicense: CC BY-SA 3.0

Title: Angular async not resolving timeouts

Body:
It looks like Angular's async from @angular/core/testing isn't resolving timeouts in tests with async when there's a beforeEach with async as well.
 Unfortunately, I haven't been able to reproduce this bug on any kind of Plunkr or JSFiddle.

The easiest way to recreate it is to simple create a fresh new Angular CLI app and paste this code into the app.component.spec.ts:

import { async } from "@angular/core/testing";

describe("test async", () => {

   let count: number = 0;

   beforeEach(async(() => {
       count++;
       console.log('async before test ' + count);
       setTimeout(() => {
           console.log('timeout before test ' + count);
       }, 1000);
   }))

   it("async test 1", async(() => {
       console.log('starting test 1');
       setTimeout(() => {
           console.log('test 1 finished');
           console.log('expected count: 1, actual count: ' + count);
           expect(count).toBe(1, "should be test 1");
       }, 2000);
   }));

   it("async test 2", async(() => {
       console.log('starting test 2');
       setTimeout(() => {
           console.log('test 2 finished');
           console.log('expected count: 2, actual count: ' + count);
           expect(count).toBe(2, "should be test 2");
       }, 2000);
   }));

   it("async test 3", async(() => {
       console.log('starting test 3');
       setTimeout(() => {
           console.log('test 3 finished');
           console.log('expected count: 3, actual count: ' + count);
           expect(count).toBe(3, "should be test 3");
       }, 2000);
   }));
});

If you then run this test, you should see the output as follows:

async before test 1
timeout before test 1
starting test 1
async before test 2
timeout before test 2
starting test 2
async before test 3
test 1 finished
expected count: 1, actual count: 3
timeout before test 3
starting test 3
test 2 finished
expected count: 2, actual count: 3
test 3 finished
expected count: 3, actual count: 3

But that is incorrect from my understanding because the timeouts in the tests should complete before the next test starts, which is the whole point of async.

This is what the output would look like if it was working correctly:

async before test 1
timeout before test 1
starting test 1
test 1 finished
expected count: 1, actual count: 1
async before test 2
timeout before test 2
starting test 2
test 2 finished
expected count: 2, actual count: 2
async before test 3
timeout before test 3
starting test 3
test 3 finished
expected count: 3, actual count: 3

Any help would be greatly appreciated, thanks!

Body:
async from @angular/core/testing isn't resolving timeouts in tests with async when there's a beforeEach with async as well

async only resolves Promises not setTimeout. You can wrap setTimeout in a delay function

const delay = (ms) => new Promise(res => setTimeout(res,ms));


问:
Parcel Number from Google Places API?
Does anyone know if Google Places or perhaps another API is able to look up a property APN (assessor's parcel number) by address?

I'm using Google Places to get the address and update fields in a form, and I'd also like to populate the APN field based on the property address.

答:
Disclaimer, the API is not publicly available, but you can request an invitation here:
https://rets.ly/docs/platform.html

My first thought was the Zillow API but I don't think they provide APNs.

The Bridge, formarly Rets.ly API, allows you to query by lat/lng and get back a parcel number. AFAIK they won't geocode for you, but if you are already using a google api, you should be able to get them to geocode, and then pass the lat/lng onto Bridge.

An example GET request might look like

```<code>https://rets.io/api/v2/pub/parcels?access_token=$token&near=41.9171124,-87.6475581&limit=1
</code>```

with a response like

```<code>{
  "success": true,
  "status": 200,
  "bundle": [
    {
      "id": "372176",
      "fips": "17031",
      "apn": "14333001270000",
      "county": "Cook",
      "state": "IL",
   //...
</code>```

Title: Parcel Number from Google Places API?

Body:
Disclaimer, the API is not publicly available, but you can request an invitation here:
https://rets.ly/docs/platform.html

My first thought was the Zillow API but I don't think they provide APNs.

The Bridge, formarly Rets.ly API, allows you to query by lat/lng and get back a parcel number. AFAIK they won't geocode for you, but if you are already using a google api, you should be able to get them to geocode, and then pass the lat/lng onto Bridge.

An example GET request might look like

https://rets.io/api/v2/pub/parcels?access_token=$token&near=41.9171124,-87.6475581&limit=1

with a response like

{
  "success": true,
  "status": 200,
  "bundle": [
    {
      "id": "372176",
      "fips": "17031",
      "apn": "14333001270000",
      "county": "Cook",
      "state": "IL",
   //...


问:
SQL condition: (A=B AND C LIKE %D%) OR (A LIKE %B% AND C=D)
I've got a table of first names and last names.

I'm trying to make a jQuery instant search on an input, in order to find very quickly and precisely a person in a huge list of people.

When the first word is entered in the input, it might be the first name or the last name.

I do this : SELECT * FROM myTable WHERE firstName LIKE %content% OR lastName LIKE %content%

When two words are entered, it might be:
* the full firstname and a bit of the lastname
* the full lastname and a bit of the firstame

So I tried this query : SELECT * FROM myTable WHERE (firstName = content1 AND lastName LIKE %content2%) OR ( lastName = content1 AND firstName LIKE %content2%)

Unfortunately parenthesis seems to do nothing, and the query is not interpreted this way, I've got a lot of results, basically produced by the two LIKE %% condition

Anyone had deal with this before and could give me a hand?

Thanx

答: I believe you are going to need to split the two words entered and use them indepenently in your query.</p>

ContentLicense: CC BY-SA 2.5


问:
Falied to resolve endpoint in apache camel
I am working on a spring mvc application and i am using apache camel to send message.When i run my code in test case it show to me error failed to resolve endpoint.It is my code:</p>

```<code>  CamelContext camelContext = new DefaultCamelContext();
    ProducerTemplate producerTemplate = camelContext.createProducerTemplate();
    producerTemplate.requestBody(
            "jetty:http://here my message service http api",
            "hello", String.class);
</code>```

答:
When you see errors like "failed to resolve endpoint" in Camel, it's most likely due to lack of the dependency declaration in your Maven pom.xml. In your case, make sure your pom.xml has the following dependency:

```<code><dependency>
  <groupId>org.apache.camel</groupId>
  <artifactId>camel-jetty9</artifactId>
  <version>${camel.version}</version>
</dependency>
</code>```

Body:
I am working on a spring mvc application and i am using apache camel to send message.When i run my code in test case it show to me error failed to resolve endpoint.It is my code:

  CamelContext camelContext = new DefaultCamelContext();
    ProducerTemplate producerTemplate = camelContext.createProducerTemplate();
    producerTemplate.requestBody(
            "jetty:http://here my message service http api",
            "hello", String.class);

Body:
When you see errors like "failed to resolve endpoint" in Camel, it's most likely due to lack of the dependency declaration in your Maven pom.xml. In your case, make sure your pom.xml has the following dependency:

<dependency>
  <groupId>org.apache.camel</groupId>
  <artifactId>camel-jetty9</artifactId>
  <version>${camel.version}</version>
</dependency>


问:
MemoryError from sklearn.metrics.silhouette_samples
I get a memory error when trying to call sklearn.metrics.silhouette_samples. My use case is identical to this tutorial. I am using scikit-learn 0.18.1 in Python 3.5.

For the related function, silhouette_score , this post suggests the use of the sample_size parameter which reduces the sample size before calling silhouette_samples. I am not sure that the down-sampling would still produce reliable results so I hesitate to do that.

My input, X, is a [107545 rows x 12 columns] dataframe which I would not really consider to be big, although I do only have 8gb of RAM

```<code>sklearn.metrics.silhouette_samples(X, labels, metric=’euclidean’)
---------------------------------------------------------------------------
MemoryError                               Traceback (most recent call last)
<ipython-input-39-7285690e9ce8> in <module>()
----> 1 silhouette_samples(df_scaled, df['Cluster_Label'])

C:\Users\KE56166\AppData\Local\Enthought\Canopy\edm\envs\User\lib\site-packages\sklearn\metrics\cluster\unsupervised.py in silhouette_samples(X, labels, metric, **kwds)
    167     check_number_of_labels(len(le.classes_), X.shape[0])
    168
--> 169     distances = pairwise_distances(X, metric=metric, **kwds)
    170     unique_labels = le.classes_
    171     n_samples_per_label = np.bincount(labels, minlength=len(unique_labels))
C:\Users\KE56166\AppData\Local\Enthought\Canopy\edm\envs\User\lib\site-packages\sklearn\metrics\pairwise.py in pairwise_distances(X, Y, metric, n_jobs, **kwds)
   1245         func = partial(distance.cdist, metric=metric, **kwds)
   1246
-> 1247     return _parallel_pairwise(X, Y, func, n_jobs, **kwds)
   1248
   1249
C:\Users\KE56166\AppData\Local\Enthought\Canopy\edm\envs\User\lib\site-packages\sklearn\metrics\pairwise.py in _parallel_pairwise(X, Y, func, n_jobs, **kwds)
   1088     if n_jobs == 1:
   1089         # Special case to avoid picklability checks in delayed
-> 1090         return func(X, Y, **kwds)
   1091
   1092     # TODO: in some cases, backend='threading' may be appropriate
C:\Users\KE56166\AppData\Local\Enthought\Canopy\edm\envs\User\lib\site-packages\sklearn\metrics\pairwise.py in euclidean_distances(X, Y, Y_norm_squared, squared, X_norm_squared)
    244         YY = row_norms(Y, squared=True)[np.newaxis, :]
    245
--> 246     distances = safe_sparse_dot(X, Y.T, dense_output=True)
    247     distances *= -2
    248     distances += XX
C:\Users\KE56166\AppData\Local\Enthought\Canopy\edm\envs\User\lib\site-packages\sklearn\utils\extmath.py in safe_sparse_dot(a, b, dense_output)
    138         return ret
    139     else:
--> 140         return np.dot(a, b)
    141
    142
MemoryError:
</code>```

The calculation seems to rely on euclidean_distances which crashed on the call of np.dot. I am not dealing with scarcity here so maybe there is no solution. When calculating distance I normally use numpy.linalg.norm(A-B). Does this have better memory handling?

答:
Update: PR 11135 should resolve this issue within scikit-learn, making the rest of the post obsolete.

You have about 100000 = 1e5 samples, which are points in 12-dimensional space. The pairwise_distances method is trying to compute all pairwise distances between them. That is (1e5)**2 = 1e10 distances. Each is a floating point number; float64 format takes 8 bytes of memory. So the size of the distance matrix is 8e10 bytes, which is 74.5 GB.

This is occasionally reported on GitHub: #4701, #4197 with the answer being roughly: it's a NumPy problem that it can't handle np.dot with matrices of that size.  Although there was one comment saying

it might be possible to break this up into sub-matrices to do the calculation more memory efficient.

Indeed, if instead of forming one giant distance matrix at the beginning, the method computed relevant chunks of it in the loop over labels, that would require less memory.

It is not hard to modify the method using its source so that instead of computing distances first and applying binary masks later, it masks first. This is what I did below. Instead of N**2 memory, where N is the number of samples, it requires n**2 where n is the maximal cluster size.

If this is something that looks practical, I imagine it could be added to Scikit by way of some flag... one should note that this version does not support metric='precomputed', though.

```<code>import numpy as np
from sklearn.metrics.pairwise import pairwise_distances
from sklearn.utils import check_X_y
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics.cluster.unsupervised import check_number_of_labels

def silhouette_samples_memory_saving(X, labels, metric='euclidean', **kwds):
    X, labels = check_X_y(X, labels, accept_sparse=['csc', 'csr'])
    le = LabelEncoder()
    labels = le.fit_transform(labels)
    check_number_of_labels(len(le.classes_), X.shape[0])

    unique_labels = le.classes_
    n_samples_per_label = np.bincount(labels, minlength=len(unique_labels))

    # For sample i, store the mean distance of the cluster to which
    # it belongs in intra_clust_dists[i]
    intra_clust_dists = np.zeros(X.shape[0], dtype=X.dtype)

    # For sample i, store the mean distance of the second closest
    # cluster in inter_clust_dists[i]
    inter_clust_dists = np.inf + intra_clust_dists

    for curr_label in range(len(unique_labels)):

        # Find inter_clust_dist for all samples belonging to the same
        # label.
        mask = labels == curr_label

        # Leave out current sample.
        n_samples_curr_lab = n_samples_per_label[curr_label] - 1
        if n_samples_curr_lab != 0:
            intra_distances = pairwise_distances(X[mask, :], metric=metric, **kwds)
            intra_clust_dists[mask] = np.sum(intra_distances, axis=1) / n_samples_curr_lab

        # Now iterate over all other labels, finding the mean
        # cluster distance that is closest to every sample.
        for other_label in range(len(unique_labels)):
            if other_label != curr_label:
                other_mask = labels == other_label
                inter_distances = pairwise_distances(X[mask, :], X[other_mask, :], metric=metric, **kwds)
                other_distances = np.mean(inter_distances, axis=1)
                inter_clust_dists[mask] = np.minimum(inter_clust_dists[mask], other_distances)

    sil_samples = inter_clust_dists - intra_clust_dists
    sil_samples /= np.maximum(intra_clust_dists, inter_clust_dists)
    # score 0 for clusters of size 1, according to the paper
    sil_samples[n_samples_per_label.take(labels) == 1] = 0
    return sil_samples
</code>```

Body:
I get a memory error when trying to call sklearn.metrics.silhouette_samples. My use case is identical to this tutorial. I am using scikit-learn 0.18.1 in Python 3.5.

For the related function, silhouette_score , this post suggests the use of the sample_size parameter which reduces the sample size before calling silhouette_samples. I am not sure that the down-sampling would still produce reliable results so I hesitate to do that.

My input, X, is a [107545 rows x 12 columns] dataframe which I would not really consider to be big, although I do only have 8gb of RAM

sklearn.metrics.silhouette_samples(X, labels, metric=’euclidean’)
---------------------------------------------------------------------------
MemoryError                               Traceback (most recent call last)
<ipython-input-39-7285690e9ce8> in <module>()
----> 1 silhouette_samples(df_scaled, df['Cluster_Label'])

C:\Users\KE56166\AppData\Local\Enthought\Canopy\edm\envs\User\lib\site-packages\sklearn\metrics\cluster\unsupervised.py in silhouette_samples(X, labels, metric, **kwds)
    167     check_number_of_labels(len(le.classes_), X.shape[0])
    168
--> 169     distances = pairwise_distances(X, metric=metric, **kwds)
    170     unique_labels = le.classes_
    171     n_samples_per_label = np.bincount(labels, minlength=len(unique_labels))
C:\Users\KE56166\AppData\Local\Enthought\Canopy\edm\envs\User\lib\site-packages\sklearn\metrics\pairwise.py in pairwise_distances(X, Y, metric, n_jobs, **kwds)
   1245         func = partial(distance.cdist, metric=metric, **kwds)
   1246
-> 1247     return _parallel_pairwise(X, Y, func, n_jobs, **kwds)
   1248
   1249
C:\Users\KE56166\AppData\Local\Enthought\Canopy\edm\envs\User\lib\site-packages\sklearn\metrics\pairwise.py in _parallel_pairwise(X, Y, func, n_jobs, **kwds)
   1088     if n_jobs == 1:
   1089         # Special case to avoid picklability checks in delayed
-> 1090         return func(X, Y, **kwds)
   1091
   1092     # TODO: in some cases, backend='threading' may be appropriate
C:\Users\KE56166\AppData\Local\Enthought\Canopy\edm\envs\User\lib\site-packages\sklearn\metrics\pairwise.py in euclidean_distances(X, Y, Y_norm_squared, squared, X_norm_squared)
    244         YY = row_norms(Y, squared=True)[np.newaxis, :]
    245
--> 246     distances = safe_sparse_dot(X, Y.T, dense_output=True)
    247     distances *= -2
    248     distances += XX
C:\Users\KE56166\AppData\Local\Enthought\Canopy\edm\envs\User\lib\site-packages\sklearn\utils\extmath.py in safe_sparse_dot(a, b, dense_output)
    138         return ret
    139     else:
--> 140         return np.dot(a, b)
    141
    142
MemoryError:

The calculation seems to rely on euclidean_distances which crashed on the call of np.dot. I am not dealing with scarcity here so maybe there is no solution. When calculating distance I normally use numpy.linalg.norm(A-B). Does this have better memory handling?

Body:
Update: PR 11135 should resolve this issue within scikit-learn, making the rest of the post obsolete.

You have about 100000 = 1e5 samples, which are points in 12-dimensional space. The pairwise_distances method is trying to compute all pairwise distances between them. That is (1e5)**2 = 1e10 distances. Each is a floating point number; float64 format takes 8 bytes of memory. So the size of the distance matrix is 8e10 bytes, which is 74.5 GB.

This is occasionally reported on GitHub: #4701, #4197 with the answer being roughly: it's a NumPy problem that it can't handle np.dot with matrices of that size.  Although there was one comment saying

it might be possible to break this up into sub-matrices to do the calculation more memory efficient.

Indeed, if instead of forming one giant distance matrix at the beginning, the method computed relevant chunks of it in the loop over labels, that would require less memory.

It is not hard to modify the method using its source so that instead of computing distances first and applying binary masks later, it masks first. This is what I did below. Instead of N**2 memory, where N is the number of samples, it requires n**2 where n is the maximal cluster size.

If this is something that looks practical, I imagine it could be added to Scikit by way of some flag... one should note that this version does not support metric='precomputed', though.

import numpy as np
from sklearn.metrics.pairwise import pairwise_distances
from sklearn.utils import check_X_y
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics.cluster.unsupervised import check_number_of_labels

def silhouette_samples_memory_saving(X, labels, metric='euclidean', **kwds):
    X, labels = check_X_y(X, labels, accept_sparse=['csc', 'csr'])
    le = LabelEncoder()
    labels = le.fit_transform(labels)
    check_number_of_labels(len(le.classes_), X.shape[0])

    unique_labels = le.classes_
    n_samples_per_label = np.bincount(labels, minlength=len(unique_labels))

    # For sample i, store the mean distance of the cluster to which
    # it belongs in intra_clust_dists[i]
    intra_clust_dists = np.zeros(X.shape[0], dtype=X.dtype)

    # For sample i, store the mean distance of the second closest
    # cluster in inter_clust_dists[i]
    inter_clust_dists = np.inf + intra_clust_dists

    for curr_label in range(len(unique_labels)):

        # Find inter_clust_dist for all samples belonging to the same
        # label.
        mask = labels == curr_label

        # Leave out current sample.
        n_samples_curr_lab = n_samples_per_label[curr_label] - 1
        if n_samples_curr_lab != 0:
            intra_distances = pairwise_distances(X[mask, :], metric=metric, **kwds)
            intra_clust_dists[mask] = np.sum(intra_distances, axis=1) / n_samples_curr_lab

        # Now iterate over all other labels, finding the mean
        # cluster distance that is closest to every sample.
        for other_label in range(len(unique_labels)):
            if other_label != curr_label:
                other_mask = labels == other_label
                inter_distances = pairwise_distances(X[mask, :], X[other_mask, :], metric=metric, **kwds)
                other_distances = np.mean(inter_distances, axis=1)
                inter_clust_dists[mask] = np.minimum(inter_clust_dists[mask], other_distances)

    sil_samples = inter_clust_dists - intra_clust_dists
    sil_samples /= np.maximum(intra_clust_dists, inter_clust_dists)
    # score 0 for clusters of size 1, according to the paper
    sil_samples[n_samples_per_label.take(labels) == 1] = 0
    return sil_samples

ContentLicense: CC BY-SA 4.0


问:
Add migration with different assembly
I am working on a project with ASP.NET CORE 1.0.0 and I am using EntityFrameworkCore. I have separate assemblies and my project structure looks like this:

```<code>ProjectSolution
   -src
      -1 Domain
         -Project.Data
      -2 Api
         -Project.Api
</code>```

In my Project.Api is the Startup class

```<code>public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ProjectDbContext>();

        services.AddIdentity<IdentityUser, IdentityRole>()
                .AddEntityFrameworkStores<ProjectDbContext>()
                .AddDefaultTokenProviders();
    }
</code>```

The DbContext is in my Project.Data project

```<code>public class ProjectDbContext : IdentityDbContext<IdentityUser>
{
    public ProjectDbContext(DbContextOptions<ProjectDbContext> options) : base(options)
    {

    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {

        var builder = new ConfigurationBuilder();
        builder.SetBasePath(Directory.GetCurrentDirectory());
        builder.AddJsonFile("appsettings.json");
        IConfiguration Configuration = builder.Build();

        optionsBuilder.UseSqlServer(
            Configuration.GetConnectionString("DefaultConnection"));
        base.OnConfiguring(optionsBuilder);
    }
}
</code>```

When I try to make the initial migration, I get this error:

"Your target project 'Project.Api' doesn't match your migrations assembly 'Project.Data'. Either change your target project or change your migrations assembly.
  Change your migrations assembly by using DbContextOptionsBuilder. E.g. options.UseSqlServer(connection, b => b.MigrationsAssembly("Project.Api")). By default, the migrations assembly is the assembly containing the DbContext.
  Change your target project to the migrations project by using the Package Manager Console's Default project drop-down list, or by executing "dotnet ef" from the directory containing the migrations project."

After I seeing this error, I tried to execute this command located in Project.Api:

dotnet ef --startup-project ../Project.Api  --assembly "../../1 Data/Project.Data" migrations add Initial

and I got this error:

"Unexpected value '../../1 Domain/Project.Data' for option 'assembly'"

I don't know why I get this error, when I try to execute the command with the '-assembly' parameter.

I can't create a Initial Migration from other assembly and I've searched for information about it but didn't got any results.

Has someone had similar issues?

答:
I had the same problem until I noticed that on the package manager console top bar => "Default Projects" was supposed to be "Project.Data" and not "Project.API".

Once you target the "Project.Data" from the dropdown list and run the migration you should be fine.

Title: Add migration with different assembly

Body:
I am working on a project with ASP.NET CORE 1.0.0 and I am using EntityFrameworkCore. I have separate assemblies and my project structure looks like this:

ProjectSolution
   -src
      -1 Domain
         -Project.Data
      -2 Api
         -Project.Api

In my Project.Api is the Startup class

public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ProjectDbContext>();

        services.AddIdentity<IdentityUser, IdentityRole>()
                .AddEntityFrameworkStores<ProjectDbContext>()
                .AddDefaultTokenProviders();
    }

The DbContext is in my Project.Data project

public class ProjectDbContext : IdentityDbContext<IdentityUser>
{
    public ProjectDbContext(DbContextOptions<ProjectDbContext> options) : base(options)
    {

    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {

        var builder = new ConfigurationBuilder();
        builder.SetBasePath(Directory.GetCurrentDirectory());
        builder.AddJsonFile("appsettings.json");
        IConfiguration Configuration = builder.Build();

        optionsBuilder.UseSqlServer(
            Configuration.GetConnectionString("DefaultConnection"));
        base.OnConfiguring(optionsBuilder);
    }
}

When I try to make the initial migration, I get this error:

"Your target project 'Project.Api' doesn't match your migrations assembly 'Project.Data'. Either change your target project or change your migrations assembly.
  Change your migrations assembly by using DbContextOptionsBuilder. E.g. options.UseSqlServer(connection, b => b.MigrationsAssembly("Project.Api")). By default, the migrations assembly is the assembly containing the DbContext.
  Change your target project to the migrations project by using the Package Manager Console's Default project drop-down list, or by executing "dotnet ef" from the directory containing the migrations project."

After I seeing this error, I tried to execute this command located in Project.Api:

dotnet ef --startup-project ../Project.Api  --assembly "../../1 Data/Project.Data" migrations add Initial

and I got this error:

"Unexpected value '../../1 Domain/Project.Data' for option 'assembly'"

I don't know why I get this error, when I try to execute the command with the '-assembly' parameter.

I can't create a Initial Migration from other assembly and I've searched for information about it but didn't got any results.

Has someone had similar issues?


问:
Linq returns foreign key referenced data
I have a simple db with two tables employee and employeedetails.

employee has foreignkey empdetailsid that points to the table employeedetails

My simple linq query to return employee

```<code>var employeeList = from employee in objectcontext.employees select employee;
return employeeList.ToList();
</code>```

also returns employeedetails and all its contained fields which I do not need.
I am using Entity Framework 4.0. Is there a way to avoid getting all the unnecessary data.
I could go with defining a model class that just has the employee table fields and could load into that but I was wondering if there was a simpler way. I am using a mysql database.

答:
How do you know that the query returns employee details? Have you checked the generated SQL query, or did you just try to access the EmployeeDetails object and got the data. In the second case, EF could indeed just be lazy-loading the data on demand (when you try to access it). Otherwise, if you are sure the extra data gets fetched during the execution of the initial query, try implicitly enabling lazy loading before running the query:

```<code>objectcontext.ContextOptions.LazyLoadingEnabled = true;
</code>```

Body:
I have a simple db with two tables employee and employeedetails.

employee has foreignkey empdetailsid that points to the table employeedetails

My simple linq query to return employee

var employeeList = from employee in objectcontext.employees select employee;
return employeeList.ToList();

also returns employeedetails and all its contained fields which I do not need.
I am using Entity Framework 4.0. Is there a way to avoid getting all the unnecessary data.
I could go with defining a model class that just has the employee table fields and could load into that but I was wondering if there was a simpler way. I am using a mysql database.

Body:
How do you know that the query returns employee details? Have you checked the generated SQL query, or did you just try to access the EmployeeDetails object and got the data. In the second case, EF could indeed just be lazy-loading the data on demand (when you try to access it). Otherwise, if you are sure the extra data gets fetched during the execution of the initial query, try implicitly enabling lazy loading before running the query:

objectcontext.ContextOptions.LazyLoadingEnabled = true;


问:
Response to preflight request doesn't pass access control check
I'm getting this error using ngResource to call a REST API on Amazon Web Services:

XMLHttpRequest cannot load
http://server.apiurl.com:8000/s/login?login=facebook. Response to
preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost' is therefore not allowed access.
Error 405

Service:

```<code>socialMarkt.factory('loginService', ['$resource', function ($resource) {
    var apiAddress = "http://server.apiurl.com:8000/s/login/";
    return $resource(apiAddress, {
        login: "facebook",
        access_token: "@access_token",
        facebook_id: "@facebook_id"
    }, {
        getUser: {
            method: 'POST'
        }
    });
}]);
</code>```

Controller:

```<code>[...]
loginService.getUser(JSON.stringify(fbObj)),
    function (data) {
        console.log(data);
    },
    function (result) {
        console.error('Error', result.status);
    }
[...]
</code>```

I'm using Chrome. What else can I do in order to fix this problem?

I've even configured the server to accept headers from origin localhost.

答:
For those who are using Lambda Integrated Proxy with API Gateway, you need configure your lambda function as if you are submitting your requests to it directly, meaning the function should set up the response headers properly. (If you are using custom lambda functions, this will be handled by the API Gateway.)

```<code>// In your lambda's index.handler():
exports.handler = (event, context, callback) => {
    // On success:
    callback(null, {
        statusCode: 200,
        headers: {
            "Access-Control-Allow-Origin" : "*"
        }
    }
}
</code>```

Body:
I'm getting this error using ngResource to call a REST API on Amazon Web Services:

XMLHttpRequest cannot load
http://server.apiurl.com:8000/s/login?login=facebook. Response to
preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost' is therefore not allowed access.
Error 405

Service:

socialMarkt.factory('loginService', ['$resource', function ($resource) {
    var apiAddress = "http://server.apiurl.com:8000/s/login/";
    return $resource(apiAddress, {
        login: "facebook",
        access_token: "@access_token",
        facebook_id: "@facebook_id"
    }, {
        getUser: {
            method: 'POST'
        }
    });
}]);

Controller:

[...]
loginService.getUser(JSON.stringify(fbObj)),
    function (data) {
        console.log(data);
    },
    function (result) {
        console.error('Error', result.status);
    }
[...]

I'm using Chrome. What else can I do in order to fix this problem?

I've even configured the server to accept headers from origin localhost.

Body:
For those who are using Lambda Integrated Proxy with API Gateway, you need configure your lambda function as if you are submitting your requests to it directly, meaning the function should set up the response headers properly. (If you are using custom lambda functions, this will be handled by the API Gateway.)

// In your lambda's index.handler():
exports.handler = (event, context, callback) => {
    // On success:
    callback(null, {
        statusCode: 200,
        headers: {
            "Access-Control-Allow-Origin" : "*"
        }
    }
}


问:
Grouping HTML elements by order in document
I have an HTML document that goes something like this:

```<code><div class = "Group"> Group 1 </div>
<div class = "item"> Item 1 </div>
<div class = "Group"> Group 2 </div>
<div class = "item"> Item 2 </div>
<div class = "item"> Item 3 </div>
</code>```

I want to create a list of each item that belongs to the group group element that proceeds them:

```<code>Group 1: [Item 1]
Group 2: [Item 2, Item 3]
</code>```

Normally it's easy to do this, but I'm not sure how to approach when elements aren't nested accurately. I instead need to do this by only selecting HTML that appears below an element, but not sure how to do that.

答:
Although it could be done with re or other methods, html parsing requires a suitable library.

Using bs4:

```<code>from bs4 import BeautifulSoup

html = '''
<div class = "Group"> Group 1 </div>
<div class = "item"> Item 1 </div>
<div class = "Group"> Group 2 </div>
<div class = "item"> Item 2 </div>
<div class = "item"> Item 3 </div>
'''

soup = BeautifulSoup(html, 'lxml')
data = {}
key = None
for i in soup.find_all('div'):
    if 'Group' in i.get('class'):
        key = i.text.strip()
        data[key] = []
    elif key:
        data[key].append(i.text.strip())

print(data)
</code>```

```<code>{'Group 2': ['Item 2', 'Item 3'], 'Group 1': ['Item 1']}
</code>```

Body:
I have an HTML document that goes something like this:

 Group 1

 Item 1

 Group 2

 Item 2

 Item 3

I want to create a list of each item that belongs to the group group element that proceeds them:

Group 1: [Item 1]
Group 2: [Item 2, Item 3]

Normally it's easy to do this, but I'm not sure how to approach when elements aren't nested accurately. I instead need to do this by only selecting HTML that appears below an element, but not sure how to do that.

Body:
Although it could be done with re or other methods, html parsing requires a suitable library.

Using bs4:

from bs4 import BeautifulSoup

html = '''
<div class = "Group"> Group 1 </div>
<div class = "item"> Item 1 </div>
<div class = "Group"> Group 2 </div>
<div class = "item"> Item 2 </div>
<div class = "item"> Item 3 </div>
'''

soup = BeautifulSoup(html, 'lxml')
data = {}
key = None
for i in soup.find_all('div'):
    if 'Group' in i.get('class'):
        key = i.text.strip()
        data[key] = []
    elif key:
        data[key].append(i.text.strip())

print(data)

{'Group 2': ['Item 2', 'Item 3'], 'Group 1': ['Item 1']}


问:
Add Babel to Typescript React app
I've created a React app with Typescript support using create-react-app.

I'm targeting ES5 with the Typescript transpiler, which gives me support for ES6 syntax, but doesn't add the polyfills for the enhanced Array features etc of ES6 like Babel does.

Is there a way to use both Typescript and Babel?

i.e. .ts > ES6 > babel > ES5.

答:
add the polyfills for the enhanced Array features etc of ES6 like Bable does.

Babel doesn't do that. core-js does that. You can use core-js with TypeScript. Just add the following to your code:

```<code>import 'core-js'
</code>```

More

Covered in the lib.d.ts option

Title: Add Babel to Typescript React app

Body:
add the polyfills for the enhanced Array features etc of ES6 like Bable does.

Babel doesn't do that. core-js does that. You can use core-js with TypeScript. Just add the following to your code:

import 'core-js'

More

Covered in the lib.d.ts option


问:
Sqlite query from mutliple databases which are already existing
I am having difficulty in converting below sqlite query into Android source code.

I have two databases:
  - db1 : program table
  - db2 : event table

Here is the query:

sqlite3 db1.db

attach database '/data/data/com.stack.test/db2.db' as db2;

select a.show_id from main.program a inner join db2.event b on b.program_id = a.program_id group by a.show_id;

the query above works fine and i get the desired output.

I am having difficulty in converting this query into android java code.
The DBs are already created. I just want to open them and query.

Here is my code:

```<code>    SQLiteDatabase mDb = getDatabaseOpener().getWritableDatabase();         <-- this returns db1

    String attachDb = "attach database '" + "/data/data/com.stack.test/db2.db" + "' as db2";
    mDb.execSQL(attachDb);

    String tables = "main.program INNER JOIN db2.event ON db2.event.program_id=main.program.program_id";

    String groupBy = "main.program.show_id";

    String rawShowsQuery = SQLiteQueryBuilder.buildQueryString(false, tables,
            SHOWS_PROJECTION, null, groupBy, null, null, null);

    try (Cursor cursor = mDb.rawQuery(rawShowsQuery, null)) {
        if (cursor == null) {
            return Collections.emptyList();
        } else {
            while (cursor.moveToNext()) {
                // do something
            }
        }
    }
</code>```

I am getting following error :

E/SQLiteDatabase( 9952): Failed to open database '/data/data/com.stack.test/db2.db'.
E/SQLiteDatabase( 9952): android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database

If attaching db2 to db1 connected worked in the command line, then if should have worked here in the code as well right ?
Am i missing something in the code ?

答:
This is a fully working example (albeit with 3 attached for demonstration purposes and perhaps overly complicated due to column name duplication) :-

```<code>public class MainActivity extends AppCompatActivity {

    public static final String DBNAME1 = "db1";
    public static final String DBNAME2 = "db2";
    public static final String DBNAME3 = "db3";
    public static final String ID_COLUMN = "_id";
    public static final String TABLENAME_BASE = "_table_main";
    public static final String NAMECOLUMN_BASE = "_name";
    public static final String DB2_COL_NAME = DBNAME2 + NAMECOLUMN_BASE;
    public static final String EXTENDED_DB2TABLENAME = DBNAME2 + "." + DBNAME2 + TABLENAME_BASE;
    public static final String EXTENDED_DB3TABLENAME = DBNAME3 + "." + DBNAME2 + TABLENAME_BASE;
    public static final String DB2_FULL_IDCOL = EXTENDED_DB2TABLENAME + "." + ID_COLUMN;
    public static final String DB2_FULL_NAMECOL = EXTENDED_DB2TABLENAME + "." + DBNAME2 + NAMECOLUMN_BASE;
    public static final String DB3_FULL_IDCOL = EXTENDED_DB3TABLENAME + "." + ID_COLUMN;
    public static final String DB3_FULL_NAMECOL = EXTENDED_DB3TABLENAME + "." + DBNAME2 + NAMECOLUMN_BASE;

    private static final String[] DB1NAMES = new String[] {"Fred","Bert","Harry","Tom","Dick"};
    private static final String[] DB2NAMES = new String[] {"Alan","George","Robert","Colin","Ian","John"};

    String mDB1Path, mDB2path;
    SQLiteDatabase mMaster;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mDB1Path = createDatbase(DBNAME1);
        mDB2path = createDatbase(DBNAME2);

        // Check that can be added for those who are too arrogant to
        // even consider they may have the incorrect path name coded
        // when hard coding the path rather than obtaining it via code.
        Log.d("DBPATHS","Path for " + DBNAME1 + " is " + mDB1Path);
        Log.d("DBPATHS","Path for " + DBNAME2 + " is " + mDBPath2);

        /* Only uncomment for first run to populate database tables
        for (String s: DB2NAMES) {
            insertRow(DBNAME1,s);
        }
        for (String s: DB1NAMES) {
            insertRow(DBNAME2,s);
        }
        */

        mMaster = this.openOrCreateDatabase(mDB1Path, Context.MODE_PRIVATE,null);
        String attachsql = "ATTACH DATABASE '" + mDB2path + "' AS " + DBNAME2;
        String attachsql2 = "ATTACH DATABASE '" + mDB2path + "' AS " +  DBNAME3;
        mMaster.execSQL(attachsql);
        mMaster.execSQL(attachsql2);

        String sqlstr = "SELECT " +
                DBNAME1 + TABLENAME_BASE + ".*, " +
                DBNAME2 + "." + DBNAME2 + TABLENAME_BASE + "." + DB2_COL_NAME +
                ", " + DBNAME3 + "." + DBNAME2 + TABLENAME_BASE + "." + DB2_COL_NAME +
                " FROM " + DBNAME1 + TABLENAME_BASE +
                " JOIN " + DBNAME2 + "." + DBNAME2 + TABLENAME_BASE +
                " ON " + DBNAME1 + TABLENAME_BASE + "." + ID_COLUMN +
                " =  " + DBNAME2 + "." + DBNAME2 + TABLENAME_BASE + "." + ID_COLUMN +
                " JOIN " + DBNAME3 + "." + DBNAME2 + TABLENAME_BASE +
                " ON " + DBNAME1 + TABLENAME_BASE + "." + ID_COLUMN +
                " =  " + DBNAME3 + "." + DBNAME2 + TABLENAME_BASE + "." + ID_COLUMN;

        Log.d("SELECTSQL_1",sqlstr);
        Cursor csr = mMaster.rawQuery(sqlstr,null);
        while (csr.moveToNext()) {
            String logdata = "Row = " + csr.getPosition();
            for (int i=0; i < csr.getColumnCount(); i++) {
                logdata = logdata + " Column = " + csr.getColumnName(i) +
                        " Value = " + csr.getString(i);
            }
            Log.d("CSRINFO",logdata);
        }

        String arg1 = "12";
        String arg2 = "Fred";

        String sqlstr2 = " SELECT " +
                DB2_FULL_IDCOL + ", " +
                DB2_FULL_NAMECOL + ", " +
                DB3_FULL_IDCOL + ", " +
                DB3_FULL_NAMECOL +
                " FROM " + DBNAME2 + TABLENAME_BASE +
                " JOIN " + DBNAME3 + "." + DBNAME2 + TABLENAME_BASE +
                " ON   " + DBNAME2 + "." + DBNAME2 + TABLENAME_BASE + "." + ID_COLUMN +
                " =    " + DB3_FULL_IDCOL +
                " WHERE " +
                DB2_FULL_IDCOL + "=? AND " +
                DB3_FULL_NAMECOL + "=?";
        Log.d("SELECTSQL_2",sqlstr2);
        Cursor csr2 = mMaster.rawQuery(sqlstr2,new String[]{arg1,arg2});

        while (csr2.moveToNext()) {
            String logdata = "Row = " + csr2.getPosition();
            for (int i=0; i < csr2.getColumnCount(); i++) {
                logdata = logdata + " Column = " + csr2.getColumnName(i) +
                        " Value = " + csr2.getString(i);
            }
            Log.d("CSRINFO",logdata);
        }
    }

    private String createDatbase(String dbqualifier) {
        SQLiteDatabase db = this.openOrCreateDatabase(dbqualifier,Context.MODE_PRIVATE,null);
        String tblcrtstr = "CREATE TABLE IF NOT EXISTS " +
                dbqualifier + TABLENAME_BASE +
                "(" +
                ID_COLUMN + " INTEGER PRIMARY KEY, " +
                dbqualifier + NAMECOLUMN_BASE  + " TEXT" +
                ")";
        db.execSQL(tblcrtstr);
        String rv = db.getPath();
        db.close();
        return rv;
    }

    private void insertRow(String dbqualifier, String name) {
        SQLiteDatabase db = this.openOrCreateDatabase(dbqualifier,MODE_PRIVATE,null);
        ContentValues cv = new ContentValues();
        cv.put(dbqualifier + NAMECOLUMN_BASE, name);
        db.insert(dbqualifier + TABLENAME_BASE,null,cv);
        db.close();
    }
}
</code>```

You problem is that it cannot open the database db2, perhaps because of the path being incorrect. The above gets the path according to the database name.

Example output from the above (note 2nd query purposefully results in empty cursor, it is an example of coping with multiple columns named _id) :-

```<code>12-07 19:32:26.764 2913-2913/mjt.attachdatabases D/SELECTSQL_1: SELECT db1_table_main.*, db2.db2_table_main.db2_name, db3.db2_table_main.db2_name FROM db1_table_main JOIN db2.db2_table_main ON db1_table_main._id =  db2.db2_table_main._id JOIN db3.db2_table_main ON db1_table_main._id =  db3.db2_table_main._id
12-07 19:32:26.764 2913-2913/mjt.attachdatabases D/CSRINFO: Row = 0 Column = _id Value = 1 Column = db1_name Value = Alan Column = db2_name Value = Fred Column = db2_name Value = Fred
12-07 19:32:26.764 2913-2913/mjt.attachdatabases D/CSRINFO: Row = 1 Column = _id Value = 2 Column = db1_name Value = George Column = db2_name Value = Bert Column = db2_name Value = Bert
12-07 19:32:26.764 2913-2913/mjt.attachdatabases D/CSRINFO: Row = 2 Column = _id Value = 3 Column = db1_name Value = Robert Column = db2_name Value = Harry Column = db2_name Value = Harry
12-07 19:32:26.764 2913-2913/mjt.attachdatabases D/CSRINFO: Row = 3 Column = _id Value = 4 Column = db1_name Value = Colin Column = db2_name Value = Tom Column = db2_name Value = Tom
12-07 19:32:26.764 2913-2913/mjt.attachdatabases D/CSRINFO: Row = 4 Column = _id Value = 5 Column = db1_name Value = Ian Column = db2_name Value = Dick Column = db2_name Value = Dick
12-07 19:32:26.764 2913-2913/mjt.attachdatabases D/SELECTSQL_2:  SELECT db2.db2_table_main._id, db2.db2_table_main.db2_name, db3.db2_table_main._id, db3.db2_table_main.db2_name FROM db2_table_main JOIN db3.db2_table_main ON   db2.db2_table_main._id =    db3.db2_table_main._id WHERE db2.db2_table_main._id=? AND db3.db2_table_main.db2_name=?
</code>```

Amended Code

tested on  3 devices API's 16, 23 and 24 with default permissions.
Now uses databases from different directories.

```<code>public class MainActivity extends AppCompatActivity {

    public static final String DBNAME1 = "db1";
    public static final String DBNAME2 = "db2";
    public static final String DBNAME3 = "db3";
    public static final String ID_COLUMN = "_id";
    public static final String TABLENAME_BASE = "_table_main";
    public static final String NAMECOLUMN_BASE = "_name";
    public static final String DB2_COL_NAME = DBNAME2 + NAMECOLUMN_BASE;
    public static final String EXTENDED_DB2TABLENAME = DBNAME2 + "." + DBNAME2 + TABLENAME_BASE;
    public static final String EXTENDED_DB3TABLENAME = DBNAME3 + "." + DBNAME2 + TABLENAME_BASE;
    public static final String DB2_FULL_IDCOL = EXTENDED_DB2TABLENAME + "." + ID_COLUMN;
    public static final String DB2_FULL_NAMECOL = EXTENDED_DB2TABLENAME + "." + DBNAME2 + NAMECOLUMN_BASE;
    public static final String DB3_FULL_IDCOL = EXTENDED_DB3TABLENAME + "." + ID_COLUMN;
    public static final String DB3_FULL_NAMECOL = EXTENDED_DB3TABLENAME + "." + DBNAME2 + NAMECOLUMN_BASE;

    private static final String[] DB1NAMES = new String[] {"Fred","Bert","Harry","Tom","Dick"};
    private static final String[] DB2NAMES = new String[] {"Alan","George","Robert","Colin","Ian","John"};

    private static final String altbasepath = "/data/data/mjt.attachdatabases/";

    String mDB1Path, mDB2path, mDBA1Path, mDBA2Path;
    SQLiteDatabase mMaster, mAltMaster;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mDB1Path = createDatbase(DBNAME1);
        mDB2path = createDatbase(DBNAME2);
        mDBA1Path = createDatabase(DBNAME1,altbasepath);
        mDBA2Path = createDatabase(DBNAME2,altbasepath);

        // Only uncomment for first run to populate database tables
        for (String s: DB2NAMES) {
            insertRow(DBNAME1,s);
            insertAltRow(DBNAME2,s);
        }
        for (String s: DB1NAMES) {
            insertRow(DBNAME2,s);
            insertAltRow(DBNAME1,s);
        }
        Log.d("DBPATHS", "DB1 Path=" + mDB1Path + " - DSB2 path=" + mDB2path);
        Log.d("DBPATHS", "ADB1 Path=" + mDBA1Path + " - DADB2 path=" + mDBA2Path);

        mMaster = this.openOrCreateDatabase(mDB1Path, Context.MODE_PRIVATE,null);
        mAltMaster = this.openOrCreateDatabase(mDBA1Path,Context.MODE_PRIVATE,null);
        /*
        String altattachsql = "ATTACH DATABASE '" + mDBA2Path + "' AS " + DBNAME2;
        String attachsql = "ATTACH DATABASE '" + mDB2path + "' AS " + DBNAME2;
        String aaltttachsql2 = "ATTACH DATABASE '" + mDB2path + "' AS " +  DBNAME3;
        String attachsql2 = "ATTACH DATABASE '" + mDB2path + "' AS " +  DBNAME3;
        mMaster.execSQL(attachsql);
        mMaster.execSQL(attachsql2);
        mAltMaster.execSQL(altattachsql);
        mAltMaster.execSQL(aaltttachsql2);
        */
        String mdattachsql = "ATTACH DATABASE '" + mDBA2Path + "' AS " + DBNAME2;
        String mdattachsql2 = "ATTACH DATABASE '" + mDBA2Path + "' AS " + DBNAME3;
        mMaster.execSQL(mdattachsql);
        mMaster.execSQL(mdattachsql2);

        String sqlstr = "SELECT " +
                DBNAME1 + TABLENAME_BASE + ".*, " +
                DBNAME2 + "." + DBNAME2 + TABLENAME_BASE + "." + DB2_COL_NAME +
                ", " + DBNAME3 + "." + DBNAME2 + TABLENAME_BASE + "." + DB2_COL_NAME +
                " FROM " + DBNAME1 + TABLENAME_BASE +
                " JOIN " + DBNAME2 + "." + DBNAME2 + TABLENAME_BASE +
                " ON " + DBNAME1 + TABLENAME_BASE + "." + ID_COLUMN +
                " =  " + DBNAME2 + "." + DBNAME2 + TABLENAME_BASE + "." + ID_COLUMN +
                " JOIN " + DBNAME3 + "." + DBNAME2 + TABLENAME_BASE +
                " ON " + DBNAME1 + TABLENAME_BASE + "." + ID_COLUMN +
                " =  " + DBNAME3 + "." + DBNAME2 + TABLENAME_BASE + "." + ID_COLUMN;

        Log.d("SELECTSQL_1",sqlstr);
        Cursor csr = mMaster.rawQuery(sqlstr,null);
        while (csr.moveToNext()) {
            String logdata = "Row = " + csr.getPosition();
            for (int i=0; i < csr.getColumnCount(); i++) {
                logdata = logdata + " Column = " + csr.getColumnName(i) +
                        " Value = " + csr.getString(i);
            }
            Log.d("CSRINFO",logdata);
        }

        /*
        Log.d("SELECTSQL_ALT",sqlstr);
        Cursor acsr = mAltMaster.rawQuery(sqlstr,null);
        while (acsr.moveToNext()) {
            String logdata = "Row = " + acsr.getPosition();
            for (int i=0; i < acsr.getColumnCount(); i++) {
                logdata = logdata + " Column = " + acsr.getColumnName(i) +
                        " Value = " + acsr.getString(i);
            }
            Log.d("CSRINFO",logdata);
        }
        */

        String arg1 = "12";
        String arg2 = "Fred";

        String sqlstr2 = " SELECT " +
                DB2_FULL_IDCOL + ", " +
                DB2_FULL_NAMECOL + ", " +
                DB3_FULL_IDCOL + ", " +
                DB3_FULL_NAMECOL +
                " FROM " + DBNAME2 + TABLENAME_BASE +
                " JOIN " + DBNAME3 + "." + DBNAME2 + TABLENAME_BASE +
                " ON   " + DBNAME2 + "." + DBNAME2 + TABLENAME_BASE + "." + ID_COLUMN +
                " =    " + DB3_FULL_IDCOL +
                " WHERE " +
                DB2_FULL_IDCOL + "=? AND " +
                DB3_FULL_NAMECOL + "=?";
        Log.d("SELECTSQL_2",sqlstr2);
        Cursor csr2 = mMaster.rawQuery(sqlstr2,new String[]{arg1,arg2});

        while (csr2.moveToNext()) {
            String logdata = "Row = " + csr2.getPosition();
            for (int i=0; i < csr2.getColumnCount(); i++) {
                logdata = logdata + " Column = " + csr2.getColumnName(i) +
                        " Value = " + csr2.getString(i);
            }
            Log.d("CSRINFO",logdata);
        }
    }

    private String createDatbase(String dbqualifier) {
        SQLiteDatabase db = this.openOrCreateDatabase(dbqualifier,Context.MODE_PRIVATE,null);
        String tblcrtstr = "CREATE TABLE IF NOT EXISTS " +
                dbqualifier + TABLENAME_BASE +
                "(" +
                ID_COLUMN + " INTEGER PRIMARY KEY, " +
                dbqualifier + NAMECOLUMN_BASE  + " TEXT" +
                ")";
        db.execSQL(tblcrtstr);
        String rv = db.getPath();
        db.close();
        return rv;
    }

    private String createDatabase(String dbqualifier, String altpath) {
        SQLiteDatabase db = this.openOrCreateDatabase(altpath + "/" + dbqualifier,Context.MODE_PRIVATE, null);
        String tblcrtstr = "CREATE TABLE IF NOT EXISTS " +
                dbqualifier + TABLENAME_BASE +
                "(" +
                ID_COLUMN + " INTEGER PRIMARY KEY, " +
                dbqualifier + NAMECOLUMN_BASE  + " TEXT" +
                ")";
        db.execSQL(tblcrtstr);
        String rv = db.getPath();
        db.close();
        return rv;
    }

    private void insertRow(String dbqualifier, String name) {
        SQLiteDatabase db = this.openOrCreateDatabase(dbqualifier,MODE_PRIVATE,null);
        ContentValues cv = new ContentValues();
        cv.put(dbqualifier + NAMECOLUMN_BASE, name);
        db.insert(dbqualifier + TABLENAME_BASE,null,cv);
        db.close();
    }

    private void insertAltRow(String dbqualifier, String name) {
        SQLiteDatabase db = this.openOrCreateDatabase(altbasepath + "/" + dbqualifier, MODE_PRIVATE,null);
        ContentValues cv = new ContentValues();
        cv.put(dbqualifier + NAMECOLUMN_BASE, name);
        db.insert(dbqualifier + TABLENAME_BASE, null, cv);
        db.close();
    }
}
</code>```

Attempts to recreate the same error :-

1 - Try to open with a path that has a non-existing file :-

Changed code to :-

```<code>mAltMaster = this.openOrCreateDatabase(mDBA1Path+"x",Context.MODE_PRIVATE,null);
</code>```

Fails trying to open :-

```<code>12-08 06:03:31.294 1482-1482/? E/SQLiteLog: (14) cannot open file at line 30174 of [00bb9c9ce4]
12-08 06:03:31.294 1482-1482/? E/SQLiteLog: (14) os_unix.c:30174: (21) open(/data/data/mjt.attachdatabases/db1x) -
12-08 06:03:31.294 1482-1482/? E/SQLiteDatabase: Failed to open database '/data/data/mjt.attachdatabases/db1x'.
                                                 android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
</code>```

2 - Skip the open and try to attach with non-existing file :-

e.g. ATTACH DATABASE '/data/data/mjt.attachdatabases/db2blah' AS db2

The ATTACH works but fails later due to table not found (i.e. the database is created, as attach appears to use openOrCreate, but has no user defined tables).

3 - try to attach a database that is not a database file, in this case a pdf file renamed to db2blah.

The ATTACH fails with :-

```<code>E/SQLiteLog: (26) statement aborts at 5: [ATTACH DATABASE '/data/data/mjt.attachdatabases/db2blah' AS db2] file is encrypted or is not a database
</code>```

All the above appear to not meet the error. So perhaps the issue is that the database file doesn't have the appropriate permissions, another possibility is that the file may be in use.

Body:
I am having difficulty in converting below sqlite query into Android source code.

I have two databases:
  - db1 : program table
  - db2 : event table

Here is the query:

sqlite3 db1.db

attach database '/data/data/com.stack.test/db2.db' as db2;

select a.show_id from main.program a inner join db2.event b on b.program_id = a.program_id group by a.show_id;

the query above works fine and i get the desired output.

I am having difficulty in converting this query into android java code.
The DBs are already created. I just want to open them and query.

Here is my code:

    SQLiteDatabase mDb = getDatabaseOpener().getWritableDatabase();         <-- this returns db1

    String attachDb = "attach database '" + "/data/data/com.stack.test/db2.db" + "' as db2";
    mDb.execSQL(attachDb);

    String tables = "main.program INNER JOIN db2.event ON db2.event.program_id=main.program.program_id";

    String groupBy = "main.program.show_id";

    String rawShowsQuery = SQLiteQueryBuilder.buildQueryString(false, tables,
            SHOWS_PROJECTION, null, groupBy, null, null, null);

    try (Cursor cursor = mDb.rawQuery(rawShowsQuery, null)) {
        if (cursor == null) {
            return Collections.emptyList();
        } else {
            while (cursor.moveToNext()) {
                // do something
            }
        }
    }

I am getting following error :

E/SQLiteDatabase( 9952): Failed to open database '/data/data/com.stack.test/db2.db'.
E/SQLiteDatabase( 9952): android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database

If attaching db2 to db1 connected worked in the command line, then if should have worked here in the code as well right ?
Am i missing something in the code ?

Body:
This is a fully working example (albeit with 3 attached for demonstration purposes and perhaps overly complicated due to column name duplication) :-

public class MainActivity extends AppCompatActivity {

    public static final String DBNAME1 = "db1";
    public static final String DBNAME2 = "db2";
    public static final String DBNAME3 = "db3";
    public static final String ID_COLUMN = "_id";
    public static final String TABLENAME_BASE = "_table_main";
    public static final String NAMECOLUMN_BASE = "_name";
    public static final String DB2_COL_NAME = DBNAME2 + NAMECOLUMN_BASE;
    public static final String EXTENDED_DB2TABLENAME = DBNAME2 + "." + DBNAME2 + TABLENAME_BASE;
    public static final String EXTENDED_DB3TABLENAME = DBNAME3 + "." + DBNAME2 + TABLENAME_BASE;
    public static final String DB2_FULL_IDCOL = EXTENDED_DB2TABLENAME + "." + ID_COLUMN;
    public static final String DB2_FULL_NAMECOL = EXTENDED_DB2TABLENAME + "." + DBNAME2 + NAMECOLUMN_BASE;
    public static final String DB3_FULL_IDCOL = EXTENDED_DB3TABLENAME + "." + ID_COLUMN;
    public static final String DB3_FULL_NAMECOL = EXTENDED_DB3TABLENAME + "." + DBNAME2 + NAMECOLUMN_BASE;

    private static final String[] DB1NAMES = new String[] {"Fred","Bert","Harry","Tom","Dick"};
    private static final String[] DB2NAMES = new String[] {"Alan","George","Robert","Colin","Ian","John"};

    String mDB1Path, mDB2path;
    SQLiteDatabase mMaster;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mDB1Path = createDatbase(DBNAME1);
        mDB2path = createDatbase(DBNAME2);

        // Check that can be added for those who are too arrogant to
        // even consider they may have the incorrect path name coded
        // when hard coding the path rather than obtaining it via code.
        Log.d("DBPATHS","Path for " + DBNAME1 + " is " + mDB1Path);
        Log.d("DBPATHS","Path for " + DBNAME2 + " is " + mDBPath2);

        /* Only uncomment for first run to populate database tables
        for (String s: DB2NAMES) {
            insertRow(DBNAME1,s);
        }
        for (String s: DB1NAMES) {
            insertRow(DBNAME2,s);
        }
        */

        mMaster = this.openOrCreateDatabase(mDB1Path, Context.MODE_PRIVATE,null);
        String attachsql = "ATTACH DATABASE '" + mDB2path + "' AS " + DBNAME2;
        String attachsql2 = "ATTACH DATABASE '" + mDB2path + "' AS " +  DBNAME3;
        mMaster.execSQL(attachsql);
        mMaster.execSQL(attachsql2);

        String sqlstr = "SELECT " +
                DBNAME1 + TABLENAME_BASE + ".*, " +
                DBNAME2 + "." + DBNAME2 + TABLENAME_BASE + "." + DB2_COL_NAME +
                ", " + DBNAME3 + "." + DBNAME2 + TABLENAME_BASE + "." + DB2_COL_NAME +
                " FROM " + DBNAME1 + TABLENAME_BASE +
                " JOIN " + DBNAME2 + "." + DBNAME2 + TABLENAME_BASE +
                " ON " + DBNAME1 + TABLENAME_BASE + "." + ID_COLUMN +
                " =  " + DBNAME2 + "." + DBNAME2 + TABLENAME_BASE + "." + ID_COLUMN +
                " JOIN " + DBNAME3 + "." + DBNAME2 + TABLENAME_BASE +
                " ON " + DBNAME1 + TABLENAME_BASE + "." + ID_COLUMN +
                " =  " + DBNAME3 + "." + DBNAME2 + TABLENAME_BASE + "." + ID_COLUMN;

        Log.d("SELECTSQL_1",sqlstr);
        Cursor csr = mMaster.rawQuery(sqlstr,null);
        while (csr.moveToNext()) {
            String logdata = "Row = " + csr.getPosition();
            for (int i=0; i < csr.getColumnCount(); i++) {
                logdata = logdata + " Column = " + csr.getColumnName(i) +
                        " Value = " + csr.getString(i);
            }
            Log.d("CSRINFO",logdata);
        }

        String arg1 = "12";
        String arg2 = "Fred";

        String sqlstr2 = " SELECT " +
                DB2_FULL_IDCOL + ", " +
                DB2_FULL_NAMECOL + ", " +
                DB3_FULL_IDCOL + ", " +
                DB3_FULL_NAMECOL +
                " FROM " + DBNAME2 + TABLENAME_BASE +
                " JOIN " + DBNAME3 + "." + DBNAME2 + TABLENAME_BASE +
                " ON   " + DBNAME2 + "." + DBNAME2 + TABLENAME_BASE + "." + ID_COLUMN +
                " =    " + DB3_FULL_IDCOL +
                " WHERE " +
                DB2_FULL_IDCOL + "=? AND " +
                DB3_FULL_NAMECOL + "=?";
        Log.d("SELECTSQL_2",sqlstr2);
        Cursor csr2 = mMaster.rawQuery(sqlstr2,new String[]{arg1,arg2});

        while (csr2.moveToNext()) {
            String logdata = "Row = " + csr2.getPosition();
            for (int i=0; i < csr2.getColumnCount(); i++) {
                logdata = logdata + " Column = " + csr2.getColumnName(i) +
                        " Value = " + csr2.getString(i);
            }
            Log.d("CSRINFO",logdata);
        }
    }

    private String createDatbase(String dbqualifier) {
        SQLiteDatabase db = this.openOrCreateDatabase(dbqualifier,Context.MODE_PRIVATE,null);
        String tblcrtstr = "CREATE TABLE IF NOT EXISTS " +
                dbqualifier + TABLENAME_BASE +
                "(" +
                ID_COLUMN + " INTEGER PRIMARY KEY, " +
                dbqualifier + NAMECOLUMN_BASE  + " TEXT" +
                ")";
        db.execSQL(tblcrtstr);
        String rv = db.getPath();
        db.close();
        return rv;
    }

    private void insertRow(String dbqualifier, String name) {
        SQLiteDatabase db = this.openOrCreateDatabase(dbqualifier,MODE_PRIVATE,null);
        ContentValues cv = new ContentValues();
        cv.put(dbqualifier + NAMECOLUMN_BASE, name);
        db.insert(dbqualifier + TABLENAME_BASE,null,cv);
        db.close();
    }
}

You problem is that it cannot open the database db2, perhaps because of the path being incorrect. The above gets the path according to the database name.

Example output from the above (note 2nd query purposefully results in empty cursor, it is an example of coping with multiple columns named _id) :-

12-07 19:32:26.764 2913-2913/mjt.attachdatabases D/SELECTSQL_1: SELECT db1_table_main.*, db2.db2_table_main.db2_name, db3.db2_table_main.db2_name FROM db1_table_main JOIN db2.db2_table_main ON db1_table_main._id =  db2.db2_table_main._id JOIN db3.db2_table_main ON db1_table_main._id =  db3.db2_table_main._id
12-07 19:32:26.764 2913-2913/mjt.attachdatabases D/CSRINFO: Row = 0 Column = _id Value = 1 Column = db1_name Value = Alan Column = db2_name Value = Fred Column = db2_name Value = Fred
12-07 19:32:26.764 2913-2913/mjt.attachdatabases D/CSRINFO: Row = 1 Column = _id Value = 2 Column = db1_name Value = George Column = db2_name Value = Bert Column = db2_name Value = Bert
12-07 19:32:26.764 2913-2913/mjt.attachdatabases D/CSRINFO: Row = 2 Column = _id Value = 3 Column = db1_name Value = Robert Column = db2_name Value = Harry Column = db2_name Value = Harry
12-07 19:32:26.764 2913-2913/mjt.attachdatabases D/CSRINFO: Row = 3 Column = _id Value = 4 Column = db1_name Value = Colin Column = db2_name Value = Tom Column = db2_name Value = Tom
12-07 19:32:26.764 2913-2913/mjt.attachdatabases D/CSRINFO: Row = 4 Column = _id Value = 5 Column = db1_name Value = Ian Column = db2_name Value = Dick Column = db2_name Value = Dick
12-07 19:32:26.764 2913-2913/mjt.attachdatabases D/SELECTSQL_2:  SELECT db2.db2_table_main._id, db2.db2_table_main.db2_name, db3.db2_table_main._id, db3.db2_table_main.db2_name FROM db2_table_main JOIN db3.db2_table_main ON   db2.db2_table_main._id =    db3.db2_table_main._id WHERE db2.db2_table_main._id=? AND db3.db2_table_main.db2_name=?

Amended Code

tested on  3 devices API's 16, 23 and 24 with default permissions.
Now uses databases from different directories.

public class MainActivity extends AppCompatActivity {

    public static final String DBNAME1 = "db1";
    public static final String DBNAME2 = "db2";
    public static final String DBNAME3 = "db3";
    public static final String ID_COLUMN = "_id";
    public static final String TABLENAME_BASE = "_table_main";
    public static final String NAMECOLUMN_BASE = "_name";
    public static final String DB2_COL_NAME = DBNAME2 + NAMECOLUMN_BASE;
    public static final String EXTENDED_DB2TABLENAME = DBNAME2 + "." + DBNAME2 + TABLENAME_BASE;
    public static final String EXTENDED_DB3TABLENAME = DBNAME3 + "." + DBNAME2 + TABLENAME_BASE;
    public static final String DB2_FULL_IDCOL = EXTENDED_DB2TABLENAME + "." + ID_COLUMN;
    public static final String DB2_FULL_NAMECOL = EXTENDED_DB2TABLENAME + "." + DBNAME2 + NAMECOLUMN_BASE;
    public static final String DB3_FULL_IDCOL = EXTENDED_DB3TABLENAME + "." + ID_COLUMN;
    public static final String DB3_FULL_NAMECOL = EXTENDED_DB3TABLENAME + "." + DBNAME2 + NAMECOLUMN_BASE;

    private static final String[] DB1NAMES = new String[] {"Fred","Bert","Harry","Tom","Dick"};
    private static final String[] DB2NAMES = new String[] {"Alan","George","Robert","Colin","Ian","John"};

    private static final String altbasepath = "/data/data/mjt.attachdatabases/";

    String mDB1Path, mDB2path, mDBA1Path, mDBA2Path;
    SQLiteDatabase mMaster, mAltMaster;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mDB1Path = createDatbase(DBNAME1);
        mDB2path = createDatbase(DBNAME2);
        mDBA1Path = createDatabase(DBNAME1,altbasepath);
        mDBA2Path = createDatabase(DBNAME2,altbasepath);

        // Only uncomment for first run to populate database tables
        for (String s: DB2NAMES) {
            insertRow(DBNAME1,s);
            insertAltRow(DBNAME2,s);
        }
        for (String s: DB1NAMES) {
            insertRow(DBNAME2,s);
            insertAltRow(DBNAME1,s);
        }
        Log.d("DBPATHS", "DB1 Path=" + mDB1Path + " - DSB2 path=" + mDB2path);
        Log.d("DBPATHS", "ADB1 Path=" + mDBA1Path + " - DADB2 path=" + mDBA2Path);

        mMaster = this.openOrCreateDatabase(mDB1Path, Context.MODE_PRIVATE,null);
        mAltMaster = this.openOrCreateDatabase(mDBA1Path,Context.MODE_PRIVATE,null);
        /*
        String altattachsql = "ATTACH DATABASE '" + mDBA2Path + "' AS " + DBNAME2;
        String attachsql = "ATTACH DATABASE '" + mDB2path + "' AS " + DBNAME2;
        String aaltttachsql2 = "ATTACH DATABASE '" + mDB2path + "' AS " +  DBNAME3;
        String attachsql2 = "ATTACH DATABASE '" + mDB2path + "' AS " +  DBNAME3;
        mMaster.execSQL(attachsql);
        mMaster.execSQL(attachsql2);
        mAltMaster.execSQL(altattachsql);
        mAltMaster.execSQL(aaltttachsql2);
        */
        String mdattachsql = "ATTACH DATABASE '" + mDBA2Path + "' AS " + DBNAME2;
        String mdattachsql2 = "ATTACH DATABASE '" + mDBA2Path + "' AS " + DBNAME3;
        mMaster.execSQL(mdattachsql);
        mMaster.execSQL(mdattachsql2);

        String sqlstr = "SELECT " +
                DBNAME1 + TABLENAME_BASE + ".*, " +
                DBNAME2 + "." + DBNAME2 + TABLENAME_BASE + "." + DB2_COL_NAME +
                ", " + DBNAME3 + "." + DBNAME2 + TABLENAME_BASE + "." + DB2_COL_NAME +
                " FROM " + DBNAME1 + TABLENAME_BASE +
                " JOIN " + DBNAME2 + "." + DBNAME2 + TABLENAME_BASE +
                " ON " + DBNAME1 + TABLENAME_BASE + "." + ID_COLUMN +
                " =  " + DBNAME2 + "." + DBNAME2 + TABLENAME_BASE + "." + ID_COLUMN +
                " JOIN " + DBNAME3 + "." + DBNAME2 + TABLENAME_BASE +
                " ON " + DBNAME1 + TABLENAME_BASE + "." + ID_COLUMN +
                " =  " + DBNAME3 + "." + DBNAME2 + TABLENAME_BASE + "." + ID_COLUMN;

        Log.d("SELECTSQL_1",sqlstr);
        Cursor csr = mMaster.rawQuery(sqlstr,null);
        while (csr.moveToNext()) {
            String logdata = "Row = " + csr.getPosition();
            for (int i=0; i < csr.getColumnCount(); i++) {
                logdata = logdata + " Column = " + csr.getColumnName(i) +
                        " Value = " + csr.getString(i);
            }
            Log.d("CSRINFO",logdata);
        }

        /*
        Log.d("SELECTSQL_ALT",sqlstr);
        Cursor acsr = mAltMaster.rawQuery(sqlstr,null);
        while (acsr.moveToNext()) {
            String logdata = "Row = " + acsr.getPosition();
            for (int i=0; i < acsr.getColumnCount(); i++) {
                logdata = logdata + " Column = " + acsr.getColumnName(i) +
                        " Value = " + acsr.getString(i);
            }
            Log.d("CSRINFO",logdata);
        }
        */

        String arg1 = "12";
        String arg2 = "Fred";

        String sqlstr2 = " SELECT " +
                DB2_FULL_IDCOL + ", " +
                DB2_FULL_NAMECOL + ", " +
                DB3_FULL_IDCOL + ", " +
                DB3_FULL_NAMECOL +
                " FROM " + DBNAME2 + TABLENAME_BASE +
                " JOIN " + DBNAME3 + "." + DBNAME2 + TABLENAME_BASE +
                " ON   " + DBNAME2 + "." + DBNAME2 + TABLENAME_BASE + "." + ID_COLUMN +
                " =    " + DB3_FULL_IDCOL +
                " WHERE " +
                DB2_FULL_IDCOL + "=? AND " +
                DB3_FULL_NAMECOL + "=?";
        Log.d("SELECTSQL_2",sqlstr2);
        Cursor csr2 = mMaster.rawQuery(sqlstr2,new String[]{arg1,arg2});

        while (csr2.moveToNext()) {
            String logdata = "Row = " + csr2.getPosition();
            for (int i=0; i < csr2.getColumnCount(); i++) {
                logdata = logdata + " Column = " + csr2.getColumnName(i) +
                        " Value = " + csr2.getString(i);
            }
            Log.d("CSRINFO",logdata);
        }
    }

    private String createDatbase(String dbqualifier) {
        SQLiteDatabase db = this.openOrCreateDatabase(dbqualifier,Context.MODE_PRIVATE,null);
        String tblcrtstr = "CREATE TABLE IF NOT EXISTS " +
                dbqualifier + TABLENAME_BASE +
                "(" +
                ID_COLUMN + " INTEGER PRIMARY KEY, " +
                dbqualifier + NAMECOLUMN_BASE  + " TEXT" +
                ")";
        db.execSQL(tblcrtstr);
        String rv = db.getPath();
        db.close();
        return rv;
    }

    private String createDatabase(String dbqualifier, String altpath) {
        SQLiteDatabase db = this.openOrCreateDatabase(altpath + "/" + dbqualifier,Context.MODE_PRIVATE, null);
        String tblcrtstr = "CREATE TABLE IF NOT EXISTS " +
                dbqualifier + TABLENAME_BASE +
                "(" +
                ID_COLUMN + " INTEGER PRIMARY KEY, " +
                dbqualifier + NAMECOLUMN_BASE  + " TEXT" +
                ")";
        db.execSQL(tblcrtstr);
        String rv = db.getPath();
        db.close();
        return rv;
    }

    private void insertRow(String dbqualifier, String name) {
        SQLiteDatabase db = this.openOrCreateDatabase(dbqualifier,MODE_PRIVATE,null);
        ContentValues cv = new ContentValues();
        cv.put(dbqualifier + NAMECOLUMN_BASE, name);
        db.insert(dbqualifier + TABLENAME_BASE,null,cv);
        db.close();
    }

    private void insertAltRow(String dbqualifier, String name) {
        SQLiteDatabase db = this.openOrCreateDatabase(altbasepath + "/" + dbqualifier, MODE_PRIVATE,null);
        ContentValues cv = new ContentValues();
        cv.put(dbqualifier + NAMECOLUMN_BASE, name);
        db.insert(dbqualifier + TABLENAME_BASE, null, cv);
        db.close();
    }
}

Attempts to recreate the same error :-

1 - Try to open with a path that has a non-existing file :-

Changed code to :-

mAltMaster = this.openOrCreateDatabase(mDBA1Path+"x",Context.MODE_PRIVATE,null);

Fails trying to open :-

12-08 06:03:31.294 1482-1482/? E/SQLiteLog: (14) cannot open file at line 30174 of [00bb9c9ce4]
12-08 06:03:31.294 1482-1482/? E/SQLiteLog: (14) os_unix.c:30174: (21) open(/data/data/mjt.attachdatabases/db1x) -
12-08 06:03:31.294 1482-1482/? E/SQLiteDatabase: Failed to open database '/data/data/mjt.attachdatabases/db1x'.
                                                 android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database

2 - Skip the open and try to attach with non-existing file :-

e.g. ATTACH DATABASE '/data/data/mjt.attachdatabases/db2blah' AS db2

The ATTACH works but fails later due to table not found (i.e. the database is created, as attach appears to use openOrCreate, but has no user defined tables).

3 - try to attach a database that is not a database file, in this case a pdf file renamed to db2blah.

The ATTACH fails with :-

E/SQLiteLog: (26) statement aborts at 5: [ATTACH DATABASE '/data/data/mjt.attachdatabases/db2blah' AS db2] file is encrypted or is not a database

All the above appear to not meet the error. So perhaps the issue is that the database file doesn't have the appropriate permissions, another possibility is that the file may be in use.


问:
Using Dynamic SQL for Column Headers in SSRS Report Builder Execute(@Query) - Use Values From 1 Table as Col Headers for Values From A Different Table

I am using Microsoft SQL Server Report Builder 3.0 on SQL Server Reporting Services 2012.

I have a stored procedure that uses dynamic SQL.  It works great when executing it in SQL, but when I use this as a data set in Report Builder, it doesn't load any data fields.

The reason I wrote this as dynamic SQL is because I want to use field values from a specific table as column headers for other fields accessed from different tables in my result set.

Below is a portion of the code from the sp.  The actual sp joins to many more tables and pulls more data fields.

```<code>DECLARE @INRM as char(30)
        ,@OUTRM as char(30)
        ,@PROCSTART as char(30)
        ,@PROCEND as char(30)
        ,@Query as NVARCHAR(MAX)

SET NOCOUNT ON;

SELECT ST.SurTimeID, ST.Name
INTO #STL
FROM [livefdb].[dbo].[SurTime_Main] as ST

**SET @INRM = (select c.Name
            from #STL as c
            where c.SurTimeID = 'INRM')
SET @OUTRM = (select c.Name
            from #STL as c
            where c.SurTimeID = 'OUTRM')
SET @PROCSTART = (select c.Name
                from #STL as c
                where c.SurTimeID = 'PROCSTART')
SET @PROCEND = (select c.Name
                from #STL as c
                where c.SurTimeID = 'PROCEND')**

DROP TABLE #STL

-- Insert statements for procedure here
SET @Query =
'SELECT CAST(CIO.IntraoperativeOperationDateTime as date) as [Operation Date]
    ,REG.AccountNumber as [Account Number]
    ,HRM.Name as [Patient Name]
    ,CSE.OperatingRoom_CwsResRoomID as [Operating Room]
    ,SRG.NameWithCredentialsStored as [Case Surgeon]
    ,ISNULL(CASE    WHEN CONVERT(DATE,INRM.IntraoperativeDateTime) = ''1900-01-01'' THEN ''''
                    ELSE CONVERT(VARCHAR(23),INRM.IntraoperativeDateTime,121)
                    END,'''') as **['+ @INRM +']**
    ,ISNULL(CASE    WHEN CONVERT(DATE,PS.IntraoperativeDateTime) = ''1900-01-01'' THEN ''''
                    ELSE CONVERT(VARCHAR(23),PS.IntraoperativeDateTime,121)
                    END,'''') as **['+ @PROCSTART +']**
    ,ISNULL(CASE    WHEN CONVERT(DATE,PE.IntraoperativeDateTime) = ''1900-01-01'' THEN ''''
                    ELSE CONVERT(VARCHAR(23),PE.IntraoperativeDateTime,121)
                    END,'''') as **['+ @PROCEND +']**
    ,ISNULL(CASE    WHEN CONVERT(DATE,OUTRM.IntraoperativeDateTime) = ''1900-01-01'' THEN ''''
                    ELSE CONVERT(VARCHAR(23),OUTRM.IntraoperativeDateTime,121)
                    END,'''') as **['+ @OUTRM +']**

FROM [livefdb].[dbo].[SurCase_Main] as CSE with (nolock)

INNER JOIN [livefdb].[dbo].[SurCase_Inop] as CIO with (nolock)
on CIO.SourceID = CSE.SourceID
    AND CIO.CwsApptID = CSE.CwsApptID

**LEFT JOIN [livefdb].[dbo].[SurCase_InopTimes] as INRM with (nolock)
on INRM.SourceID = CSE.SourceID
    AND INRM.CwsApptID = CSE.CwsApptID
    AND INRM.IntraoperativeTimeLabel_SurTimeID = ''INRM''**

**LEFT JOIN [livefdb].[dbo].[SurCase_InopTimes] as OUTRM with (nolock)
on OUTRM.SourceID = CSE.SourceID
    AND OUTRM.CwsApptID = CSE.CwsApptID
    AND OUTRM.IntraoperativeTimeLabel_SurTimeID = ''OUTRM''**

**LEFT JOIN [livefdb].[dbo].[SurCase_InopTimes] as PS with (nolock)
on PS.SourceID = CSE.SourceID
    AND PS.CwsApptID = CSE.CwsApptID
    AND PS.IntraoperativeTimeLabel_SurTimeID = ''PROCSTART''**

**LEFT JOIN [livefdb].[dbo].[SurCase_InopTimes] as PE with (nolock)
on PE.SourceID = CSE.SourceID
    AND PE.CwsApptID = CSE.CwsApptID
    AND PE.IntraoperativeTimeLabel_SurTimeID = ''PROCEND''**

LEFT JOIN [livefdb].[dbo].[CwsAppt_Main] as APT with (nolock)
on APT.SourceID = CSE.SourceID
    AND APT.CwsApptID = CSE.CwsApptID

LEFT JOIN [livefdb].[dbo].[RegAcct_Main] as REG with (nolock)
on REG.SourceID = APT.SourceID
    AND REG.VisitID = APT.VisitID

LEFT JOIN [livefdb].[dbo].[HimRec_Main] as HRM with (nolock)
on HRM.SourceID = REG.SourceID
    AND HRM.PatientID = REG.PatientID

LEFT JOIN [livefdb].[dbo].[MisPerson_Names] as SRG with (nolock)
on SRG.SourceID = CSE.SourceID
    AND SRG.UnvUserID = CSE.Surgeon_UnvUserID

WHERE CIO.IntraoperativeOperationDateTime
      BETWEEN ''' + CONVERT(VARCHAR(23),@spFromOperationDate,121) + ''' AND '''
          + CONVERT(VARCHAR(23),@spThruOperationDate,121) + ''''
</code>```

The SurTime_Main table contains types of times and their descriptions...not the actual times themselves.

SurTime_Main Record Example:

SurTimeID = 'INRM' (PK)

Name = 'Into Room'

I want to use the description from this table as a column header (SurTime_Main.Name) for a date/time pulled from the SurCase_InopTimes table.  The SurCase_InopTimes table contains the actual times entered and the time types they were entered on.

SurCase_InopTimes Record Examples:

CwsApptID = '1234567890' (PK)

IntraoperativeTimeLabel_SurTimeID = 'INRM' (PK)

IntraoperativeDateTime = '2000-01-01 00:00:00.000'

CwsApptID = '1234567890' (PK)

IntraoperativeTimeLabel_SurTimeID = 'OUTRM' (PK)

IntraoperativeDateTime = '2000-01-01 01:00:00.000'

I hope this makes sense.  If our time type descriptions are ever updated in the future, then the report would be ready to run with updated column header descriptions...at least this is what I was going for.

If dynamic SQL is not an option to use for pulling data fields into Report Builder, is there another way I can accomplish this in SQL or Report Builder itself so that my column headers will be values from the SurTime_Main table?

Thank you in advance.

答:
I've done something similar in the past.

Basically SSRS always expects your dataset to return the same columns every time it's executed.

So taking a very simple example, instead of returning something like

```<code>Creature    Legs    Claws
Dog         4       16
Cat         4       18
</code>```

and then another run returns something like this

```<code>Creature    Arms    Fingers
Human       2       10
Zombie      2       3
</code>```

What I do is return something like this...

```<code>Label    ColumnA    ColumnB     CaptionA    CaptionB
Dog         4       16            Legs        Claws
Cat         4       18            Legs        Claws
</code>```

and next next run with different parameters might return

```<code>Label    ColumnA    ColumnB     CaptionA    CaptionB
Human       2       10            Arms        Fingers
Zombie      2        3            Arms        Fingers
</code>```

In your report design, simply replace the column headers with an expression something like =First(Fields!CaptionA.Value) etc

Body:
I am using Microsoft SQL Server Report Builder 3.0 on SQL Server Reporting Services 2012.

I have a stored procedure that uses dynamic SQL.  It works great when executing it in SQL, but when I use this as a data set in Report Builder, it doesn't load any data fields.

The reason I wrote this as dynamic SQL is because I want to use field values from a specific table as column headers for other fields accessed from different tables in my result set.

Below is a portion of the code from the sp.  The actual sp joins to many more tables and pulls more data fields.

DECLARE @INRM as char(30)
        ,@OUTRM as char(30)
        ,@PROCSTART as char(30)
        ,@PROCEND as char(30)
        ,@Query as NVARCHAR(MAX)

SET NOCOUNT ON;

SELECT ST.SurTimeID, ST.Name
INTO #STL
FROM [livefdb].[dbo].[SurTime_Main] as ST

**SET @INRM = (select c.Name
            from #STL as c
            where c.SurTimeID = 'INRM')
SET @OUTRM = (select c.Name
            from #STL as c
            where c.SurTimeID = 'OUTRM')
SET @PROCSTART = (select c.Name
                from #STL as c
                where c.SurTimeID = 'PROCSTART')
SET @PROCEND = (select c.Name
                from #STL as c
                where c.SurTimeID = 'PROCEND')**

DROP TABLE #STL

-- Insert statements for procedure here
SET @Query =
'SELECT CAST(CIO.IntraoperativeOperationDateTime as date) as [Operation Date]
    ,REG.AccountNumber as [Account Number]
    ,HRM.Name as [Patient Name]
    ,CSE.OperatingRoom_CwsResRoomID as [Operating Room]
    ,SRG.NameWithCredentialsStored as [Case Surgeon]
    ,ISNULL(CASE    WHEN CONVERT(DATE,INRM.IntraoperativeDateTime) = ''1900-01-01'' THEN ''''
                    ELSE CONVERT(VARCHAR(23),INRM.IntraoperativeDateTime,121)
                    END,'''') as **['+ @INRM +']**
    ,ISNULL(CASE    WHEN CONVERT(DATE,PS.IntraoperativeDateTime) = ''1900-01-01'' THEN ''''
                    ELSE CONVERT(VARCHAR(23),PS.IntraoperativeDateTime,121)
                    END,'''') as **['+ @PROCSTART +']**
    ,ISNULL(CASE    WHEN CONVERT(DATE,PE.IntraoperativeDateTime) = ''1900-01-01'' THEN ''''
                    ELSE CONVERT(VARCHAR(23),PE.IntraoperativeDateTime,121)
                    END,'''') as **['+ @PROCEND +']**
    ,ISNULL(CASE    WHEN CONVERT(DATE,OUTRM.IntraoperativeDateTime) = ''1900-01-01'' THEN ''''
                    ELSE CONVERT(VARCHAR(23),OUTRM.IntraoperativeDateTime,121)
                    END,'''') as **['+ @OUTRM +']**

FROM [livefdb].[dbo].[SurCase_Main] as CSE with (nolock)

INNER JOIN [livefdb].[dbo].[SurCase_Inop] as CIO with (nolock)
on CIO.SourceID = CSE.SourceID
    AND CIO.CwsApptID = CSE.CwsApptID

**LEFT JOIN [livefdb].[dbo].[SurCase_InopTimes] as INRM with (nolock)
on INRM.SourceID = CSE.SourceID
    AND INRM.CwsApptID = CSE.CwsApptID
    AND INRM.IntraoperativeTimeLabel_SurTimeID = ''INRM''**

**LEFT JOIN [livefdb].[dbo].[SurCase_InopTimes] as OUTRM with (nolock)
on OUTRM.SourceID = CSE.SourceID
    AND OUTRM.CwsApptID = CSE.CwsApptID
    AND OUTRM.IntraoperativeTimeLabel_SurTimeID = ''OUTRM''**

**LEFT JOIN [livefdb].[dbo].[SurCase_InopTimes] as PS with (nolock)
on PS.SourceID = CSE.SourceID
    AND PS.CwsApptID = CSE.CwsApptID
    AND PS.IntraoperativeTimeLabel_SurTimeID = ''PROCSTART''**

**LEFT JOIN [livefdb].[dbo].[SurCase_InopTimes] as PE with (nolock)
on PE.SourceID = CSE.SourceID
    AND PE.CwsApptID = CSE.CwsApptID
    AND PE.IntraoperativeTimeLabel_SurTimeID = ''PROCEND''**

LEFT JOIN [livefdb].[dbo].[CwsAppt_Main] as APT with (nolock)
on APT.SourceID = CSE.SourceID
    AND APT.CwsApptID = CSE.CwsApptID

LEFT JOIN [livefdb].[dbo].[RegAcct_Main] as REG with (nolock)
on REG.SourceID = APT.SourceID
    AND REG.VisitID = APT.VisitID

LEFT JOIN [livefdb].[dbo].[HimRec_Main] as HRM with (nolock)
on HRM.SourceID = REG.SourceID
    AND HRM.PatientID = REG.PatientID

LEFT JOIN [livefdb].[dbo].[MisPerson_Names] as SRG with (nolock)
on SRG.SourceID = CSE.SourceID
    AND SRG.UnvUserID = CSE.Surgeon_UnvUserID

WHERE CIO.IntraoperativeOperationDateTime
      BETWEEN ''' + CONVERT(VARCHAR(23),@spFromOperationDate,121) + ''' AND '''
          + CONVERT(VARCHAR(23),@spThruOperationDate,121) + ''''

The SurTime_Main table contains types of times and their descriptions...not the actual times themselves.

SurTime_Main Record Example:

SurTimeID = 'INRM' (PK)

Name = 'Into Room'

I want to use the description from this table as a column header (SurTime_Main.Name) for a date/time pulled from the SurCase_InopTimes table.  The SurCase_InopTimes table contains the actual times entered and the time types they were entered on.

SurCase_InopTimes Record Examples:

CwsApptID = '1234567890' (PK)

IntraoperativeTimeLabel_SurTimeID = 'INRM' (PK)

IntraoperativeDateTime = '2000-01-01 00:00:00.000'

CwsApptID = '1234567890' (PK)

IntraoperativeTimeLabel_SurTimeID = 'OUTRM' (PK)

IntraoperativeDateTime = '2000-01-01 01:00:00.000'

I hope this makes sense.  If our time type descriptions are ever updated in the future, then the report would be ready to run with updated column header descriptions...at least this is what I was going for.

If dynamic SQL is not an option to use for pulling data fields into Report Builder, is there another way I can accomplish this in SQL or Report Builder itself so that my column headers will be values from the SurTime_Main table?

Thank you in advance.

Body:
I've done something similar in the past.

Basically SSRS always expects your dataset to return the same columns every time it's executed.

So taking a very simple example, instead of returning something like

Creature    Legs    Claws
Dog         4       16
Cat         4       18

and then another run returns something like this

Creature    Arms    Fingers
Human       2       10
Zombie      2       3

What I do is return something like this...

Label    ColumnA    ColumnB     CaptionA    CaptionB
Dog         4       16            Legs        Claws
Cat         4       18            Legs        Claws

and next next run with different parameters might return

Label    ColumnA    ColumnB     CaptionA    CaptionB
Human       2       10            Arms        Fingers
Zombie      2        3            Arms        Fingers

In your report design, simply replace the column headers with an expression something like =First(Fields!CaptionA.Value) etc


问:
unable to include logged in user id in url(address bar)
I'm trying to echo user id to be displayed in url view db structure here when a user is logged in to a system much like abc.php?uid=5 (Reason is, I need the logged in user id to be passed when a logged in user makes a post so as to use their user_id to display their details in a feeds view page) I've tried various codes but unable to achieve it. When I run the code below, there's no reaction, just stuck at the log in page. Pls I need help.</p>

```<code>    <?php
    session_start();
   include_once('queryclass.php');

  $error = false;
  if(isset($_POST['btn-login'])){
  $username = trim($_POST['username']);
  $username = htmlspecialchars(strip_tags($username));

  $password = trim($_POST['password']);
  $password = htmlspecialchars(strip_tags($password));

   if(empty($username)){
    $error = true;
    $errorUsername = 'Please Input Username';
  }

  if(empty($password)){
    $error = true;
    $errorPassword = 'Please Input Password';
   }elseif(strlen($password)< 6){
    $error = true;
    $errorPassword = 'Password must be at least six characters';
   }

  if(!$error){

        $password = md5($password);
    $sql = "select * from company where username='$username' ";
    $result = mysqli_query($conn, $sql);
    $count = mysqli_num_rows($result);
    $row = mysqli_fetch_assoc($result);
    if($count==1 && $row['password'] == $password){
        $_SESSION['username'] = $row['username'];
        function do_user_directory(){
        $users = $this->load_all_user_objects();
        foreach($users as $user){?>
        header('location: loggedin.php?uid=<?php echo $user->id;?>');
        <?php
        }
        }
    }else{
        $errorMsg = 'Invalid Username or Password';
    }
    }

    }

    ?>

   This is the queryclass.php

  <?php
  require_once('connectdb.php');

  function load_user_object($user_id){
  global $db;

  $table = 'users';

  $query = "
              SELECT * FROM $table
              WHERE ID = $user_id
           ";

   $obj = $db->select($query);
    if(!$obj) {
        return "No user found";
     }

    return $obj[0];

   }

   function load_all_user_objects(){
   global $db;

   $table = 'users';

     $query = "
              SELECT * FROM $table

           ";

   $obj = $db->select($query);

    if(!$obj) {
        return "No user found";
     }

     return $obj;

   }

   ?>
</code>```

答: In query class. Php query statement use single quotes as = '$user_rid'</p>

Body:
I'm trying to echo user id to be displayed in url view db structure here when a user is logged in to a system much like abc.php?uid=5 (Reason is, I need the logged in user id to be passed when a logged in user makes a post so as to use their user_id to display their details in a feeds view page) I've tried various codes but unable to achieve it. When I run the code below, there's no reaction, just stuck at the log in page. Pls I need help.

    <?php
    session_start();
   include_once('queryclass.php');

  $error = false;
  if(isset($_POST['btn-login'])){
  $username = trim($_POST['username']);
  $username = htmlspecialchars(strip_tags($username));

  $password = trim($_POST['password']);
  $password = htmlspecialchars(strip_tags($password));

   if(empty($username)){
    $error = true;
    $errorUsername = 'Please Input Username';
  }

  if(empty($password)){
    $error = true;
    $errorPassword = 'Please Input Password';
   }elseif(strlen($password)< 6){
    $error = true;
    $errorPassword = 'Password must be at least six characters';
   }

  if(!$error){

        $password = md5($password);
    $sql = "select * from company where username='$username' ";
    $result = mysqli_query($conn, $sql);
    $count = mysqli_num_rows($result);
    $row = mysqli_fetch_assoc($result);
    if($count==1 && $row['password'] == $password){
        $_SESSION['username'] = $row['username'];
        function do_user_directory(){
        $users = $this->load_all_user_objects();
        foreach($users as $user){?>
        header('location: loggedin.php?uid=<?php echo $user->id;?>');
        <?php
        }
        }
    }else{
        $errorMsg = 'Invalid Username or Password';
    }
    }

    }

    ?>

   This is the queryclass.php

  <?php
  require_once('connectdb.php');

  function load_user_object($user_id){
  global $db;

  $table = 'users';

  $query = "
              SELECT * FROM $table
              WHERE ID = $user_id
           ";

   $obj = $db->select($query);
    if(!$obj) {
        return "No user found";
     }

    return $obj[0];

   }

   function load_all_user_objects(){
   global $db;

   $table = 'users';

     $query = "
              SELECT * FROM $table

           ";

   $obj = $db->select($query);

    if(!$obj) {
        return "No user found";
     }

     return $obj;

   }

   ?>


答:
If one of the words is going to be the full first name of the full last name, while the other word is a partial of the other, why don't you split up the words first? Then you'd pass in two paramaters and have:</p>

```<code>SELECT
    *
FROM
    myTable
WHERE
    (
        firstName = %content1%
        AND lastName LIKE %content2%
    ) OR (
        lastName = %content1%
        AND firstName LIKE %content2%
    )
</code>```

Title: SQL condition: (A=B AND C LIKE %D%) OR (A LIKE %B% AND C=D)

Body:
I've got a table of first names and last names.

I'm trying to make a jQuery instant search on an input, in order to find very quickly and precisely a person in a huge list of people.

When the first word is entered in the input, it might be the first name or the last name.

I do this : SELECT * FROM myTable WHERE firstName LIKE %content% OR lastName LIKE %content%

When two words are entered, it might be:
* the full firstname and a bit of the lastname
* the full lastname and a bit of the firstame

So I tried this query : SELECT * FROM myTable WHERE (firstName = content1 AND lastName LIKE %content2%) OR ( lastName = content1 AND firstName LIKE %content2%)

Unfortunately parenthesis seems to do nothing, and the query is not interpreted this way, I've got a lot of results, basically produced by the two LIKE %% condition

Anyone had deal with this before and could give me a hand?

Thanx

Body:
If one of the words is going to be the full first name of the full last name, while the other word is a partial of the other, why don't you split up the words first? Then you'd pass in two paramaters and have:

SELECT
    *
FROM
    myTable
WHERE
    (
        firstName = %content1%
        AND lastName LIKE %content2%
    ) OR (
        lastName = %content1%
        AND firstName LIKE %content2%
    )