问:
PHP - array_diff all similar values are compared and removed
I would appreciate a little help . I have tried array_diff(), intersect combos but not able to get my expected return.

Here is an example what i want to do.

First array.

```<code>Array
(
    [0] => 21
    [1] => 2
    [2] => 1
    [3] => 2
)
</code>```

Second array

```<code>Array
(
    [0] => 21
    [1] => 2
)
</code>```

using array_diff(firstarray, secondarray) i get following.

```<code>Array
(
    [2] => 1
)
</code>```

But what i want

```<code>Array
(
    [2] => 1
    [3] => 2
)
</code>```

keys from firstarray and secondarray wont necessarily be same.

答:
in that case you can use "in_array" to check if exists and "array_search" to get the key and "unset" to delete an element from the array like this:

```<code>    $array1 = array(21, 2, 1, 2);
    $array2 = array(21, 2);
    $result = array();
    for ($i=0; $i < count($array1) ; $i++) {
        if (in_array($array1[$i], $array2)) {
            unset($array2[array_search($array1[$i], $array2)]);
        } else {
            array_push($result,$array1[$i]);
        }
    }
</code>```

and the output will be:

```<code>Array ( [0] => 1 [1] => 2 )
</code>```

Body:
I would appreciate a little help . I have tried array_diff(), intersect combos but not able to get my expected return.

Here is an example what i want to do.

First array.

Array
(
    [0] => 21
    [1] => 2
    [2] => 1
    [3] => 2
)

Second array

Array
(
    [0] => 21
    [1] => 2
)

using array_diff(firstarray, secondarray) i get following.

Array
(
    [2] => 1
)

But what i want

Array
(
    [2] => 1
    [3] => 2
)

keys from firstarray and secondarray wont necessarily be same.

Body:
in that case you can use "in_array" to check if exists and "array_search" to get the key and "unset" to delete an element from the array like this:

    $array1 = array(21, 2, 1, 2);
    $array2 = array(21, 2);
    $result = array();
    for ($i=0; $i < count($array1) ; $i++) {
        if (in_array($array1[$i], $array2)) {
            unset($array2[array_search($array1[$i], $array2)]);
        } else {
            array_push($result,$array1[$i]);
        }
    }

and the output will be:

Array ( [0] => 1 [1] => 2 )


来源: stackexchange

问:
Online JS / CSS / HTML minifier
Is there a service out there that provides public API for compressing CSS or Javascript?

(Like imgur let's you upload images trough PHP and get the image URL)

答:
I am using .Maui and it is awesome! You can minify and combine CSS and JS using the web tool or the free API. For JS it even optimize the code and is ES5 and ES6 compatible! There are other useful tools like Sitemap Generator, HTML Minify, Image Resizer and Free CDN for the minified files.

Before i tried Google Closure Compiler, cssminifier.com and javascript-minifier.com, but they have restrict limits of POST size and number of requests per second.

ContentLicense: CC BY-SA 3.0

Title: Online JS / CSS / HTML minifier


问:
I want to display results after a search of the database in a div dynamically. Right now i can achieve only one result how to make it auto
//my php code that connects to database</p>

```<code><?php
    $output = NULL;
    if(isset($_POST['submit'])){

        $search = $link->real_escape_string($_POST['search']);

        //Query the database
        $resultSet = $link->query("SELECT * FROM members WHERE city LIKE '$search%'");

        if($resultSet->num_rows > 0){
            while($rows = $resultSet->fetch_assoc())
            {
                $fname = $rows['firstname'];
                $lname = $rows['lastname'];
                $city = $rows['city'];
                $price = $rows['price'];
                $img = $rows['img'];
                $output = " $city ";

            }
        } else{
         $output = "no results";
        }

    }
?>

// DIv where i want to display the results dynamically

<ul class="products">
    <li >
        <a href="#" >
            <img width="450" height="450" src="<?php echo $img; ?>"  alt="Dancing between Red Mountain" title="nature-person-red-woman" />
            <h3><?php echo $fname ." ". $lname; ?></h3> <span class="price"><span >

                <span >£</span><?php echo $price; ?></span>
                </span>

        </a>
    </li>
</ul>
</code>```

答:
Put your DIV output INSIDE the while loop. It is the WHILE loop that is consuming all your result set</p>

```<code><?php
    $output = NULL;
    if(isset($_POST['submit'])){

        $search = $link->real_escape_string($_POST['search']);

        //Query the database
        $resultSet = $link->query("SELECT * FROM members WHERE city LIKE '$search%'");

        if($resultSet->num_rows > 0){
            while($rows = $resultSet->fetch_assoc())
            {
                $fname = $rows['firstname'];
                $lname = $rows['lastname'];
                $city = $rows['city'];
                $price = $rows['price'];
                $img = $rows['img'];
                $output = " $city ";
                // DIv where i want to display the results dynamically
?>
                <ul class="products">
                    <li>
                        <a href="#">
                            <img width="450" height="450" src="<?php echo $img; ?>" alt="Dancing between Red Mountain" title="nature-person-red-woman" />
                            <h3><?php echo $fname ." ". $lname; ?></h3>
                            <span class="price"><span >
                            <span>£</span><?php echo $price; ?></span>
                        </a>
                    </li>
                </ul>
<?php
           } // endwhile
        } else{
         $output = "no results";
        }

    }
?>
</code>```

Body:
//my php code that connects to database

<?php
    $output = NULL;
    if(isset($_POST['submit'])){

        $search = $link->real_escape_string($_POST['search']);

        //Query the database
        $resultSet = $link->query("SELECT * FROM members WHERE city LIKE '$search%'");

        if($resultSet->num_rows > 0){
            while($rows = $resultSet->fetch_assoc())
            {
                $fname = $rows['firstname'];
                $lname = $rows['lastname'];
                $city = $rows['city'];
                $price = $rows['price'];
                $img = $rows['img'];
                $output = " $city ";

            }
        } else{
         $output = "no results";
        }

    }
?>

// DIv where i want to display the results dynamically

            <img width="450" height="450" src="<?php echo $img; ?>"  alt="Dancing between Red Mountain" title="nature-person-red-woman" />

<?php echo $fname ." ". $lname; ?>

                £<?php echo $price; ?>

Body:
Put your DIV output INSIDE the while loop. It is the WHILE loop that is consuming all your result set

<?php
    $output = NULL;
    if(isset($_POST['submit'])){

        $search = $link->real_escape_string($_POST['search']);

        //Query the database
        $resultSet = $link->query("SELECT * FROM members WHERE city LIKE '$search%'");

        if($resultSet->num_rows > 0){
            while($rows = $resultSet->fetch_assoc())
            {
                $fname = $rows['firstname'];
                $lname = $rows['lastname'];
                $city = $rows['city'];
                $price = $rows['price'];
                $img = $rows['img'];
                $output = " $city ";
                // DIv where i want to display the results dynamically
?>
                <ul class="products">
                    <li>
                        <a href="#">
                            <img width="450" height="450" src="<?php echo $img; ?>" alt="Dancing between Red Mountain" title="nature-person-red-woman" />
                            <h3><?php echo $fname ." ". $lname; ?></h3>
                            <span class="price"><span >
                            <span>&pound;</span><?php echo $price; ?></span>
                        </a>
                    </li>
                </ul>
<?php
           } // endwhile
        } else{
         $output = "no results";
        }

    }
?>


问:
How do I get the runtime Class of a parameterized Type in a Scala trait
I'm trying to implement a Scala trait that handles the details of interfacing with a Java library that requires us to create

What I want to do is something like:

```<code>trait SomeTrait[A] extends JavaAPI {
  def foo = {
    callApi(classOf[A])
  }

  override def bar = {
    foo
  }
}
</code>```

Note that bar is actually overriding a method from a base class, so I can't change it's signature.

I've tried several variations with Manifests, etc., but can't quite get this to work. Is there a way to get the runtime class of a parameterized type?

答:
Due to type erasure, the compiler has no way to figure out what the type should be within the trait. Thus what you want can't be done. However, you could make it a class. That way the compiler can pass an evidence parameter when an instance is created.

```<code>class SomeTrait[A](implicit ev: Manifest[A]) extends JavaApi {
  def foo = {
    callApi(ev.erasure)
  }

  override def bar = {
    foo
  }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to implement a Scala trait that handles the details of interfacing with a Java library that requires us to create

What I want to do is something like:

trait SomeTrait[A] extends JavaAPI {
  def foo = {
    callApi(classOf[A])
  }

  override def bar = {
    foo
  }
}

Note that bar is actually overriding a method from a base class, so I can't change it's signature.

I've tried several variations with Manifests, etc., but can't quite get this to work. Is there a way to get the runtime class of a parameterized type?

Body:
Due to type erasure, the compiler has no way to figure out what the type should be within the trait. Thus what you want can't be done. However, you could make it a class. That way the compiler can pass an evidence parameter when an instance is created.

class SomeTrait[A](implicit ev: Manifest[A]) extends JavaApi {
  def foo = {
    callApi(ev.erasure)
  }

  override def bar = {
    foo
  }
}


问:
Makefile can't find input files in specified directory
I am working with the following Makefile:

```<code>CFLAGS=-g -O2 -Wall -Wextra -Isrc -rdynamic -DNDEBUG $(OPTFLAGS)
LIBS=-ldl $(OPTLIBS)
PREFIX?=/usr/local

SOURCES=$(wildcard src/lcthw/*.c src/*.c)
OBJECTS=$(patsubst %.c,%.o,$(SOURCES))

TEST_SRC=$(wildcard tests/*_tests.c)
TESTS=$(patsubst %.c,%,$(TEST_SRC))

TARGET=build/libYOUR_LIBRARY.a
SO_TARGET=$(patsubst %.a,%.so,$(TARGET))

all: $(TARGET) $(SO_TARGET) tests

dev: CFLAGS=-g -Wall -Isrc -Wall -Wextra $(OPTFLAGS)
dev: all

$(TARGET): CFLAGS += -fPIC
$(TARGET): build $(OBJECTS)
   ar rcs $@ $(OBJECTS)
   ranlib $@

$(SO_TARGET): $(TARGET) $(OBJECTS)
   $(CC) -shared -o $@ $(OBJECTS)

build:
   @mkdir -p build
   @mkdir -p bin

# The Unit Tests
.PHONY: tests
tests: CFLAGS += $(TARGET)
tests: $(TESTS)
   sh ./tests/runtests.sh

valgrind:
   VALGRIND="valgrind --log-file=/tmp/valgrind-%p.log" $(MAKE)

# The Cleaner
clean:
   rm -rf build $(OBJECTS) $(TESTS)
   rm -f tests/tests.log
   find . -name "*.gc*" -exec rm {} \;
   rm -rf `find . -name "*.dSYM" -print`

install: all
   install -d $(DESTDIR)/$(PREFIX)/lib/
   install $(TARGET) $(DESTDIR)/$(PREFIX)/lib/
</code>```

And I'm having trouble with this line:

```<code>$(CC)   -shared -o  $@  $(OBJECTS)
</code>```

I am getting the error:

```<code>cc: fatal error: no input files
</code>```

when I try and run any of the following commands: make, make all and make dev. Why can't my makefile find the .c files in the directories I specified?

答:
You need to specify the full paths in this line:

SOURCES=$(wildcard src/lcthw/.c src/.c)

OTW this becomes a constraint on where you can run the make command from. Possibly what's happening is that the wildcards are not being expanded since the directory you are sitting in, $(CURDIR) , makes it hard for it to see these paths.

You should try printing these variables from inside your makefile, by doing:

```<code>$(info source=$(SOURCES))
</code>```

And if your .obj files are placed in a different location than the sources, then you need to account for that by including that place in the $(OBJECTS) as well.

OwnerDisplayName: aprdrivesmecrazy

Body:
I am working with the following Makefile:

CFLAGS=-g -O2 -Wall -Wextra -Isrc -rdynamic -DNDEBUG $(OPTFLAGS)
LIBS=-ldl $(OPTLIBS)
PREFIX?=/usr/local

SOURCES=$(wildcard src/lcthw/*.c src/*.c)
OBJECTS=$(patsubst %.c,%.o,$(SOURCES))

TEST_SRC=$(wildcard tests/*_tests.c)
TESTS=$(patsubst %.c,%,$(TEST_SRC))

TARGET=build/libYOUR_LIBRARY.a
SO_TARGET=$(patsubst %.a,%.so,$(TARGET))

all: $(TARGET) $(SO_TARGET) tests

dev: CFLAGS=-g -Wall -Isrc -Wall -Wextra $(OPTFLAGS)
dev: all

$(TARGET): CFLAGS += -fPIC
$(TARGET): build $(OBJECTS)
   ar rcs $@ $(OBJECTS)
   ranlib $@

$(SO_TARGET): $(TARGET) $(OBJECTS)
   $(CC) -shared -o $@ $(OBJECTS)

build:
   @mkdir -p build
   @mkdir -p bin

# The Unit Tests
.PHONY: tests
tests: CFLAGS += $(TARGET)
tests: $(TESTS)
   sh ./tests/runtests.sh

valgrind:
   VALGRIND="valgrind --log-file=/tmp/valgrind-%p.log" $(MAKE)

# The Cleaner
clean:
   rm -rf build $(OBJECTS) $(TESTS)
   rm -f tests/tests.log
   find . -name "*.gc*" -exec rm {} \;
   rm -rf `find . -name "*.dSYM" -print`

install: all
   install -d $(DESTDIR)/$(PREFIX)/lib/
   install $(TARGET) $(DESTDIR)/$(PREFIX)/lib/

And I'm having trouble with this line:

$(CC)   -shared -o  $@  $(OBJECTS)

I am getting the error:

cc: fatal error: no input files

when I try and run any of the following commands: make, make all and make dev. Why can't my makefile find the .c files in the directories I specified?

Body:
You need to specify the full paths in this line:

SOURCES=$(wildcard src/lcthw/.c src/.c)

OTW this becomes a constraint on where you can run the make command from. Possibly what's happening is that the wildcards are not being expanded since the directory you are sitting in, $(CURDIR) , makes it hard for it to see these paths.

You should try printing these variables from inside your makefile, by doing:

$(info source=$(SOURCES))

And if your .obj files are placed in a different location than the sources, then you need to account for that by including that place in the $(OBJECTS) as well.

OwnerDisplayName: Rakesh Sharma


问:
Payment Services Exception Domain verification failed for merchantId
I verified my domain successfully via Apple Developer Account. But, when I try to call Apple's registerMerchant API they respond with:

statusMessage: Payment Services Exception Domain verification failed for merchantId...
errorMessage=\"exception decoding Hex string: invalid characters encountered in Hex string\""
statusCode: 400

Did anyone encounter this error?

答: Apple was expecting to find a specific domain-verification-file (that they provided us). When I uploaded the correct file, the issue was resolved.</p>


问:
Connect android client with backend app engine module
This question is because most of the information I find is obsolete and the google documentation I have found is not so clear for me.

Thing is I am developing an application with the backend in app engine and I am not sure how to pass the information between client and server, I have done the endpoints of my server logic and everything i find is not so clear.

I wish to make http querys with the info in Json, also I'm not sure how to use the async calls in the client even when I have the client library (from server endpoints) generated. I'm using Android Studio.

Please don't link obsoletes tutorials, most of the library or methods they use are deprecated and i'm not sure if is someone developing now for app engine or is better to build a server more traditional.

Thank you all

Actualization

Then I finally decided to follow this tutorial:

https://github.com/GoogleCloudPlatform/gradle-appengine-templates/tree/master/HelloEndpoints

Thing is It seems to be the solution but in my case It is not working.

To test in a real device in a LAN with the development server Do yo know if It is necessary some specific configuration else?

More than:

```<code>appengine {
  httpAddress = "0.0.0.0"
}
</code>```

and

```<code> .setRootUrl("http://<my-computer-address>:8080/_ah/api/")
</code>```

I mean some kind of Auth or maybe the router blocks??

Thanks

答:
actually, I don't understand clearly your question, but I guess you wanna connect your application to your backend ( API Webservice), right?
When I was a junior developer (Now, I am also a junior, but I have experience), I used HttpClient even thought it was deprecated.
Then I used OkHttpClient, it's ok and didn't have any problem but I think what senior program will do ? Then my friends told me about Retrofit (library), to handle data you can use reactivex.rxjava . You can try to explore base on my flow
Reply if my opinion is wrong or have any confuse. Thanks</p>

Body:
This question is because most of the information I find is obsolete and the google documentation I have found is not so clear for me.

Thing is I am developing an application with the backend in app engine and I am not sure how to pass the information between client and server, I have done the endpoints of my server logic and everything i find is not so clear.

I wish to make http querys with the info in Json, also I'm not sure how to use the async calls in the client even when I have the client library (from server endpoints) generated. I'm using Android Studio.

Please don't link obsoletes tutorials, most of the library or methods they use are deprecated and i'm not sure if is someone developing now for app engine or is better to build a server more traditional.

Thank you all

Actualization

Then I finally decided to follow this tutorial:

https://github.com/GoogleCloudPlatform/gradle-appengine-templates/tree/master/HelloEndpoints

Thing is It seems to be the solution but in my case It is not working.

To test in a real device in a LAN with the development server Do yo know if It is necessary some specific configuration else?

More than:

appengine {
  httpAddress = "0.0.0.0"
}

and

 .setRootUrl("http://<my-computer-address>:8080/_ah/api/")

I mean some kind of Auth or maybe the router blocks??

Thanks


问:
very slow to get specific rows in scipy csr_matrix and use sparse.vstack to combine them
I'm learning machine learning and I have two tables, the first one is the training set which includes a column named "userID".

The other table is the App feature of each user(the apps each user have) and was transformed as csr_matrix which looks like(in dense form):

```<code>[[0,1,...0,1],[1,0,...,1,1],[0,0,...0,0]...]
</code>```

some of the row in csr_matrix are all zeros element. For each userID in first table, I construct the app feature by getting the corresponding row from the feature matrix and vstack one by one.

```<code>index = userMap[userID] # the userMap contains {userID: index},index is the row index in csr_matrix
userAppfeat = sparse.vstack((userAppfeat,App_csr_Matrix.getrow(index)))
</code>```

It's very slow to add a row to the existing userAppfeat. It is because of the getrow() or the vstack()?  Or i guess it's some rows that contains all zero element cause this.
 and another strange thing is that for the first 100k users it used 5 mins but for the second 100k users it used 20 mins.

答:
It's been noted many times that building a dense array iteratively is slow.  Doing a concatenate at each step creates a new array each time. It is better to collect values in a list, and do one array creation at the end.

Sparse matrix iteration is even slower.  getrow creates a new (1,n) csr matrix; vstack constructs a new matrix from the components, using the coo attributes.

```<code>In [74]: M=sparse.rand(100,100,.2,'csr')
In [75]: idx=np.random.randint(0,100,50)
In [76]:
    ...: target = sparse.csr_matrix((0,100))
    ...: for i in idx:
    ...:    target=sparse.vstack([target, M.getrow(i)])
    ...:
In [77]: target
Out[77]:
<50x100 sparse matrix of type '<class 'numpy.float64'>'
    with 944 stored elements in Compressed Sparse Row format>
</code>```

But we don't have to iterate.  M accepts a list of row indices.

```<code>In [78]: M[idx,:]
Out[78]:
<50x100 sparse matrix of type '<class 'numpy.float64'>'
    with 944 stored elements in Compressed Sparse Row format>
In [79]:
In [79]: %%timeit
    ...: target = sparse.csr_matrix((0,100))
    ...: for i in idx:
    ...:    target=sparse.vstack([target, M.getrow(i)])
    ...:
100 loops, best of 3: 10.4 ms per loop
In [80]:
In [80]: timeit M[idx,:]
1000 loops, best of 3: 334 µs per loop
</code>```

The M[idx,:] actually constructs an extractor matrix, p, and performs a matrix multiplication, p*M.  csr matrices are optimized for multiplication tasks.

Iterative but with delayed vstack:

```<code>In [94]: %%timeit
    ...: target = []
    ...: for i in idx: target.append(M.getrow(i))
    ...: target = sparse.vstack(target)
100 loops, best of 3: 4.63 ms per loop
</code>```

Body:
I'm learning machine learning and I have two tables, the first one is the training set which includes a column named "userID".

The other table is the App feature of each user(the apps each user have) and was transformed as csr_matrix which looks like(in dense form):

[[0,1,...0,1],[1,0,...,1,1],[0,0,...0,0]...]

some of the row in csr_matrix are all zeros element. For each userID in first table, I construct the app feature by getting the corresponding row from the feature matrix and vstack one by one.

index = userMap[userID] # the userMap contains {userID: index},index is the row index in csr_matrix
userAppfeat = sparse.vstack((userAppfeat,App_csr_Matrix.getrow(index)))

It's very slow to add a row to the existing userAppfeat. It is because of the getrow() or the vstack()?  Or i guess it's some rows that contains all zero element cause this.
 and another strange thing is that for the first 100k users it used 5 mins but for the second 100k users it used 20 mins.

Body:
It's been noted many times that building a dense array iteratively is slow.  Doing a concatenate at each step creates a new array each time. It is better to collect values in a list, and do one array creation at the end.

Sparse matrix iteration is even slower.  getrow creates a new (1,n) csr matrix; vstack constructs a new matrix from the components, using the coo attributes.

In [74]: M=sparse.rand(100,100,.2,'csr')
In [75]: idx=np.random.randint(0,100,50)
In [76]:
    ...: target = sparse.csr_matrix((0,100))
    ...: for i in idx:
    ...:    target=sparse.vstack([target, M.getrow(i)])
    ...:
In [77]: target
Out[77]:
<50x100 sparse matrix of type '<class 'numpy.float64'>'
    with 944 stored elements in Compressed Sparse Row format>

But we don't have to iterate.  M accepts a list of row indices.

In [78]: M[idx,:]
Out[78]:
<50x100 sparse matrix of type '<class 'numpy.float64'>'
    with 944 stored elements in Compressed Sparse Row format>
In [79]:
In [79]: %%timeit
    ...: target = sparse.csr_matrix((0,100))
    ...: for i in idx:
    ...:    target=sparse.vstack([target, M.getrow(i)])
    ...:
100 loops, best of 3: 10.4 ms per loop
In [80]:
In [80]: timeit M[idx,:]
1000 loops, best of 3: 334 µs per loop

The M[idx,:] actually constructs an extractor matrix, p, and performs a matrix multiplication, p*M.  csr matrices are optimized for multiplication tasks.

Iterative but with delayed vstack:

In [94]: %%timeit
    ...: target = []
    ...: for i in idx: target.append(M.getrow(i))
    ...: target = sparse.vstack(target)
100 loops, best of 3: 4.63 ms per loop


问:
How to change the grouping of items in a list?
So if I have a list like this:

```<code>x = [0,1,2,3,4,5,6,7,8,9]
</code>```

How do I convert this list into something like this:

```<code>x = [01,23,45,67,89]
</code>```

How can I do that?

I know about the built in zip function,
but I don't want a tuple and I want 2 numbers grouped into 1.

答:
Using zip and list comprehensions, assuming data type is going from list of ints to list of strings:</p>

```<code>In [1]: x = [0,1,2,3,4,5,6,7,8,9]

In [2]: pairs = zip(x[::2], x[1::2])

In [3]: pairs
Out[3]: [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)]

In [4]: [str(fst) + str(snd) for fst, snd in pairs]
Out[4]: ['01', '23', '45', '67', '89']
</code>```

Body:
So if I have a list like this:

x = [0,1,2,3,4,5,6,7,8,9]

How do I convert this list into something like this:

x = [01,23,45,67,89]

How can I do that?

I know about the built in zip function,
but I don't want a tuple and I want 2 numbers grouped into 1.

Body:
Using zip and list comprehensions, assuming data type is going from list of ints to list of strings:

In [1]: x = [0,1,2,3,4,5,6,7,8,9]

In [2]: pairs = zip(x[::2], x[1::2])

In [3]: pairs
Out[3]: [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)]

In [4]: [str(fst) + str(snd) for fst, snd in pairs]
Out[4]: ['01', '23', '45', '67', '89']


问:
Finding an entity then attaching relational data vs. using Include and then FirstOrDefault
Considering a table [Person] which has two foreign keys ([Phone_Numbers], [Business_Information]). When using EF Core, we can simply find a Person using the dbContext.Find method like var person = await db.Context.FindAsync<Person>(1); however, the Find method only looks for the entity inside the tracking cache and it does not handle relational properties. In order to solve this, we can call the Entry method to attach those properties like dbContext.Entry<Person>(person).Reference(x=> x.Business_Information). Considering the provided example, we have to call the Entry method twice in this case:

```<code>dbContext.Entry<Person>(person).Reference(x=> x.Business_Information).Load();
dbContext.Entry<Person>(person).Collection(x=> x.Phone_Numbers).Load();
</code>```

An alternative solution is to use the Include method:

```<code>var person = await dbContext.Set<Person>().Include("Business_Information").Include("Phone_Numbers").FirstOrDefaultAsync(x=> x.id == id);
</code>```

The first solution sends two request to the Db (I think the Find method does not send a request if the entity is being tracked); however, I'm not sure how the second one works and accordingly I'm also unsure if it has any performance advantages. I've been thinking the first solution could be faster and more efficient. I'd appreciate if someone clarifies this for me.

答:
It really depends on number of related properties, their type (reference or collection) and in the first case - if they are already loaded or not.

Let say your entity has N reference navigation properties and M collection navigation properties that you want to load.

The approach with Include will always execute 1 + M db queries - one for the entity + reference properties which data is retrieved with JOINs to the corresponding tables and returned as columns in the query result) and one for each collection - regardless of whether the entity and any of the related entities/collections is already loaded.

The approach with explicit loading is more dynamic.

It will execute 1 db query for the entity if it's not loaded in the context, 0 otherwise.

For each reference navigation property it will execute 1 db query if the referenced entity is not already loaded in the context, 0 otherwise.

For each collection navigation property, it will execute 1 db query if the collection is not marked as loaded (db.Entry(entity).Collection(e => e.Collection).IsLoaded == false), 0 otherwise.

At the end, the explicit loading approach could execute between 0 and 1 + N + M db queries.

With all that being said, it's not clear which one is better. If you are using relatively short lived DbContext instances, hence the chances of not execution related queries is low, I would go with Include approach because it is deterministic.

Body:
Considering a table [Person] which has two foreign keys ([Phone_Numbers], [Business_Information]). When using EF Core, we can simply find a Person using the dbContext.Find method like var person = await db.Context.FindAsync<Person>(1); however, the Find method only looks for the entity inside the tracking cache and it does not handle relational properties. In order to solve this, we can call the Entry method to attach those properties like dbContext.Entry<Person>(person).Reference(x=> x.Business_Information). Considering the provided example, we have to call the Entry method twice in this case:

dbContext.Entry<Person>(person).Reference(x=> x.Business_Information).Load();
dbContext.Entry<Person>(person).Collection(x=> x.Phone_Numbers).Load();

An alternative solution is to use the Include method:

var person = await dbContext.Set<Person>().Include("Business_Information").Include("Phone_Numbers").FirstOrDefaultAsync(x=> x.id == id);

The first solution sends two request to the Db (I think the Find method does not send a request if the entity is being tracked); however, I'm not sure how the second one works and accordingly I'm also unsure if it has any performance advantages. I've been thinking the first solution could be faster and more efficient. I'd appreciate if someone clarifies this for me.


问:
Create a Scroll Event with add Event Listener - Javascript
I'm trying to achieve something in vanilla JS and it's not playing ball.  I have an element I want to change color after a certain scroll length, but when I use addEventListener('scroll', function) etc it's not working, but I'm not getting any errors in my console.

Any help would be awesome.

Emily

The code is below and I have a pen here: https://codepen.io/emilychews/pen/eRYwzm

HTML

```<code><div class="box"></div>
</code>```

CSS

```<code>body {height: 200vh;}

.box {
  width: 200px;
  height: 200px;
  background: red;
}
</code>```

JAVASCRIPT

```<code>var box = document.getElementsByClassName('box')[0];

window.addEventListener('scroll', function() {

  if (box.scrollTop > 0) {
    box.style.background = "blue";
  }

});
</code>```

答:
You have to get the scrollTop on the document body element, not on your box. In your case, box.scrollTop will always be 0.

Replace this:

```<code>  if (box.scrollTop > 0) {
    box.style.background = "blue";
  }
</code>```

with this:

```<code>  if (document.body.scrollTop > 0) {
    box.style.background = "blue";
  }
</code>```

Also note, that as of now it's better to use window.pageYOffset as document.body.scrollTop is deprecated in strict mode. Read this to learn more about scroll detection on the entire window.

Demo: https://codepen.io/anon/pen/mwdZwL

Body:
I'm trying to achieve something in vanilla JS and it's not playing ball.  I have an element I want to change color after a certain scroll length, but when I use addEventListener('scroll', function) etc it's not working, but I'm not getting any errors in my console.

Any help would be awesome.

Emily

The code is below and I have a pen here: https://codepen.io/emilychews/pen/eRYwzm

HTML

CSS

body {height: 200vh;}

.box {
  width: 200px;
  height: 200px;
  background: red;
}

JAVASCRIPT

var box = document.getElementsByClassName('box')[0];

window.addEventListener('scroll', function() {

  if (box.scrollTop > 0) {
    box.style.background = "blue";
  }

});

Body:
You have to get the scrollTop on the document body element, not on your box. In your case, box.scrollTop will always be 0.

Replace this:

  if (box.scrollTop > 0) {
    box.style.background = "blue";
  }

with this:

  if (document.body.scrollTop > 0) {
    box.style.background = "blue";
  }

Also note, that as of now it's better to use window.pageYOffset as document.body.scrollTop is deprecated in strict mode. Read this to learn more about scroll detection on the entire window.

Demo: https://codepen.io/anon/pen/mwdZwL


问:
SQL Server: Group By based on one column and get columns based on other column
My data:

```<code>ColumnA                 Column B            ColumnC
A                          Hi                  Yes
A                          Hello               NULL
B                          Hola                Yes
B                          Hola                Yes
B                          Hi                  NULL
C                          ABCD                Yes
</code>```

My SQL should be able to do following:

Group by Column A

Select only those groups of A that contain Yes and Null both in the result of a

Expected Result is:

```<code>ColumnA                 Column B            ColumnC
A                          Hi                  Yes
A                          Hello               NULL
B                          Hola                Yes
B                          Hola                Yes
B                          Hi                  NULL
</code>```

How do I select all values that satisfy above rule?

答:
One method uses GROUP BY and HAVING:

```<code>select columnA
from t
group by columnA
having sum(case when columnC is null then 1 else 0 end) > 0 and
       sum(case when columnC = 'yes' then 1 else 0 end) > 0;
</code>```

Body:
My data:

ColumnA                 Column B            ColumnC
A                          Hi                  Yes
A                          Hello               NULL
B                          Hola                Yes
B                          Hola                Yes
B                          Hi                  NULL
C                          ABCD                Yes

My SQL should be able to do following:

Group by Column A

Select only those groups of A that contain Yes and Null both in the result of a

Expected Result is:

ColumnA                 Column B            ColumnC
A                          Hi                  Yes
A                          Hello               NULL
B                          Hola                Yes
B                          Hola                Yes
B                          Hi                  NULL

How do I select all values that satisfy above rule?

Body:
One method uses GROUP BY and HAVING:

select columnA
from t
group by columnA
having sum(case when columnC is null then 1 else 0 end) > 0 and
       sum(case when columnC = 'yes' then 1 else 0 end) > 0;


问:
angularjs - object property is undefined
In my Angular.js app, I have one parent controller, which generate my present longitude and latitude so that I can get that data into my child controller. My code is given below:

Parent Controller

```<code>(function() {
  'use strict';
   angular.module('app').controller('InitCtrl', InitCtrl);
   function InitCtrl() {
      var init = this;
      init.g_map = {};
      init.g_map.current = {};
      let geocoder = new google.maps.Geocoder();
      // current latitude & longitude
      navigator.geolocation.getCurrentPosition(function(position) {
        init.g_map.current.lat = position.coords.latitude;
         init.g_map.current.lng = position.coords.longitude;
      });
   }
})();
</code>```

Child Controller

```<code>(function() {
   'use strict';

   angular.module('app').controller('ListCtrl', ListCtrl);

   function ListCtrl($scope, $timeout, _, NgMap, RestaurantApi) {
      let list = this;

      list.load = function load() {
        let init = $scope.$parent.init;
        list.res = {};
        list.res = init.g_map.current;
        console.log("list.res  1: ", list.res);
        /* Output (console window):
             list.res 1 : >Object{}
                           {
                               lat: 'my-current-lat'
                               lng: 'my-current-lng'
                           }
            // here I have got my parent controller data
         */
        // but in the following console, I got undefine
        // even if I already got data which is printed previous console
        console.log("list.res  2 : ", list.res.lat, list.res.lng);
       /* Output (console window)
           list.res 2 : undefined undefined
        */
      }

     list.load();
   }

 })();
</code>```

I don't understand why this is happening, any suggestion ?

答:
The function that gets the location is asynchronous, so you are trying to access its properties before it has them. Try the documentation of promises.

Promises in an api call

I have a decent example of how the use a promise in this case, check this jsfiddle.net/0bghsjf8/ and let me know if you need anything else.

Body:
In my Angular.js app, I have one parent controller, which generate my present longitude and latitude so that I can get that data into my child controller. My code is given below:

Parent Controller

(function() {
  'use strict';
   angular.module('app').controller('InitCtrl', InitCtrl);
   function InitCtrl() {
      var init = this;
      init.g_map = {};
      init.g_map.current = {};
      let geocoder = new google.maps.Geocoder();
      // current latitude & longitude
      navigator.geolocation.getCurrentPosition(function(position) {
        init.g_map.current.lat = position.coords.latitude;
         init.g_map.current.lng = position.coords.longitude;
      });
   }
})();

Child Controller

(function() {
   'use strict';

   angular.module('app').controller('ListCtrl', ListCtrl);

   function ListCtrl($scope, $timeout, _, NgMap, RestaurantApi) {
      let list = this;

      list.load = function load() {
        let init = $scope.$parent.init;
        list.res = {};
        list.res = init.g_map.current;
        console.log("list.res  1: ", list.res);
        /* Output (console window):
             list.res 1 : >Object{}
                           {
                               lat: 'my-current-lat'
                               lng: 'my-current-lng'
                           }
            // here I have got my parent controller data
         */
        // but in the following console, I got undefine
        // even if I already got data which is printed previous console
        console.log("list.res  2 : ", list.res.lat, list.res.lng);
       /* Output (console window)
           list.res 2 : undefined undefined
        */
      }

     list.load();
   }

 })();

I don't understand why this is happening, any suggestion ?


问:
** (CompileError) test/integration/listing_authors.test.exs:9: BookcaseApi.Author.__struct__/1
I have a integration test I am working on, but right now it won't compile.

listing_authors.test.exs

```<code>defmodule ListingAuthorsIntegrationTest do
  use ExUnit.Case, async: true
  use Plug.Test
  alias BookcaseApi.Web.Router
  alias BookcaseApi.Author

  @opts Router.init([])
  test 'listing authors' do
    author = %Author{name: "Oscar Wilde"}
             |> Repo.insert!

    # Note: single quotes are for char lists.
    # Note: double quotes are for strings.
    conn = conn(:get, "/authors")
    response = Router.call(conn, @opts)

    assert response.status == 200
    assert response.resp_body == author
  end
end
</code>```

author.ex

```<code>defmodule BookcaseApi.Author do
  use BookcaseApi.Web, :model

  schema "name" do

    timestamps()
  end

  @doc """
  Builds a changeset based on the `struct` and `params`.
  """
  def changeset(struct, params \\ %{}) do
    struct
    |> cast(params, [])
    |> validate_required([])
  end
end
</code>```

stacktrace.txt

```<code>λ mix test test/integration/listing_authors.test.exs                             0 < 18:39:12
** (CompileError) test/integration/listing_authors.test.exs:9: BookcaseApi.Author.__struct__/1 is undefined, cannot expand struct BookcaseApi.Author
    (stdlib) lists.erl:1354: :lists.mapfoldl/3
    test/integration/listing_authors.test.exs:8: (module)
(stdlib) erl_eval.erl:670: :erl_eval.do_apply/6
</code>```

Any help on how I can get the integration test to compile would be awesome.

Update June 4, 2017
This is a phoenix v1.3 rc2 project that was generated with the below command,

```<code>mix phx.new bookcase_api --no-html --no-brunch
</code>```

I then generated a model for the project with the below command,

```<code>mix phoenix.gen.json Author name
</code>```

答: I'm guessing your problem was in using mix phoenix.gen.json (which is the Phoenix 1.2 generator) with a Phoenix 1.3 project. Try using mix phx.gen.json instead. Your model is trying to use BookcaseApi.Web, :model whereas Phoenix 1.3 schemes should use Ecto.Schema instead.

Body:
I have a integration test I am working on, but right now it won't compile.

listing_authors.test.exs

defmodule ListingAuthorsIntegrationTest do
  use ExUnit.Case, async: true
  use Plug.Test
  alias BookcaseApi.Web.Router
  alias BookcaseApi.Author

  @opts Router.init([])
  test 'listing authors' do
    author = %Author{name: "Oscar Wilde"}
             |> Repo.insert!

    # Note: single quotes are for char lists.
    # Note: double quotes are for strings.
    conn = conn(:get, "/authors")
    response = Router.call(conn, @opts)

    assert response.status == 200
    assert response.resp_body == author
  end
end

author.ex

defmodule BookcaseApi.Author do
  use BookcaseApi.Web, :model

  schema "name" do

    timestamps()
  end

  @doc """
  Builds a changeset based on the `struct` and `params`.
  """
  def changeset(struct, params \\ %{}) do
    struct
    |> cast(params, [])
    |> validate_required([])
  end
end

stacktrace.txt

λ mix test test/integration/listing_authors.test.exs                             0 < 18:39:12
** (CompileError) test/integration/listing_authors.test.exs:9: BookcaseApi.Author.__struct__/1 is undefined, cannot expand struct BookcaseApi.Author
    (stdlib) lists.erl:1354: :lists.mapfoldl/3
    test/integration/listing_authors.test.exs:8: (module)
(stdlib) erl_eval.erl:670: :erl_eval.do_apply/6

Any help on how I can get the integration test to compile would be awesome.

Update June 4, 2017
This is a phoenix v1.3 rc2 project that was generated with the below command,

mix phx.new bookcase_api --no-html --no-brunch

I then generated a model for the project with the below command,

mix phoenix.gen.json Author name


问:
How to prevent displaying multiple fragments over each other
I have a multiple-dialog-fragment layout. In the large layout, I show them as dialogs and there's no problem:

```<code>fragment.show(fragmentManager, "fragment_dialog");
</code>```

But in normal devices, I am using a fragment transaction and replace fragments as below:

```<code>FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
transaction.replace(R.id.fragment_container, fragment).addToBackStack(null).commit();
</code>```

The problem is that in normal devices, when I press the menu button twice (or more), the same fragment will be shown over the previous one. Is there a way to find out which fragment is visible right now and prevent it from opening again?

答:
// Replace fragmentCotainer with your container id
Fragment currentFragment = fragmentManager.findFragmentById(R.id.fragmentCotainer);
// Return if the class are the same
if(currentFragment.getClass().equals(fragment.getClass())) return;</p>

Body:
I have a multiple-dialog-fragment layout. In the large layout, I show them as dialogs and there's no problem:

fragment.show(fragmentManager, "fragment_dialog");

But in normal devices, I am using a fragment transaction and replace fragments as below:

FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
transaction.replace(R.id.fragment_container, fragment).addToBackStack(null).commit();

The problem is that in normal devices, when I press the menu button twice (or more), the same fragment will be shown over the previous one. Is there a way to find out which fragment is visible right now and prevent it from opening again?


问:
What does an executable file compilation depends on?
Let assume that I want to compile a C program for a platform. I know that I must specify CPU architecture in compilation because of differences of instruction sets between different CPU architectures. I also know that I must specify the destination platform operation system because of the differences between executable file structures and system calls and ... between different operation systems.

Q1: The question is that if I need to specify the 32bit or 64bit of OS (not of the CPU architecture) too?

In the other word let assume that I have two systems:

64bit CPU + 32 Bit Microsoft Windows

64bit CPU + 64 Bit Microsoft Windows

Is there any difference in compilation a program for above systems?

Q2: When I add -m32 in the options of gcc compiler, what is this 32 for? Is it for Operation System or it is for CPU architecture?

答:
The question is that if I need to specify the 32bit or 64bit of OS (not of the CPU architecture) too?

You don't specify an Operating System (you have only one OS running on a given machine; to run several of them use an hypervisor or some VM). You specify & choose an Application Binary Interface (ABI) since some OSes are able to offer several ABIs (and runtime systems).

Is there any difference in compilation a program for above systems?

Yes, there is some difference (think of sizeof(void*) at least; also the 64 bits ISA uses more registers and the ABI could define different calling conventions, by passing more arguments thru registers). I can't tell more about Windows, which I don't know.

When I add -m32 in the options of gcc compiler, what is this 32 for?

Dive into the documentation of GCC, notably the Invoking GCC chapter.

It is some x86 option:

The -m32 option sets int, long, and pointer types to 32 bits, and generates code that runs on any i386 system.

The -m64 option sets int to 32 bits and long and pointer types to 64 bits, and generates code for the x86-64 architecture. For Darwin only the -m64 option also turns off the -fno-pic and -mdynamic-no-pic options.

Read also about the x32 ABI (which is a Linux specific thing).

I can't say more about Windows specific (which I don't know and never used). But I will explain what is happening on Linux. I leave you to seek similar knowledge for your proprietary Microsoft operating system.

On Linux, the operating system kernel can be configured (at kernel build time) to accept both 32 bits and 64 bits ELF executables and provide a system call runtime environment for both architectures. Such kernels are able to execute with execve(2) both 32 bits executables, and 64 bits executables and provide two different ABIs (one for -m32 for 686 instruction set architecture, another for -m64 for x86-64 ISA) for them. Notice that the same OS kernel enable executions of binary executables in either 32 bits or 64 bits mode.

I don't know Windows, but I could imagine that Microsoft provide also two different runtime environments & ABIs, one for 32 bits 686 ISA and another for 64 bits x86-64 ISA. Maybe one of them is optional and needs to be installed or bought separately (I really don't know and I don't care).

It is up to you to dive into Microsoft documentations to find the details of the differences.

See also x86 calling conventions wikipage.

I recommend reading something like Operating Systems : Three Easy Pieces (freely downloadable, chapter by chapter) to understand more the role of an OS, and also more about the x86-64 ISA, including its long mode.

Of course you need to care of other dependencies (or coupling). Read about DLL hell & dependency hell.


问:
Why does clojure give this arity error
I have the function definition below for map-edit

```<code>(def map-edit
  (fn [m lst k f]
    (if (car lst)
      (assoc m
             (car lst)
             (map-edit (get m (car lst) {}) k f))
      (assoc m k (f (get m k))))))
</code>```

When I try to call this function in my repl

```<code>(map-edit {} (list "oeu") "oeuoeu" (fn [q] "oeu"))
</code>```

I get an error for Arity

```<code>ArityException Wrong number of args (3) passed to: core/map-edit  clojure.lang.AFn.throwArity (AFn.java:429)
</code>```

Why does it think I am only passing 3 arguments?

```<code>; CIDER 0.8.2 (Java 1.8.0_121, Clojure 1.8.0, nREPL 0.2.12)
</code>```

答:
Note

Assuming that @SultanLegend's answer is correct (not accepted as I write), the core update-in does what you require. You could define ...

```<code>(defn map-edit [m lst k f]
  (update-in m (conj (vec lst) k) f))

(map-edit {} (list "oeu") "oeuoeu" (fn [q] "oeu"))
=> {"oeu" {"oeuoeu" "oeu"}}
</code>```

Title: Why does clojure give this arity error

Body:
I have the function definition below for map-edit

(def map-edit
  (fn [m lst k f]
    (if (car lst)
      (assoc m
             (car lst)
             (map-edit (get m (car lst) {}) k f))
      (assoc m k (f (get m k))))))

When I try to call this function in my repl

(map-edit {} (list "oeu") "oeuoeu" (fn [q] "oeu"))

I get an error for Arity

ArityException Wrong number of args (3) passed to: core/map-edit  clojure.lang.AFn.throwArity (AFn.java:429)

Why does it think I am only passing 3 arguments?

; CIDER 0.8.2 (Java 1.8.0_121, Clojure 1.8.0, nREPL 0.2.12)

Body:
Note

Assuming that @SultanLegend's answer is correct (not accepted as I write), the core update-in does what you require. You could define ...

(defn map-edit [m lst k f]
  (update-in m (conj (vec lst) k) f))

(map-edit {} (list "oeu") "oeuoeu" (fn [q] "oeu"))
=> {"oeu" {"oeuoeu" "oeu"}}


问:
Simple Batch In For Loop Not Working
My goal is to convert some files with *.cdr extension to *.ai in a directory. The files look like file_a.cdr. file_b.cdr ......
I have replaced the convert.exe for you to another simple command like copy, so don't ask about the sense here in my example.

```<code>    setlocal enableDelayedExpansion
    for %%f in (*.cdr) do (
    set "infile=%%f"
    set "outfile=%%~nf.ai"
    copy "%infile%" "%outfile%"
    )
</code>```

The output of the batch is always different!!!!

Sometimes it is:

copy "%file_a.cdr" "%file_a.ai" => system cannot find file

or

copy "" "" => system cannot find file

I have already used this syntax copy !infile! !outfile!  with now success:

Thx in advance

答: Use delayed expansion. And surround your variables by ! instead of %</p>

Title: Simple Batch In For Loop Not Working

Body:
My goal is to convert some files with *.cdr extension to *.ai in a directory. The files look like file_a.cdr. file_b.cdr ......
I have replaced the convert.exe for you to another simple command like copy, so don't ask about the sense here in my example.

    setlocal enableDelayedExpansion
    for %%f in (*.cdr) do (
    set "infile=%%f"
    set "outfile=%%~nf.ai"
    copy "%infile%" "%outfile%"
    )

The output of the batch is always different!!!!

Sometimes it is:

copy "%file_a.cdr" "%file_a.ai" => system cannot find file

or

copy "" "" => system cannot find file

I have already used this syntax copy !infile! !outfile!  with now success:

Thx in advance


问:
spring-security & jersey: no automatic redirection to the login site
I ran into the following problem using spring-security 3.0.3 with jersey 1.2:

when i annotate my Jersey Resources with the @Secured or @PreAuthorize Annotations, spring-security does not autoredirect the user-agent to the login page as i want it to. Only the AuthenticationCredentialsNotFoundException gets thrown and a HTTP 500 gets returned to the user-agent instead of a redirection to spring-security's form login page.
Does anyone know why this problem occurs?

Resource:

```<code>@Path("/event")
@Component
public class EventResource extends AbstractBaseResource {

     @Resource(name = "eventService")
     private EventService eventService;

     public void setEventService(EventService eventService) {
         this.eventService = eventService;
     }

 @GET
 @Path("/view/{id}")
 @Produces(MediaType.TEXT_HTML)
 @PreAuthorize("hasRole('ROLE_USER')")
 public Viewable viewEvent(@PathParam("id") long id) throws UnsupportedEncodingException, URISyntaxException{
            ...
        }
}
</code>```

web.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_3_0.xsd"
    version="3.0">
    <filter>
        <filter-name>jersey</filter-name>
        <filter-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</filter-class>
        <init-param>
            <param-name>com.sun.jersey.config.property.WebPageContentRegex</param-name>
            <param-value>/(static|images|js|css|(WEB-INF/views))/.*</param-value>
        </init-param>
        <init-param>
            <param-name>com.sun.jersey.config.property.JSPTemplatesBasePath</param-name>
            <param-value>/WEB-INF/views/</param-value>
        </init-param>
    </filter>

    <filter>
  <filter-name>springSecurityFilterChain</filter-name>
  <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
 </filter>

    <filter-mapping>
        <filter-name>jersey</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <filter-mapping>
  <filter-name>springSecurityFilterChain</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>

    [...]
</web-app>
</code>```

context:

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:security="http://www.springframework.org/schema/security" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
       http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd">

    <context:annotation-config />
    <context:component-scan base-package="..." />
 <context:mbean-export/>

    <security:http auto-config="true" >
     <security:form-login/>
     <security:logout/>
    </security:http>

    <security:authentication-manager>
        <security:authentication-provider ref="..." />
    </security:authentication-manager>

 <security:global-method-security pre-post-annotations="enabled" />

    [...]
</beans>
</code>```

Thank you!

答:
add the following filer to web.xml

```<code><filter>
        <filter-name>Acegi Filter Chain Proxy</filter-name>
        <filter-class>org.springframework.security.util.FilterToBeanProxy</filter-class>
        <init-param>

            <param-name>targetClass</param-name>
            <param-value>org.springframework.security.util.FilterChainProxy</param-value>
        </init-param>
    </filter>
</code>```

update the context file with:

```<code><security:intercept-url pattern="/login*" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
<security:form-login login-page="/login.htm"
                             login-processing-url="/yourprocessingurl.do"
                             default-target-url="/index.htm"
                             authentication-failure-url="/login.htm" />
<security:logout logout-url="/logout" logout-success-url="/logout.jsp" />
<security:anonymous key="anonymous-security" />
</code>```

Body:
I ran into the following problem using spring-security 3.0.3 with jersey 1.2:

when i annotate my Jersey Resources with the @Secured or @PreAuthorize Annotations, spring-security does not autoredirect the user-agent to the login page as i want it to. Only the AuthenticationCredentialsNotFoundException gets thrown and a HTTP 500 gets returned to the user-agent instead of a redirection to spring-security's form login page.
Does anyone know why this problem occurs?

Resource:

@Path("/event")
@Component
public class EventResource extends AbstractBaseResource {

     @Resource(name = "eventService")
     private EventService eventService;

     public void setEventService(EventService eventService) {
         this.eventService = eventService;
     }

 @GET
 @Path("/view/{id}")
 @Produces(MediaType.TEXT_HTML)
 @PreAuthorize("hasRole('ROLE_USER')")
 public Viewable viewEvent(@PathParam("id") long id) throws UnsupportedEncodingException, URISyntaxException{
            ...
        }
}

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_3_0.xsd"
    version="3.0">
    <filter>
        <filter-name>jersey</filter-name>
        <filter-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</filter-class>
        <init-param>
            <param-name>com.sun.jersey.config.property.WebPageContentRegex</param-name>
            <param-value>/(static|images|js|css|(WEB-INF/views))/.*</param-value>
        </init-param>
        <init-param>
            <param-name>com.sun.jersey.config.property.JSPTemplatesBasePath</param-name>
            <param-value>/WEB-INF/views/</param-value>
        </init-param>
    </filter>

    <filter>
  <filter-name>springSecurityFilterChain</filter-name>
  <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
 </filter>

    <filter-mapping>
        <filter-name>jersey</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <filter-mapping>
  <filter-name>springSecurityFilterChain</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>

    [...]
</web-app>

context:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:security="http://www.springframework.org/schema/security" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
       http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd">

    <context:annotation-config />
    <context:component-scan base-package="..." />
 <context:mbean-export/>

    <security:http auto-config="true" >
     <security:form-login/>
     <security:logout/>
    </security:http>

    <security:authentication-manager>
        <security:authentication-provider ref="..." />
    </security:authentication-manager>

 <security:global-method-security pre-post-annotations="enabled" />

    [...]
</beans>

Thank you!

Body:
add the following filer to web.xml

<filter>
        <filter-name>Acegi Filter Chain Proxy</filter-name>
        <filter-class>org.springframework.security.util.FilterToBeanProxy</filter-class>
        <init-param>

            <param-name>targetClass</param-name>
            <param-value>org.springframework.security.util.FilterChainProxy</param-value>
        </init-param>
    </filter>

update the context file with:

<security:intercept-url pattern="/login*" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
<security:form-login login-page="/login.htm"
                             login-processing-url="/yourprocessingurl.do"
                             default-target-url="/index.htm"
                             authentication-failure-url="/login.htm" />
<security:logout logout-url="/logout" logout-success-url="/logout.jsp" />
<security:anonymous key="anonymous-security" />


问:
Java split function gives me a small length of result String array
I have this code:

```<code>String string = "_a_b___";
String[] parts = string.split("_");
</code>```

The result is that variable parts has only three elements

```<code>parts[0] = ""
parts[1] = "a"
parts[2] = "b"
</code>```

This is weird, because there are five "_" chars, so after splitting there should be six elements, not only three of them.

I want

```<code>parts[0] = ""
parts[1] = "a"
parts[2] = "b"
parts[3] = ""
parts[4] = ""
parts[5] = ""
</code>```

How to do that? Thank you very much!

答:
The solution of @Zakir is correct, i would add another information to use it perfectly, to get what you want instead of using split("_", 6) you can generalize it and use :

```<code>String[] parts = string.split("_", string.replace("(?!_)", "").length());
</code>```

Which can accept any length.

for _a_b___ you will get [, a, b, , , ]

Edit

Or like @Bill F mention in comment,  you can also use String[] parts = string.split("_", -1); for any length as well. Java doc

Body:
I have this code:

String string = "_a_b___";
String[] parts = string.split("_");

The result is that variable parts has only three elements

parts[0] = ""
parts[1] = "a"
parts[2] = "b"

This is weird, because there are five "_" chars, so after splitting there should be six elements, not only three of them.

I want

parts[0] = ""
parts[1] = "a"
parts[2] = "b"
parts[3] = ""
parts[4] = ""
parts[5] = ""

How to do that? Thank you very much!

Body:
The solution of @Zakir is correct, i would add another information to use it perfectly, to get what you want instead of using split("_", 6) you can generalize it and use :

String[] parts = string.split("_", string.replace("(?!_)", "").length());

Which can accept any length.

for _a_b___ you will get [, a, b, , , ]

Edit

Or like @Bill F mention in comment,  you can also use String[] parts = string.split("_", -1); for any length as well. Java doc


问:
Is it possible to create a Mongoose hook to apply a projection to all queries
I'd like to prevent a user's encrypted password from getting sent over the wire each time a user requests their information. I know that in mongo I can apply a projection to achieve this

```<code>db.users.findByID(_id, { password: 0 } )
</code>```

but I would prefer to have some sort of .pre() hook to that will apply it to every query. Is this or a functional equivalent possible?

答:
You can configure a field so it'll be excluded from queries by default using select:

```<code>let UserSchema = new Schema({
  ...
  password : { type : String, select : false },
  ...
});
</code>```

You can override that on a per-query basis if you do require the field to be returned:

```<code>db.users.findByID(_id, { password: 1 } )
</code>```

Documented here: http://mongoosejs.com/docs/api.html#schematype_SchemaType-select

Body:
I'd like to prevent a user's encrypted password from getting sent over the wire each time a user requests their information. I know that in mongo I can apply a projection to achieve this

db.users.findByID(_id, { password: 0 } )

but I would prefer to have some sort of .pre() hook to that will apply it to every query. Is this or a functional equivalent possible?

Body:
You can configure a field so it'll be excluded from queries by default using select:

let UserSchema = new Schema({
  ...
  password : { type : String, select : false },
  ...
});

You can override that on a per-query basis if you do require the field to be returned:

db.users.findByID(_id, { password: 1 } )

Documented here: http://mongoosejs.com/docs/api.html#schematype_SchemaType-select


问:
BigQuery: can I lower querying costs by storing data in multiple tables?
I have single table, currently with over 43 million rows in BigQuery that stores data samples. One of the fields is "owner_id". All my queries are done with respect to a single owner.

Example:

```<code>SELECT COUNT(*)
FROM `mydataset.mytable`
WHERE owner_id = "owner23" AND color = "red"
</code>```

Would creating a table for each owner lower my BigQuery query costs? I suspect querying the entire table with WHERE owner_id = "owner23" AND color = "red" requires more GBs to be processed than querying a table with only owner23's data and using WHERE color = "red" . While I suspect this is true, I wanted to confirm.

Also, would splitting my data across multiple tables cause storage costs to increase?

Thanks!

答:
BigQuery pushes filters down to the table storage, particularly for simple queries such as this.  You can read about filter push down here.  Note that Standard SQL has more powerful optimizers from this perspective.

So, I don't think that you would get much benefit.  However, you might want to test and see if it works.  I sincerely doubt that the benefit would be worth the extra complexity of managing the separate tables.

Body:
I have single table, currently with over 43 million rows in BigQuery that stores data samples. One of the fields is "owner_id". All my queries are done with respect to a single owner.

Example:

SELECT COUNT(*)
FROM `mydataset.mytable`
WHERE owner_id = "owner23" AND color = "red"

Would creating a table for each owner lower my BigQuery query costs? I suspect querying the entire table with WHERE owner_id = "owner23" AND color = "red" requires more GBs to be processed than querying a table with only owner23's data and using WHERE color = "red" . While I suspect this is true, I wanted to confirm.

Also, would splitting my data across multiple tables cause storage costs to increase?

Thanks!


问:
Find the index of two minimum values in array
I have an array that contains numbers.

I got the two minimum values (can be the same number) of this array in O(N) but i cant figure out how to get the index of this two values.

For example: in {1,2,3,1,5} the answer will be index 0 and index 3. this is the code i'm using:

```<code>    public static void minMin(int arr[]){
    int min1 = weights[0], min2 = weights[1];
      if(min1 > min2){
       int temp = min1;
       min1 = min2;
       min2 = temp;
      }
      for (int i = 2; i < weights.length; i++) {
       if(weights[i] < min1){
        int temp = min1;
        min1 = weights[i];
        min2 = temp;
       }else if(weights[i] < min2){
        min2 = weights[i];
       }
      }
}
</code>```

答:
In addition to the local variables that keep the minimum values you need variables for the indexes, too.

You initiatilaze them with 0/1 and update them whenever you change the other variables.

Further thinking about this: one other option works without more variables. Storing value + index is convenient (the comment is correct though, you would probably use a distinct class to do that) but not mandatory. Because you can always fetch the value when you have an index!

In that sense: you could change your code to remember indixes only.

Body:
I have an array that contains numbers.

I got the two minimum values (can be the same number) of this array in O(N) but i cant figure out how to get the index of this two values.

For example: in {1,2,3,1,5} the answer will be index 0 and index 3. this is the code i'm using:

    public static void minMin(int arr[]){
    int min1 = weights[0], min2 = weights[1];
      if(min1 > min2){
       int temp = min1;
       min1 = min2;
       min2 = temp;
      }
      for (int i = 2; i < weights.length; i++) {
       if(weights[i] < min1){
        int temp = min1;
        min1 = weights[i];
        min2 = temp;
       }else if(weights[i] < min2){
        min2 = weights[i];
       }
      }
}


问:
Track error of subprocess and failures
I'm maintaining a Perforce server via a Unix executable which logs the errors in the terminal whenever something happens to it. What I would like to do is use Python to start the executable, and then have it watch for any errors being logged in the terminal window from the application it's executing.

The following code works for execution, but I have no idea how to get data back from the subprocess when it gets logged to the terminal via some form of callback.

```<code>import subprocess
subprocess.call(["./p4d"])
</code>```

答:
I usually do it this way

```<code>from subprocess import Popen, PIPE
proc = Popen(["./p4d"], stdout=PIPE, stderr=PIPE)
out, err = pipe.communicate()
</code>```

pipe.communicate() will hang until the process is finished and then returns stdout and stderr

Title: Track error of subprocess and failures

Body:
I'm maintaining a Perforce server via a Unix executable which logs the errors in the terminal whenever something happens to it. What I would like to do is use Python to start the executable, and then have it watch for any errors being logged in the terminal window from the application it's executing.

The following code works for execution, but I have no idea how to get data back from the subprocess when it gets logged to the terminal via some form of callback.

import subprocess
subprocess.call(["./p4d"])

Body:
I usually do it this way

from subprocess import Popen, PIPE
proc = Popen(["./p4d"], stdout=PIPE, stderr=PIPE)
out, err = pipe.communicate()

pipe.communicate() will hang until the process is finished and then returns stdout and stderr


问:
Flask ajax modal
I want to load a page with Bootstrap modal using ajax. Scenario is like,

When a button is clicked,

The button will call ajax to get data,

From flask, it will get related data from DB and return the data in JSON format,

In ajax success part, it will dynamically generate modal page and show it up.

I wasn't able to find a good example and I'm getting errors even returning html page.

My sample code runs on

```<code><html>
<head>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<link rel="stylesheet" href="../static/css/jquery.modal.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="../static/js/jquery.modal.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
// Open modal in AJAX callback
$('#manual-ajax').click(function(event) {
  event.preventDefault();
  $.get(this.href, function(html) {
    $(html).appendTo('body').modal();
  });
});
</script>
</head>
<main>
<a href="/ajax2" id="manual-ajax">second example</a>
</main>
</html>
</code>```

and flask part will return

```<code>@app.route('/ajax2')
def ajax2():
  return app.send_static_file(url_for('static', filename='../templates/ajax2.html'))
</code>```

but it generates 404 error even from beginning. Please help.

答:
You can write: <code>$('id_body_modal').html(html);
$('id_modal').modal('show');
</code></p>

Title: Flask ajax modal

Body:
I want to load a page with Bootstrap modal using ajax. Scenario is like,

When a button is clicked,

The button will call ajax to get data,

From flask, it will get related data from DB and return the data in JSON format,

In ajax success part, it will dynamically generate modal page and show it up.

I wasn't able to find a good example and I'm getting errors even returning html page.

My sample code runs on

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<link rel="stylesheet" href="../static/css/jquery.modal.min.css">

second example

and flask part will return

@app.route('/ajax2')
def ajax2():
  return app.send_static_file(url_for('static', filename='../templates/ajax2.html'))

but it generates 404 error even from beginning. Please help.

Body:
You can write: $('id_body_modal').html(html);
$('id_modal').modal('show');


问:
Are theses two the same
The formula for a sensor I'm using is:

```<code>%RH  = (125 * rhData / 65536) - 6
</code>```

and the routine I've seen is:

```<code>*rhData = ( (uint32_t) readData[0] << 8 ) + ( readData[1] & 0xfc );
*rhData = ( ( ( *rhData ) * 15625L ) >> 13 ) - 6000;
</code>```

I cant see that the two are the same, can someone explain how it works?

Yours Simon M.

答:
Looks like a fixed point format with scale 1000. Then the integer representing the result is

```<code>RH*1000 = 5^3 * rhData / 2^16 * 2^3*5^3
        = 5^6 * rhData / 2^13
        = (15625 * rhData) >> 13
</code>```

which is exactly what is used in the formula.

Title: Are theses two the same

Body:
The formula for a sensor I'm using is:

%RH  = (125 * rhData / 65536) - 6

and the routine I've seen is:

*rhData = ( (uint32_t) readData[0] << 8 ) + ( readData[1] & 0xfc );
*rhData = ( ( ( *rhData ) * 15625L ) >> 13 ) - 6000;

I cant see that the two are the same, can someone explain how it works?

Yours Simon M.

Body:
Looks like a fixed point format with scale 1000. Then the integer representing the result is

RH*1000 = 5^3 * rhData / 2^16 * 2^3*5^3
        = 5^6 * rhData / 2^13
        = (15625 * rhData) >> 13

which is exactly what is used in the formula.


问:
ASP.NET Core WebApi service and Subscripion on AMPQ (Rabbit MQ)
The task is to make a web api (rest) service, namely, the search service.
Also this service should listen queue and reindex things on receiving an event.

What is the best way to insert listening logic to ASP.NET Core WebApi Application?

Here is working solution, but I'm not sure that is pretty good.

Program.cs

```<code>var host = new WebHostBuilder()
    .UseKestrel()
    .UseContentRoot(Directory.GetCurrentDirectory())
    .UseIISIntegration()
    .UseStartup<Startup>()
    .Build();

var ampq = host.Services.GetService(typeof(IAmpqListener)) as IAmpqListener;
ampq?.Subscribe();

host.Run();
</code>```

答:
I have a library for that on github.

This library makes simpler to listen(consume) and/or produce messages via rabbitmq.

Consumer example:

```<code>public class FooWorker : IWorker<FooData>
{
    public string JobName => "foo.job.name"; // Should be same as dispatched job name.

    public bool Work(FooData data)
    {
        // Lets, do whatever you want by data.

        // Return true, if working completed successfully, otherwise return false.
        return true;
    }
}
</code>```

FooWorker is listener. Work method called when messages transferred to the queue named foo.job.name.

For more information: https://github.com/turgayozgur/tossit

Body:
The task is to make a web api (rest) service, namely, the search service.
Also this service should listen queue and reindex things on receiving an event.

What is the best way to insert listening logic to ASP.NET Core WebApi Application?

Here is working solution, but I'm not sure that is pretty good.

Program.cs

var host = new WebHostBuilder()
    .UseKestrel()
    .UseContentRoot(Directory.GetCurrentDirectory())
    .UseIISIntegration()
    .UseStartup<Startup>()
    .Build();

var ampq = host.Services.GetService(typeof(IAmpqListener)) as IAmpqListener;
ampq?.Subscribe();

host.Run();

Body:
I have a library for that on github.

This library makes simpler to listen(consume) and/or produce messages via rabbitmq.

Consumer example:

public class FooWorker : IWorker<FooData>
{
    public string JobName => "foo.job.name"; // Should be same as dispatched job name.

    public bool Work(FooData data)
    {
        // Lets, do whatever you want by data.

        // Return true, if working completed successfully, otherwise return false.
        return true;
    }
}

FooWorker is listener. Work method called when messages transferred to the queue named foo.job.name.

For more information: https://github.com/turgayozgur/tossit


问:
Is there a way to show emojis in Django Admin?
I have various Django CharFields in my app that users use emojis to fill in. When I look in the admin, it looks like blank entries even though they show up properly as emojis on the app frontend.

How can I get emojis to show up in the admin interface so I can see what users have entered?

答:
Emojis are encoding using utf8mb4, so you have to set a connection that uses that encoding. Add this line inside the DATABASES block to your settings.py file:

```<code>'OPTIONS': {'charset': 'utf8mb4'},
</code>```

You can learn more about emoji's support in Django Admin panel in this blog post.

Body:
Emojis are encoding using utf8mb4, so you have to set a connection that uses that encoding. Add this line inside the DATABASES block to your settings.py file:

'OPTIONS': {'charset': 'utf8mb4'},

You can learn more about emoji's support in Django Admin panel in this blog post.


问:
Static library needs MD_DynamicRelease
I use 2 statically linked libraries in my project.
For some reason one of them needs the RuntimeLibrary value MD_DynamicRelease.
The other one needs MT_StaticRelease.

This creates a conflict in my project.

When I compile with /MT:

When I compile with /MD:

Do I need to compile my project differently? Do I need to compile the libraries differently?

答: I just needed to change the CMAKE_CXX_FLAGS_DEBUG and CMAKE_CXX_FLAGS_RELEASE values to the right runtime libraries.</p>

Title: Static library needs MD_DynamicRelease


问:
How can I make my error message show to the right of my input button?
I'll try to explain this best as possible with pictures.

Here is my input button (look at the one under "bet"):

I want the error message to appear here:

However, all my attempts end up like this:

How can I do this? I tried multiple things such as span, inline display, etc.

UPDATE:

Posted full front-end code on github.

CSS: https://gist.github.com/xxFlare/41ed6a1cac81bbda48848d55a716c3dd

HTML: https://gist.github.com/xxFlare/300733b8b848aea829fc6b26ac70eda2

答:
EDIT based on comment, full snippet:

This is with absolute position & coordinates on each error button with a separate class, tweak them to your benefit, note that button padding and margin may push them out of container on smaller width viewports. This will preserve your inputs centered, otherwise I can rework your html to make them inline but will push inputs to the left so labels would need to be aligned manually.

/*Smooth font*/

@font-face {
  font-family: 'smooth';
  font-style: normal;
  font-weight: 400;
  src: local('Smooth/RobotoDraft'), local('Smooth/RobotoDraft-Regular'), url(https://fonts.gstatic.com/s/robotodraft/v1/0xES5Sl_v6oyT7dAKuoni4gp9Q8gbYrhqGlRav_IXfk.woff2) format('woff2'), url(https://fonts.gstatic.com/s/robotodraft/v1/0xES5Sl_v6oyT7dAKuoni7rIa-7acMAeDBVuclsi6Gc.woff) format('woff');
}

/*--------[HEADER]-----------*/

body {
  margin: 0;
}

ul.topnav {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
}

ul.topnav li {
  float: left;
}

ul.topnav li a {
  display: block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  font-family: "smooth";
}

ul.topnav li a:hover:not(.active) {
  background-color: #111;
}

ul.topnav li a.active {
  background-color: #4CAF50;
}

ul.topnav li.right {
  float: right;
}

@media screen and (max-width: 600px) {
  ul.topnav li.right,
  ul.topnav li {
    float: none;
  }
}

/*--------[HEADER]-----------*/

/* Paper box */

.paper {
  border: 6px solid white;
  height: auto;
  margin: 20px;
  padding: 20px;
  width: auto;
  background-color: white;
  margin-left: 3%;
  margin-right: 3%;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
  font-family: "smooth";
}

/* Game box */

.gamebox {
  height: auto;
  margin: 20px;
  padding: 20px;
  width: auto;
  font-family: "smooth";
  background-color: slategray;
  color: white;
  text-align: center;
}

/* Error */

.error {
  height: auto;
  margin: 20px;
  padding: 20px;
  width: auto;
  font-family: "smooth";
  background-color: indianred;
  color: white;
  text-align: center;
  display: none;
}

/* Error */

.beterror1 {
  height: auto;
  margin: 20px;
  padding: 20px;
  width: auto;
  font-family: "smooth";
  background-color: indianred;
  color: white;
  display: inline;
  position: absolute;
  right: 7%;
  top: 250px;
}

.beterror2 {
  height: auto;
  margin: 20px;
  padding: 20px;
  width: auto;
  font-family: "smooth";
  background-color: indianred;
  color: white;
  display inline;
  position: absolute;
  right: 7%;
  top: 325px;
}

.gamebox h1,
h3,
p {
  text-align: center;
}

form {
  text-align: center;
}

input[type=text] {
  width: 20%;
  padding: 12px 20px;
  display: block;
  margin: 0 auto;
  box-sizing: border-box;
  border: 1px solid #555;
  outline: none;
}

input[type=text]:focus {
  background-color: lightblue;
}

button {
  background-color: #4CAF50;
  /* Green */
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  margin: 4px 2px;
  cursor: pointer;
}

button:hover {
  background-color: darkgreen;
  /* Green */
  border: none;
  color: gray;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  margin: 4px 2px;
  cursor: pointer;
}

button:focus {
  outline: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="paper">
  <h2>Play</h2>
  <div class="gamebox">
    <h1><i class="fa fa-btc" aria-hidden="true"></i>itcoin dice game</h1>
    <div class="error" id="error">You don't have anymore bitcoins left. Why not deposit some?</div>
    <h3 id="balance">Balance: 1000BTC</h3>
    <form>
      Bet
      <br>
      <div><input id="userbet" onchange="checkBet()" value="1" type="text" name="bet">
        <div class="beterror1" id="beterror">That is not a valid bet.</div>
      </div>
      <br> Chance
      <br>
      <div><input id="userchance" value="50" type="text" name="chance">
        <div class="beterror2" id="beterror">That is not a good chance.</div>
      </div>
      <br>
      <h3>Payout: 0BTC</h3>
      <button type="button" id="dicebutton" onclick="prepareRoll()" style="vertical-align:middle"><img src="Images/dice.png"> Roll dice!</button>
    </form>
    <button type="button" id="autobet">Autobet</button>
  </div>
</div></code>```

You are putting a div inside a span element which is inline, change that span for a div.

/* Error */

.beterror {
  height: auto;
  margin: 20px;
  padding: 20px;
  width: auto;
  font-family: "smooth";
  background-color: indianred;
  color: white;
  display: inline;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
  Bet
  <br>
  <div>
    <input id="userbet" onchange="checkBet()" value="1" type="text" name="bet">
    <div class="beterror" id="beterror">That is not a valid bet.</div>
  </div>
  <br> Chance
  <br>
  <input id="userchance" value="50" type="text" name="chance">
  <br>
  <h3>Payout: 0BTC</h3>
  <button type="button" id="dicebutton" onclick="prepareRoll()" style="vertical-align:middle"><img src="Images/dice.png"> Roll dice!</button>
</form></code>```

Or, as an alternative you set the button to absolute position and tweak its coordinates:

/* Error */

.beterror {
  height: auto;
  margin: 20px;
  padding: 20px;
  width: auto;
  font-family: "smooth";
  background-color: indianred;
  color: white;
  /*display: inline;*/
  /* new stuff */
  position: absolute;
  top: 0px;
  left: 160px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
  Bet
  <br>
  <span><input id="userbet" onchange="checkBet()" value="1" type="text" name="bet"><div class="beterror" id="beterror">That is not a valid bet.</div></span>
  <br> Chance
  <br>
  <input id="userchance" value="50" type="text" name="chance">
  <br>
  <h3>Payout: 0BTC</h3>
  <button type="button" id="dicebutton" onclick="prepareRoll()" style="vertical-align:middle"><img src="Images/dice.png"> Roll dice!</button>
</form></code>```

Body:
EDIT based on comment, full snippet:

This is with absolute position & coordinates on each error button with a separate class, tweak them to your benefit, note that button padding and margin may push them out of container on smaller width viewports. This will preserve your inputs centered, otherwise I can rework your html to make them inline but will push inputs to the left so labels would need to be aligned manually.

/*Smooth font*/

@font-face {
  font-family: 'smooth';
  font-style: normal;
  font-weight: 400;
  src: local('Smooth/RobotoDraft'), local('Smooth/RobotoDraft-Regular'), url(https://fonts.gstatic.com/s/robotodraft/v1/0xES5Sl_v6oyT7dAKuoni4gp9Q8gbYrhqGlRav_IXfk.woff2) format('woff2'), url(https://fonts.gstatic.com/s/robotodraft/v1/0xES5Sl_v6oyT7dAKuoni7rIa-7acMAeDBVuclsi6Gc.woff) format('woff');
}

/*--------[HEADER]-----------*/

body {
  margin: 0;
}

ul.topnav {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
}

ul.topnav li {
  float: left;
}

ul.topnav li a {
  display: block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  font-family: "smooth";
}

ul.topnav li a:hover:not(.active) {
  background-color: #111;
}

ul.topnav li a.active {
  background-color: #4CAF50;
}

ul.topnav li.right {
  float: right;
}

@media screen and (max-width: 600px) {
  ul.topnav li.right,
  ul.topnav li {
    float: none;
  }
}

/*--------[HEADER]-----------*/

/* Paper box */

.paper {
  border: 6px solid white;
  height: auto;
  margin: 20px;
  padding: 20px;
  width: auto;
  background-color: white;
  margin-left: 3%;
  margin-right: 3%;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
  font-family: "smooth";
}

/* Game box */

.gamebox {
  height: auto;
  margin: 20px;
  padding: 20px;
  width: auto;
  font-family: "smooth";
  background-color: slategray;
  color: white;
  text-align: center;
}

/* Error */

.error {
  height: auto;
  margin: 20px;
  padding: 20px;
  width: auto;
  font-family: "smooth";
  background-color: indianred;
  color: white;
  text-align: center;
  display: none;
}

/* Error */

.beterror1 {
  height: auto;
  margin: 20px;
  padding: 20px;
  width: auto;
  font-family: "smooth";
  background-color: indianred;
  color: white;
  display: inline;
  position: absolute;
  right: 7%;
  top: 250px;
}

.beterror2 {
  height: auto;
  margin: 20px;
  padding: 20px;
  width: auto;
  font-family: "smooth";
  background-color: indianred;
  color: white;
  display inline;
  position: absolute;
  right: 7%;
  top: 325px;
}

.gamebox h1,
h3,
p {
  text-align: center;
}

form {
  text-align: center;
}

input[type=text] {
  width: 20%;
  padding: 12px 20px;
  display: block;
  margin: 0 auto;
  box-sizing: border-box;
  border: 1px solid #555;
  outline: none;
}

input[type=text]:focus {
  background-color: lightblue;
}

button {
  background-color: #4CAF50;
  /* Green */
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  margin: 4px 2px;
  cursor: pointer;
}

button:hover {
  background-color: darkgreen;
  /* Green */
  border: none;
  color: gray;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  margin: 4px 2px;
  cursor: pointer;
}

button:focus {
  outline: none;
}

<div class="paper">
  <h2>Play</h2>
  <div class="gamebox">
    <h1><i class="fa fa-btc" aria-hidden="true"></i>itcoin dice game</h1>
    <div class="error" id="error">You don't have anymore bitcoins left. Why not deposit some?</div>
    <h3 id="balance">Balance: 1000BTC</h3>
    <form>
      Bet
      <br>
      <div><input id="userbet" onchange="checkBet()" value="1" type="text" name="bet">
        <div class="beterror1" id="beterror">That is not a valid bet.</div>
      </div>
      <br> Chance
      <br>
      <div><input id="userchance" value="50" type="text" name="chance">
        <div class="beterror2" id="beterror">That is not a good chance.</div>
      </div>
      <br>
      <h3>Payout: 0BTC</h3>
      <button type="button" id="dicebutton" onclick="prepareRoll()" style="vertical-align:middle"><img src="Images/dice.png"> Roll dice!</button>
    </form>
    <button type="button" id="autobet">Autobet</button>
  </div>
</div>

You are putting a div inside a span element which is inline, change that span for a div.

/* Error */

.beterror {
  height: auto;
  margin: 20px;
  padding: 20px;
  width: auto;
  font-family: "smooth";
  background-color: indianred;
  color: white;
  display: inline;
}

<form>
  Bet
  <br>
  <div>
    <input id="userbet" onchange="checkBet()" value="1" type="text" name="bet">
    <div class="beterror" id="beterror">That is not a valid bet.</div>
  </div>
  <br> Chance
  <br>
  <input id="userchance" value="50" type="text" name="chance">
  <br>
  <h3>Payout: 0BTC</h3>
  <button type="button" id="dicebutton" onclick="prepareRoll()" style="vertical-align:middle"><img src="Images/dice.png"> Roll dice!</button>
</form>

Or, as an alternative you set the button to absolute position and tweak its coordinates:

/* Error */

.beterror {
  height: auto;
  margin: 20px;
  padding: 20px;
  width: auto;
  font-family: "smooth";
  background-color: indianred;
  color: white;
  /*display: inline;*/
  /* new stuff */
  position: absolute;
  top: 0px;
  left: 160px;
}

<form>
  Bet
  <br>
  <span><input id="userbet" onchange="checkBet()" value="1" type="text" name="bet"><div class="beterror" id="beterror">That is not a valid bet.</div></span>
  <br> Chance
  <br>
  <input id="userchance" value="50" type="text" name="chance">
  <br>
  <h3>Payout: 0BTC</h3>
  <button type="button" id="dicebutton" onclick="prepareRoll()" style="vertical-align:middle"><img src="Images/dice.png"> Roll dice!</button>
</form>


问:
Laravel 5 - SQLSTATE[HY000][1045] Access denied for user 'root'@'localhost' (using password: NO)
I am trying to make CRUD operations in laravel and I alway have this error message. I already configured the .env and the config/database.php files to my local setting but it doesn't work.

I tried php artisan cache:clear,php artisan config:clear too...

My config/database.php:

```<code>'mysql' => [
    'driver' => 'mysql',
    'host' => env('DB_HOST', 'localhost'),
    'port' => env('DB_PORT', ''),
    'database' => env('DB_DATABASE', 'feki_test'),
    'username' => env('DB_USERNAME', 'root'),
    'password' => env('DB_PASSWORD', ''),
    'unix_socket' => env('DB_SOCKET', ''),
    'charset' => 'utf8mb4',
    'collation' => 'utf8mb4_unicode_ci',
    'prefix' => '',
    'strict' => true,
    'engine' => null,
],
</code>```

My .env:

```<code>DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=
DB_DATABASE=feki_test
DB_USERNAME=root
DB_PASSWORD=
</code>```

答:
First of all, you need not write credentials in config/database.php.
then delete you .env file and then rename your .env.example file to .env
afterward run the PHP artisan key:generate command on your terminal .

give your database credential.

```<code>DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=feki_test
DB_USERNAME=root
DB_PASSWORD=
</code>```

and the last restart your development server.
.

Body:
I am trying to make CRUD operations in laravel and I alway have this error message. I already configured the .env and the config/database.php files to my local setting but it doesn't work.

I tried php artisan cache:clear,php artisan config:clear too...

My config/database.php:

'mysql' => [
    'driver' => 'mysql',
    'host' => env('DB_HOST', 'localhost'),
    'port' => env('DB_PORT', ''),
    'database' => env('DB_DATABASE', 'feki_test'),
    'username' => env('DB_USERNAME', 'root'),
    'password' => env('DB_PASSWORD', ''),
    'unix_socket' => env('DB_SOCKET', ''),
    'charset' => 'utf8mb4',
    'collation' => 'utf8mb4_unicode_ci',
    'prefix' => '',
    'strict' => true,
    'engine' => null,
],

My .env:

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=
DB_DATABASE=feki_test
DB_USERNAME=root
DB_PASSWORD=

Body:
First of all, you need not write credentials in config/database.php.
then delete you .env file and then rename your .env.example file to .env
afterward run the PHP artisan key:generate command on your terminal .

give your database credential.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=feki_test
DB_USERNAME=root
DB_PASSWORD=

and the last restart your development server.
.


问:
Multiple OPTIONAL MATCH with COUNT doesn't seem to work
I have an Item node, which is POSTED_BY a User node.  Additionally, the Item may be LIKED by zero or more User nodes, and zero or more Comments may be POSTED_IN the Item node.

What I need to do is to query for a specific Item node (given the id), and retrieve:

The Item node itself

The User node that the Item was POSTED_BY

The count of the number of Users who LIKE the Item node

The count of the number of Comments POSTED_IN the Item node

If I try to query just 1-3, and exclude 4 for now, my query looks something like this:

```<code>MATCH (i:Item {id: 'ByvIzUdbZ'})-[:POSTED_BY]->(u:User)
OPTIONAL MATCH (u2:User)-[:LIKES]->(i)
RETURN i, u, COUNT(u2);
</code>```

This returns the Item node, the User and the LIKES count correctly.

Now, to accommodate the 4th point, I modified the query to add another OPTIONAL MATCH, as below:

```<code>MATCH (i:Item {id: 'ByvIzUdbZ'})-[:POSTED_BY]->(u:User)
OPTIONAL MATCH (u2:User)-[:LIKES]->(i)
OPTIONAL MATCH (comment:Comment)-[:POSTED_IN]->(i)
RETURN i, u, COUNT(u2), COUNT(comment);
</code>```

With this, however, the counts for both User (u2) and Comment (comment) are incorrect.  They seem to be getting "added up".  So, if the Likes was actually 3, the likes and comment count are both returned as 6.  Any tips on what I'm doing wrong here?  Thanks.

答:
You are seeing the effect of cartesian products.

If the number of rows that would be generated by a MATCH clause on its own would be N, but the number of rows that already exist (say, from previous MATCH clauses) is M, then you end up with M*N rows.

To avoid this multiplicative effect (which also adversely hits performance and memory), you can perform aggregation immediately after the appropriate clauses. For example, in your case:

```<code>MATCH (i:Item {id: 'ByvIzUdbZ'})-[:POSTED_BY]->(u:User)
OPTIONAL MATCH (u2:User)-[:LIKES]->(i)
WITH i, u, COUNT(u2) AS u2_count
OPTIONAL MATCH (comment:Comment)-[:POSTED_IN]->(i)
RETURN i, u, u2_count, COUNT(comment) AS comment_count;
</code>```

Body:
I have an Item node, which is POSTED_BY a User node.  Additionally, the Item may be LIKED by zero or more User nodes, and zero or more Comments may be POSTED_IN the Item node.

What I need to do is to query for a specific Item node (given the id), and retrieve:

The Item node itself

The User node that the Item was POSTED_BY

The count of the number of Users who LIKE the Item node

The count of the number of Comments POSTED_IN the Item node

If I try to query just 1-3, and exclude 4 for now, my query looks something like this:

MATCH (i:Item {id: 'ByvIzUdbZ'})-[:POSTED_BY]->(u:User)
OPTIONAL MATCH (u2:User)-[:LIKES]->(i)
RETURN i, u, COUNT(u2);

This returns the Item node, the User and the LIKES count correctly.

Now, to accommodate the 4th point, I modified the query to add another OPTIONAL MATCH, as below:

MATCH (i:Item {id: 'ByvIzUdbZ'})-[:POSTED_BY]->(u:User)
OPTIONAL MATCH (u2:User)-[:LIKES]->(i)
OPTIONAL MATCH (comment:Comment)-[:POSTED_IN]->(i)
RETURN i, u, COUNT(u2), COUNT(comment);

With this, however, the counts for both User (u2) and Comment (comment) are incorrect.  They seem to be getting "added up".  So, if the Likes was actually 3, the likes and comment count are both returned as 6.  Any tips on what I'm doing wrong here?  Thanks.

Body:
You are seeing the effect of cartesian products.

If the number of rows that would be generated by a MATCH clause on its own would be N, but the number of rows that already exist (say, from previous MATCH clauses) is M, then you end up with M*N rows.

To avoid this multiplicative effect (which also adversely hits performance and memory), you can perform aggregation immediately after the appropriate clauses. For example, in your case:

MATCH (i:Item {id: 'ByvIzUdbZ'})-[:POSTED_BY]->(u:User)
OPTIONAL MATCH (u2:User)-[:LIKES]->(i)
WITH i, u, COUNT(u2) AS u2_count
OPTIONAL MATCH (comment:Comment)-[:POSTED_IN]->(i)
RETURN i, u, u2_count, COUNT(comment) AS comment_count;