问:
JLayeredPane: what's the functional difference between depth and position?
I am working on a Connect Four game for a school Java project. I've got the 'how' of the JLayeredPane, and it is working as expected, but I'm not quite getting the 'why' behind a certain concept.

Here is my understanding:

JLayeredPane is a container, similar to JPanel, that allows you to specify depth and position for each component. Depth is an Integer, with 0 being the bottom layer and n-1 being the top layer, with n being the number of components. Position is an int (yes, one uses the Integer wrapper class and one is just a primitive!) that specifies a component's postion within the layer, with 0 being the topmost layer, -1 being the bottom-most layer, and positive ints in between, the lower the number the higher the position. So, four components in a single layer could be ordered into position 0, 1, 2, -1 from topmost to bottom-most.

My question is, what's the need to have both concepts?

For instance, I have created three JLabels with images: a frontBoard, a backBoard, and a piece. The piece sometimes goes in front of the frontBoard and sometimes goes between the frontBoard and the backBoard. Let's examine the second example.

I can get the same effect through either of these means:

1) I can set the backBoard to layer 0, position 0; the piece to layer 1, position 0; and the frontBoard to layer 2, position 0

```<code> or
</code>```

2) I can set the backBoard to layer 0, position -1; the piece to layer 0, position 1; and the frontBoard to layer 0, position 0

I have tested both of these ways, and I can't find a functional difference between the two methods.

Can anyone shed any light on this mystery for me?

答:
First off, the best thing to do in such a case is have a look at the tutorial, they are usually very informative: http://download.oracle.com/javase/tutorial/uiswing/components/layeredpane.html

Also, the javadoc of the class itself contains quite a good explanation of the way JLayeredPane works.

Since you already implemented your project, you know that you can achieve stacking of components in two different ways: putting each component on its own layer, or by assigning different components that are on the same layer different position values. The effect is the same, but you would use two different properties to achieve it:

"depth" is a property of the layer: they are enumerated so that the layer with depth 0 is furthest the lowest of all. Layers with higher depths cover layers with lower depths.

Since layers can contain more than one component and since components can always overlap, there must be a way to define the z-order of the components within the layer: that is achieved by enumerating the components with a "position" value. If there are n components in the layer and you start counting at 0, then a position must be a value in the range between 0 and n-1.

Now you could argue that since you have the "position" value, you don't need multiple layers at all, since you can position all components along the z-axis simply through their "position" value. That is true and nobody keeps you from doing so.

The rationale for multiple layers can be seen when you realize that there a predefined constants to be used for the "depth" value of the layers:

DEFAULT_LAYER

PALETTE_LAYER

MODAL_LAYER

POPUP_LAYER

DRAG_LAYER

These are are just logical groupings for complex multi-window applications that help you make sure that some stacking constraints are met: imagine you want to create a modal dialog window that appears on top of your main application frame. If you use a single layer, you must keep track of the positions of all visible components yourself and set the position of the dialog to n. Now add in drag and drop animations, popup menus, etc. and this task becomes quite complex.

By using predefined layers this complexity is reduced. If you want to display a modal dialog window, you don't care about the components of the main application window, you just place it on the MODAL_LAYER and you're done: you can be certain that it's displayed on top of all other components.

Luckily, Swing does all this stuff for you already (by using JLayeredPane or subclasses thereof internally), so you can just call setVisible(boolean) or setModal(boolean) on a JDialog and it will turn out the way you expect it to.

Body:
I am working on a Connect Four game for a school Java project. I've got the 'how' of the JLayeredPane, and it is working as expected, but I'm not quite getting the 'why' behind a certain concept.

Here is my understanding:

JLayeredPane is a container, similar to JPanel, that allows you to specify depth and position for each component. Depth is an Integer, with 0 being the bottom layer and n-1 being the top layer, with n being the number of components. Position is an int (yes, one uses the Integer wrapper class and one is just a primitive!) that specifies a component's postion within the layer, with 0 being the topmost layer, -1 being the bottom-most layer, and positive ints in between, the lower the number the higher the position. So, four components in a single layer could be ordered into position 0, 1, 2, -1 from topmost to bottom-most.

My question is, what's the need to have both concepts?

For instance, I have created three JLabels with images: a frontBoard, a backBoard, and a piece. The piece sometimes goes in front of the frontBoard and sometimes goes between the frontBoard and the backBoard. Let's examine the second example.

I can get the same effect through either of these means:

1) I can set the backBoard to layer 0, position 0; the piece to layer 1, position 0; and the frontBoard to layer 2, position 0

 or

2) I can set the backBoard to layer 0, position -1; the piece to layer 0, position 1; and the frontBoard to layer 0, position 0

I have tested both of these ways, and I can't find a functional difference between the two methods.

Can anyone shed any light on this mystery for me?


来源: stackexchange

问:
Uncaught exception 'Doctrine\ORM\ORMException' with message 'The EntityManager is closed
How to pass doctrine entity manager to some class constructor?

For example, i set-up and create entity manager $em in file _someAction.php.
In the same file i instantiate the class, and pass entity manager to the constructor, but em does not work in the class. I am getting

Fatal error: Uncaught exception 'Doctrine\ORM\ORMException' with message 'The EntityManager is closed.'

class dealErrCl

```<code>use Doctrine\ORM\EntityManager;
use someNamespace\LogErr;

class dealErrCl {
 private $em; //entity manager to save error to the entity

public function __construct( \Doctrine\ORM\EntityManager $em ) {
        $this->em = $em;
}

public function flush($errArr) {

    $this->le = new LogErr();

    if( isset($errArr['title']) ) {
        $this->le->setTitle($errArr['title']);
    }
/*...*/

    $this->em->persist($this->le);
    $this->em->flush();
</code>```

}

_someAction.php

```<code>include DbCon.php; // configures doctrine and creates $em. If i use this em in this file, it works, but if i tryt to pass it to some class constructor, it gives Fatal error.

use LogBundle\Components\ErrC\dealErrCl;
$dealErrIn = new dealErrCl($em);
</code>```

If i use this $em in  _someAction.php file, it works, but if i tryt to pass it to some dealErrCl constructor, it gives Fatal error.

答:
It means that there is an error during the flush, which closes the entity manager.

There maybe many possible errors:

1) setting null on non-null field

2) using reserved keywords for field name
http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/basic-mapping.html#quoting-reserved-words

POSTGRE reserved words :
https://www.postgresql.org/docs/7.3/static/sql-keywords-appendix.html

MYSQL reserved words:
https://dev.mysql.com/doc/refman/5.7/en/keywords.html

Thus better always enclose all flush, inside a try-catch block.

ContentLicense: CC BY-SA 3.0

Body:
How to pass doctrine entity manager to some class constructor?

For example, i set-up and create entity manager $em in file _someAction.php.
In the same file i instantiate the class, and pass entity manager to the constructor, but em does not work in the class. I am getting

Fatal error: Uncaught exception 'Doctrine\ORM\ORMException' with message 'The EntityManager is closed.'

class dealErrCl

use Doctrine\ORM\EntityManager;
use someNamespace\LogErr;

class dealErrCl {
 private $em; //entity manager to save error to the entity

public function __construct( \Doctrine\ORM\EntityManager $em ) {
        $this->em = $em;
}

public function flush($errArr) {

    $this->le = new LogErr();

    if( isset($errArr['title']) ) {
        $this->le->setTitle($errArr['title']);
    }
/*...*/

    $this->em->persist($this->le);
    $this->em->flush();

}

_someAction.php

include DbCon.php; // configures doctrine and creates $em. If i use this em in this file, it works, but if i tryt to pass it to some class constructor, it gives Fatal error.

use LogBundle\Components\ErrC\dealErrCl;
$dealErrIn = new dealErrCl($em);

If i use this $em in  _someAction.php file, it works, but if i tryt to pass it to some dealErrCl constructor, it gives Fatal error.


问:
Java println weird output
I'm getting a weird output from running this simple java program.

The output is: 0 4 2 -6

Why does the x++ print 0, it should be printing 4.

```<code>import java.util.*;
import java.io.*;

public class Java1 {

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

        int x = 4;
        int y = -5;

        System.out.println(x++ + " " + func(x++, y) + " " + --y);
    }

    public static int func(int work, int y) {

        int z = work + y;

        work++;

        y++;
        System.out.print(z + " ");
        return z + work + y;

    }
}
</code>```

答:
```<code>System.out.print(z + " ");
</code>```

is executed before

```<code>System.out.println(x++ + " " + func(x++, y) + " " + --y);
</code>```

So the 0 comes from z, not x.

Title: Java println weird output

Body:
I'm getting a weird output from running this simple java program.

The output is: 0 4 2 -6

Why does the x++ print 0, it should be printing 4.

import java.util.*;
import java.io.*;

public class Java1 {

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

        int x = 4;
        int y = -5;

        System.out.println(x++ + " " + func(x++, y) + " " + --y);
    }

    public static int func(int work, int y) {

        int z = work + y;

        work++;

        y++;
        System.out.print(z + " ");
        return z + work + y;

    }
}

Body:
System.out.print(z + " ");

is executed before

System.out.println(x++ + " " + func(x++, y) + " " + --y);

So the 0 comes from z, not x.


问:
When sorting row, how to swap columns along in multidimensional-array?
I have an array[x][y]

```<code>4 2 0 3 1
t o b e o
r n o t t
o b e x x
</code>```

How can i sort only the for row but move the column with the row.
The result have to be

```<code>0 1 2 3 4
b o o e t
o t n t r
e x b x o
</code>```

i tried with

```<code>for (char[] innerArray : grid) {
    Arrays.sort(innerArray);
}
</code>```

but it sorts all rows.

答:
Here is the solution for Your problem. this Algorithme can do exactly what you mention above.

```<code>Integer[][] arr = new Integer[4][4];
        arr[0][0] = 4;
        arr[0][1] = 3;
        arr[0][2] = 1;
        arr[0][3] = 2;

        arr[1][0] = 6;
        arr[1][1] = 4;
        arr[1][2] = 9;
        arr[1][3] = 2;

        arr[2][0] = 9;
        arr[2][1] = 7;
        arr[2][2] = 5;
        arr[2][3] = 4;

        arr[3][0] = 11;
        arr[3][1] = 33;
        arr[3][2] = 6;
        arr[3][3] = 8;

for (int i = 0; i < arr[0].length; i++) {
    for (int j = i+1; j < arr[0].length; j++) {
        if (arr[0][i] > arr[0][j]) {
            for (int k = 0; k < arr.length; k++) {
                int temp = arr[k][i];
                arr[k][i] = arr[k][j];
                arr[k][j] = temp;
            }
        }
    }
 }
</code>```

To print out the Array for testing purpose .

```<code>for (int i = 0; i < arr.length; i++) {
    for (int j = 0; j < arr[0].length; j++) {
        if (arr[i][j] > 9) {
            System.out.print(arr[i][j]+"  ");
        }else{
            System.out.print(arr[i][j]+"   ");
        }
    }
    System.out.println();
}
</code>```

This is an exemple of the above.

before Sorting

```<code>4   3   1   2
6   4   9   2
9   7   5   4
11  33  6   8
</code>```

After Sorting

```<code>1   2   3   4
9   2   4   6
5   4   7   9
6   8   33  11
</code>```

I hope that this solution meet your requirements.

Body:
I have an array[x][y]

4 2 0 3 1
t o b e o
r n o t t
o b e x x

How can i sort only the for row but move the column with the row.
The result have to be

0 1 2 3 4
b o o e t
o t n t r
e x b x o

i tried with

for (char[] innerArray : grid) {
    Arrays.sort(innerArray);
}

but it sorts all rows.

Body:
Here is the solution for Your problem. this Algorithme can do exactly what you mention above.

Integer[][] arr = new Integer[4][4];
        arr[0][0] = 4;
        arr[0][1] = 3;
        arr[0][2] = 1;
        arr[0][3] = 2;

        arr[1][0] = 6;
        arr[1][1] = 4;
        arr[1][2] = 9;
        arr[1][3] = 2;

        arr[2][0] = 9;
        arr[2][1] = 7;
        arr[2][2] = 5;
        arr[2][3] = 4;

        arr[3][0] = 11;
        arr[3][1] = 33;
        arr[3][2] = 6;
        arr[3][3] = 8;

for (int i = 0; i < arr[0].length; i++) {
    for (int j = i+1; j < arr[0].length; j++) {
        if (arr[0][i] > arr[0][j]) {
            for (int k = 0; k < arr.length; k++) {
                int temp = arr[k][i];
                arr[k][i] = arr[k][j];
                arr[k][j] = temp;
            }
        }
    }
 }

To print out the Array for testing purpose .

for (int i = 0; i < arr.length; i++) {
    for (int j = 0; j < arr[0].length; j++) {
        if (arr[i][j] > 9) {
            System.out.print(arr[i][j]+"  ");
        }else{
            System.out.print(arr[i][j]+"   ");
        }
    }
    System.out.println();
}

This is an exemple of the above.

before Sorting

4   3   1   2
6   4   9   2
9   7   5   4
11  33  6   8

After Sorting

1   2   3   4
9   2   4   6
5   4   7   9
6   8   33  11

I hope that this solution meet your requirements.


问:
How can I compare two lists of numpy vectors?
I have two lists of numpy vectors and wish to determine whether they represent approximately the same points (but possibly in a different order).

I've found methods such as numpy.testing.assert_allclose but it doesn't allow for possibly different orders. I have also found unittest.TestCase.assertCountEqual but that doesn't work with numpy arrays!

What is my best approach?

```<code>import unittest

import numpy as np

first = [np.array([20, 40]), np.array([20, 60])]
second = [np.array([19.8, 59.7]), np.array([20.1, 40.5])]

np.testing.assert_all_close(first, second, atol=2)  # Fails because the orders are different
unittest.TestCase.assertCountEqual(None, first, second)  # Fails because numpy comparisons evaluate element-wise; and because it doesn't allow a tolerance
</code>```

答:
Here you are :)

( idea based on
Euclidean distance between points in two different Numpy arrays, not within )

```<code>import numpy as np
import scipy.spatial
first  = [np.array([20  , 60  ]), np.array([  20,   40])]
second = [np.array([19.8, 59.7]), np.array([20.1, 40.5])]

def pointsProximityCheck(firstListOfPoints, secondListOfPoints, distanceTolerance):
    pointIndex  = 0
    maxDistance = 0
    lstIndices  = []
    for item in scipy.spatial.distance.cdist( firstListOfPoints, secondListOfPoints ):
        currMinDist = min(item)
        if currMinDist > maxDistance:
            maxDistance = currMinDist
        if currMinDist < distanceTolerance :
            pass
        else:
            lstIndices.append(pointIndex)
            # print("point with pointIndex [", pointIndex, "] in the first list outside of Tolerance")
        pointIndex+=1
    return (maxDistance, lstIndices)

maxDistance, lstIndicesOfPointsOutOfTolerance = pointsProximityCheck(first, second, distanceTolerance=0.5)
print("maxDistance:", maxDistance, "indicesOfOutOfTolerancePoints", lstIndicesOfPointsOutOfTolerance )
</code>```

gives on output with distanceTolerance=0.5 :

```<code>maxDistance: 0.509901951359 indicesOfOutOfTolerancePoints [1]
</code>```

Body:
I have two lists of numpy vectors and wish to determine whether they represent approximately the same points (but possibly in a different order).

I've found methods such as numpy.testing.assert_allclose but it doesn't allow for possibly different orders. I have also found unittest.TestCase.assertCountEqual but that doesn't work with numpy arrays!

What is my best approach?

import unittest

import numpy as np

first = [np.array([20, 40]), np.array([20, 60])]
second = [np.array([19.8, 59.7]), np.array([20.1, 40.5])]

np.testing.assert_all_close(first, second, atol=2)  # Fails because the orders are different
unittest.TestCase.assertCountEqual(None, first, second)  # Fails because numpy comparisons evaluate element-wise; and because it doesn't allow a tolerance

Body:
Here you are :)

( idea based on
Euclidean distance between points in two different Numpy arrays, not within )

import numpy as np
import scipy.spatial
first  = [np.array([20  , 60  ]), np.array([  20,   40])]
second = [np.array([19.8, 59.7]), np.array([20.1, 40.5])]

def pointsProximityCheck(firstListOfPoints, secondListOfPoints, distanceTolerance):
    pointIndex  = 0
    maxDistance = 0
    lstIndices  = []
    for item in scipy.spatial.distance.cdist( firstListOfPoints, secondListOfPoints ):
        currMinDist = min(item)
        if currMinDist > maxDistance:
            maxDistance = currMinDist
        if currMinDist < distanceTolerance :
            pass
        else:
            lstIndices.append(pointIndex)
            # print("point with pointIndex [", pointIndex, "] in the first list outside of Tolerance")
        pointIndex+=1
    return (maxDistance, lstIndices)

maxDistance, lstIndicesOfPointsOutOfTolerance = pointsProximityCheck(first, second, distanceTolerance=0.5)
print("maxDistance:", maxDistance, "indicesOfOutOfTolerancePoints", lstIndicesOfPointsOutOfTolerance )

gives on output with distanceTolerance=0.5 :

maxDistance: 0.509901951359 indicesOfOutOfTolerancePoints [1]


问:
Overriding id on create in ActiveRecord
Is there any way of overriding a model's id value on create? Something like:

```<code>Post.create(:id => 10, :title => 'Test')
</code>```

would be ideal, but obviously won't work.

答:
Try

```<code>a_post = Post.new do |p|
  p.id = 10
  p.title = 'Test'
  p.save
end
</code>```

that should give you what you're looking for.

OwnerDisplayName: Mr. Matt

ContentLicense: CC BY-SA 2.5

Title: Overriding id on create in ActiveRecord

Body:
Is there any way of overriding a model's id value on create? Something like:

Post.create(:id => 10, :title => 'Test')

would be ideal, but obviously won't work.

Body:
Try

a_post = Post.new do |p|
  p.id = 10
  p.title = 'Test'
  p.save
end

that should give you what you're looking for.

OwnerDisplayName: PJ Davis


问:
__NSAutoreleaseNoPool(): Object 0x753c2f0 of class General autoreleased with no pool in place - just leaking
I haven't noticed my console output for a while and I've suddenly noticed lots of weird errors.

__NSAutoreleaseNoPool(): Object 0x753c2f0 of class General autoreleased with no pool in place - just leaking

__NSAutoreleaseNoPool(): Object 0x753c300 of class __NSArrayM autoreleased with no pool in place - just leaking

I've no idea where this happening?

Edit..

I use this

```<code>[self performSelectorInBackground:@selector(startupStuff) withObject:sender];
</code>```

With statupStuff I have this

```<code>General *rdb = [[General alloc] autorelease];
[rdb refreshDBData];
</code>```

The Errors happen shortly after code in the refreshDBData method.

答:
This:

```<code>General *rdb = [[General alloc] autorelease];
</code>```

Is wrong.  There should always be a call to an initializer;  to -init, at the least.

Body:
I haven't noticed my console output for a while and I've suddenly noticed lots of weird errors.

__NSAutoreleaseNoPool(): Object 0x753c2f0 of class General autoreleased with no pool in place - just leaking

__NSAutoreleaseNoPool(): Object 0x753c300 of class __NSArrayM autoreleased with no pool in place - just leaking

I've no idea where this happening?

Edit..

I use this

[self performSelectorInBackground:@selector(startupStuff) withObject:sender];

With statupStuff I have this

General *rdb = [[General alloc] autorelease];
[rdb refreshDBData];

The Errors happen shortly after code in the refreshDBData method.

Body:
This:

General *rdb = [[General alloc] autorelease];

Is wrong.  There should always be a call to an initializer;  to -init, at the least.


问:
Django Context Processor Login In Issue
I have a login system:

```<code>def login(request):
title = "Login"
if request.user.is_authenticated():
    return HttpResponseRedirect('/')
form = UserLoginForm(request.POST or None)
if request.POST and form.is_valid():
    username = form.cleaned_data.get('username')
    password = form.cleaned_data.get('password')
    user = auth.authenticate(username=username, password=password)
    if user:
        auth.login(request, user)
    return HttpResponseRedirect("/")# Redirect to a success page.
return render(request, 'accounts/login.html', {'title':title, 'form': form })

def logout(request):
    auth.logout(request)
    return HttpResponseRedirect('/accounts/login')
</code>```

and it works fine. However, when I try to add in a context_processor it stops working and gives me the following error:

```<code>Environment:

Request Method: GET
Request URL: http://localhost:8000/accounts/login/

Traceback:

File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner
  39.             response = get_response(request)

File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
  149.                     response = view_func(request, *args, **kwargs)

File "/Users/andyxu/Documents/ece496-web/capstone/views.py" in login
  22.     return render(request, 'accounts/login.html', {'title':title, 'form': form })

File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/shortcuts.py" in render
  30.     content = loader.render_to_string(template_name, context, request, using=using)

File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/loader.py" in render_to_string
  68.     return template.render(context, request)

File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/backends/django.py" in render
  66.             return self.template.render(context)

File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/base.py" in render
  206.                 with context.bind_template(self):

File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/contextlib.py" in __enter__
  17.             return self.gen.next()

File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/context.py" in bind_template
  236.             updates.update(processor(self.request))

Exception Type: TypeError at /accounts/login/
Exception Value: 'NoneType' object is not iterable
</code>```

Here is my context_processor.py:

```<code>from matchalgorithm.models import Profile

def add_variable_to_context(request):
    if(request.user.id):
        profile = Profile.objects.filter(user_id = request.user.id).first()
    return {
        'main_profile': profile
    }
</code>```

Basically I just want to check if the user has a Profile else return None. I want to use this variable to be passed into my base.html which is NOT rendered by any view. Funny thing is, once I am logged in, it works fine!

Thanks

答:
The indentation on your context processor seems to be off, it doesn't match your description. I assume that the return statement is inside the if statement, since it matches both your description and the traceback.

The docs say (emphasis mine):

A context processor has a very simple interface: It’s a Python function that takes one argument, an HttpRequest object, and returns a dictionary that gets added to the template context. Each context processor must return a dictionary.

So if you don't want to add anything to the context, your processor must return an empty dictionary instead of None:

```<code>def add_variable_to_context(request):
    if(request.user.id):
        profile = Profile.objects.filter(user_id = request.user.id).first()
        return {
            'main_profile': profile
        }
    return {}
</code>```

Title: Django Context Processor Login In Issue

Body:
I have a login system:

def login(request):
title = "Login"
if request.user.is_authenticated():
    return HttpResponseRedirect('/')
form = UserLoginForm(request.POST or None)
if request.POST and form.is_valid():
    username = form.cleaned_data.get('username')
    password = form.cleaned_data.get('password')
    user = auth.authenticate(username=username, password=password)
    if user:
        auth.login(request, user)
    return HttpResponseRedirect("/")# Redirect to a success page.
return render(request, 'accounts/login.html', {'title':title, 'form': form })

def logout(request):
    auth.logout(request)
    return HttpResponseRedirect('/accounts/login')

and it works fine. However, when I try to add in a context_processor it stops working and gives me the following error:

Environment:

Request Method: GET
Request URL: http://localhost:8000/accounts/login/

Traceback:

File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner
  39.             response = get_response(request)

File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
  149.                     response = view_func(request, *args, **kwargs)

File "/Users/andyxu/Documents/ece496-web/capstone/views.py" in login
  22.     return render(request, 'accounts/login.html', {'title':title, 'form': form })

File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/shortcuts.py" in render
  30.     content = loader.render_to_string(template_name, context, request, using=using)

File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/loader.py" in render_to_string
  68.     return template.render(context, request)

File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/backends/django.py" in render
  66.             return self.template.render(context)

File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/base.py" in render
  206.                 with context.bind_template(self):

File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/contextlib.py" in __enter__
  17.             return self.gen.next()

File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/context.py" in bind_template
  236.             updates.update(processor(self.request))

Exception Type: TypeError at /accounts/login/
Exception Value: 'NoneType' object is not iterable

Here is my context_processor.py:

from matchalgorithm.models import Profile

def add_variable_to_context(request):
    if(request.user.id):
        profile = Profile.objects.filter(user_id = request.user.id).first()
    return {
        'main_profile': profile
    }

Basically I just want to check if the user has a Profile else return None. I want to use this variable to be passed into my base.html which is NOT rendered by any view. Funny thing is, once I am logged in, it works fine!

Thanks

Body:
The indentation on your context processor seems to be off, it doesn't match your description. I assume that the return statement is inside the if statement, since it matches both your description and the traceback.

The docs say (emphasis mine):

A context processor has a very simple interface: It’s a Python function that takes one argument, an HttpRequest object, and returns a dictionary that gets added to the template context. Each context processor must return a dictionary.

So if you don't want to add anything to the context, your processor must return an empty dictionary instead of None:

def add_variable_to_context(request):
    if(request.user.id):
        profile = Profile.objects.filter(user_id = request.user.id).first()
        return {
            'main_profile': profile
        }
    return {}


问:
Using JavaScript Variables in HTML code
I'm pretty new to JavaScript.

I'm trying to make a YouTube 2.0 html thing, (interesting learning experience). I want it to be so that you click on the "load video" link and it asks you the link to the actual youtube video. Then, when you paste it in, it displays the video on the page.

My code is

Youtube 2.0

Load video

```

If you have any ideas on how I can insert the JavaScript variable into my iframe src tag, please tell me. Thanks!

答:
You must use embed link instead of full link

like: https://www.youtube.com/embed/videoID

 var openVideo = function() {
  var videoID = prompt("Video id on YouTube.com");
    var embed = 'https://www.youtube.com/embed/'
  document.getElementById("myFrame").src=embed+videoID;
 };
 ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1 style="background-color: red; color: white; font-family: helvetica; padding: 20px 20px 20px 20px;">Youtube 2.0</h1>
Load video

<iframe id=myFrame width="1120" height="630" src=# frameborder="0" allowfullscreen></iframe></code>```

Title: Using JavaScript Variables in HTML code

Body:
I'm pretty new to JavaScript.

I'm trying to make a YouTube 2.0 html thing, (interesting learning experience). I want it to be so that you click on the "load video" link and it asks you the link to the actual youtube video. Then, when you paste it in, it displays the video on the page.

My code is

Youtube 2.0

Load video

If you have any ideas on how I can insert the JavaScript variable into my iframe src tag, please tell me. Thanks!

Body:
You must use embed link instead of full link

like: https://www.youtube.com/embed/videoID

 var openVideo = function() {
  var videoID = prompt("Video id on YouTube.com");
    var embed = 'https://www.youtube.com/embed/'
  document.getElementById("myFrame").src=embed+videoID;
 };

<h1 style="background-color: red; color: white; font-family: helvetica; padding: 20px 20px 20px 20px;">Youtube 2.0</h1>
<a href="#" onclick="openVideo()">Load video</a>

<iframe id=myFrame width="1120" height="630" src=# frameborder="0" allowfullscreen></iframe>


问:
os.popen() variables
So i have this application thats rather complicated...
To keep it short this is the main things you should know:

```<code>file_name = raw_input("Name your file:").lower()

os.popen(sudo tcpdump -c5 -vvv -w "file_name" host wiki or host wiki2)
</code>```

but this doesn't seem to work. Can i get a fix?
Thanks,
Pastelinux

edit1:
Alright this is what i have now, but its not working, any pointers on how to fix?

import subprocess, os, sys

filename = raw_input('File name:').lower

pipe = os.popen("sudo tcpdump -c5 -w", 'filename')

pipe = popen("sudo tcpdump -c5 -w", shell=True, stdout=PIPE).stdout

答:
If you are running newer versions of Python, then use subprocess module.

See the replacement details of os.popen at :

http://docs.python.org/library/subprocess.html#replacing-os-popen-os-popen2-os-popen3

It says: On Unix, os.popen2, os.popen3 and os.popen4 also accept a sequence as the command to execute, in which case arguments will be passed directly to the program without shell intervention.

```<code>pipe = os.popen("cmd", 'r', bufsize)
==>
pipe = Popen("cmd", shell=True, bufsize=bufsize, stdout=PIPE).stdout
</code>```

Title: os.popen() variables

Body:
So i have this application thats rather complicated...
To keep it short this is the main things you should know:

file_name = raw_input("Name your file:").lower()

os.popen(sudo tcpdump -c5 -vvv -w "file_name" host wiki or host wiki2)

but this doesn't seem to work. Can i get a fix?
Thanks,
Pastelinux

edit1:
Alright this is what i have now, but its not working, any pointers on how to fix?

import subprocess, os, sys

filename = raw_input('File name:').lower

pipe = os.popen("sudo tcpdump -c5 -w", 'filename')

pipe = popen("sudo tcpdump -c5 -w", shell=True, stdout=PIPE).stdout

Body:
If you are running newer versions of Python, then use subprocess module.

See the replacement details of os.popen at :

http://docs.python.org/library/subprocess.html#replacing-os-popen-os-popen2-os-popen3

It says: On Unix, os.popen2, os.popen3 and os.popen4 also accept a sequence as the command to execute, in which case arguments will be passed directly to the program without shell intervention.

pipe = os.popen("cmd", 'r', bufsize)
==>
pipe = Popen("cmd", shell=True, bufsize=bufsize, stdout=PIPE).stdout


问:
Dynamic angular.js orderby button ng-click
Here is the code:

```<code><button ng-init="propriety: 'name'" ng-click="propriety == 'name' ? propriety = 'price' : propriety = 'name'"></button>
<div ng-repeat="item in items | orderBy: propriety">
  <li>item.name - item.price</li>
</div>
</code>```

What am i missing?

Edit 1:
Changed to ng-click, still not working.

Edit 2:
Added ng-init.

Edit 3:
Fixed missing double quotation mark. Still not working.

答:
try that</p>

```<code>ng-init="propriety = 'name'"
ng-click="propriety = propriety == 'name' ? 'price' : 'name'"
</code>```

Body:
Here is the code:

<button ng-init="propriety: 'name'" ng-click="propriety == 'name' ? propriety = 'price' : propriety = 'name'"></button>

item.name - item.price

What am i missing?

Edit 1:
Changed to ng-click, still not working.

Edit 2:
Added ng-init.

Edit 3:
Fixed missing double quotation mark. Still not working.

Body:
try that

ng-init="propriety = 'name'"
ng-click="propriety = propriety == 'name' ? 'price' : 'name'"


答:
I have mentioned the flow of points from 0 to 7 in the comments</p>

```<code>    public static void main(String[] args) throws IOException {

        int x = 4;
        int y = -5;

        System.out.println(x++ + " " + func(x++, y) + " " + --y);
        // thus 0]4  6]2 (value returned as z) 7] localvalue of --y as -6
    }

    //1] x++ makes x as 5 when it is passed to func()
    public static int func(int work, int y) {

        int z = work + y;
        //2] z = 5 + -5 = 0
        work++;
        //3] work which was x as 5 is now 6
        y++;
        //4] y will be -4 now
        System.out.print(z + " ");
        return z + work + y;
        //5] z = 0 + 6 + -4 = 2 and is returned to func() caller
    }
</code>```

Title: Java println weird output

Body:
I'm getting a weird output from running this simple java program.

The output is: 0 4 2 -6

Why does the x++ print 0, it should be printing 4.

import java.util.*;
import java.io.*;

public class Java1 {

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

        int x = 4;
        int y = -5;

        System.out.println(x++ + " " + func(x++, y) + " " + --y);
    }

    public static int func(int work, int y) {

        int z = work + y;

        work++;

        y++;
        System.out.print(z + " ");
        return z + work + y;

    }
}

Body:
I have mentioned the flow of points from 0 to 7 in the comments

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

        int x = 4;
        int y = -5;

        System.out.println(x++ + " " + func(x++, y) + " " + --y);
        // thus 0]4  6]2 (value returned as z) 7] localvalue of --y as -6
    }

    //1] x++ makes x as 5 when it is passed to func()
    public static int func(int work, int y) {

        int z = work + y;
        //2] z = 5 + -5 = 0
        work++;
        //3] work which was x as 5 is now 6
        y++;
        //4] y will be -4 now
        System.out.print(z + " ");
        return z + work + y;
        //5] z = 0 + 6 + -4 = 2 and is returned to func() caller
    }


问:
Setting Activities' Background Color
I am trying to change all of my activities' background color from white to black. I have tried everything - changing windowBackground, colorBackground, background but nothing seems to be working and I know my style is working because if I changed primary, accent colors they seem to be changing. The background tag only changes the action bar's color. Here's my code for the theme (what I have so far) -

```<code><style name="Yoyo" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent1</item>
    <item name="android:windowBackground">@color/darkBackground</item>
    <item name="android:colorBackground">@color/darkBackground</item>
    <item name="android:textColor">#ffffff</item>
</style>
</code>```

darkBackground is black - what I need for my app to show but its not showing.

Also, I have already tried using @drawable/my_drawable_file (in which I set black color) in windowBackground but even that doesn't work.

min sdk version - 21, target sdk version - 25

答:
Try:

```<code><color name="custom_theme_color">#000000</color>
<style name="CustomTheme"Parent="android:Theme.AppCompat.Light.DarkActionBar">
    <item name="android:windowBackground">@color/custom_theme_color</item>
    <item name="android:colorBackground">@color/custom_theme_color</item>
</style>
</code>```

and then use the custom theme in your manifest

Title: Setting Activities' Background Color

Body:
I am trying to change all of my activities' background color from white to black. I have tried everything - changing windowBackground, colorBackground, background but nothing seems to be working and I know my style is working because if I changed primary, accent colors they seem to be changing. The background tag only changes the action bar's color. Here's my code for the theme (what I have so far) -

darkBackground is black - what I need for my app to show but its not showing.

Also, I have already tried using @drawable/my_drawable_file (in which I set black color) in windowBackground but even that doesn't work.

min sdk version - 21, target sdk version - 25

Body:
Try:

<color name="custom_theme_color">#000000</color>
<style name="CustomTheme"Parent="android:Theme.AppCompat.Light.DarkActionBar">
    <item name="android:windowBackground">@color/custom_theme_color</item>
    <item name="android:colorBackground">@color/custom_theme_color</item>
</style>

and then use the custom theme in your manifest


问:
Docker and Neo4J
I'm trying to get a Neo4J database up and running in a docker container.
Currently i have it running by using the command:

```<code>docker run -d -p 7474:7474 -p 7687:7687 neo4j
</code>```

.. and it's working fine.

I want to put it in a Dockerfile so i can do some server configuration, but when i use the Dockerfile, it does not expose the ports that i have set it to expose unless i explicitly expose them when i do "docker run":

```<code>FROM neo4j
ENV NEO4J_AUTH neo4j/password
EXPOSE 7474:7474
EXPOSE 7687:7687
</code>```

Did i misunderstand something, or shouldn't the ports be exposed automatically with this configuration?

答:
The EXPOSE instruction informs Docker that the container listens on
  the specified network ports at runtime. EXPOSE does not make the ports
  of the container accessible to the host. To do that, you must use
  either the -p flag to publish a range of ports or the -P flag to
  publish all of the exposed ports. You can expose one port number and
  publish it externally under another number.

To set up port redirection on the host system, see using the -P flag.
  The Docker network feature supports creating networks without the need
  to expose ports within the network, for detailed information see the
  overview of this feature).

https://docs.docker.com/engine/reference/builder/

Title: Docker and Neo4J

Body:
I'm trying to get a Neo4J database up and running in a docker container.
Currently i have it running by using the command:

docker run -d -p 7474:7474 -p 7687:7687 neo4j

.. and it's working fine.

I want to put it in a Dockerfile so i can do some server configuration, but when i use the Dockerfile, it does not expose the ports that i have set it to expose unless i explicitly expose them when i do "docker run":

FROM neo4j
ENV NEO4J_AUTH neo4j/password
EXPOSE 7474:7474
EXPOSE 7687:7687

Did i misunderstand something, or shouldn't the ports be exposed automatically with this configuration?


问:
Can't access object literal property using getter in ES6 module
I was looking for a way to self-reference an object to access it's property when I discover the ES5 getter feature (see. MDN).

I'm working with NPM module and can't access the canvas property.

config.js

```<code>import path from "path";
import layout from "./layouts";

const config = {
  canvas: { width: 80, height: 80 },
  layout: {
    get base() {
      console.log(this);
      console.log(this.canvas);
      return layout.base.bottom(this.canvas);
    },
    get annotation() {
      return layout.annotation.top(this.canvas);
    }
  }
};
export default config;
</code>```

layouts.js

```<code>export default {
  annotation: {
    top: options => ({
      x: options.width / 2,
    })
  },
  base: {
    bottom: options => ({
      x: options.width / 2,
    })
  }
};
</code>```

Error

```<code>{ base: [Getter], annotation: [Getter] }
undefined
TypeError: Cannot read property 'width' of undefined
    at Object.bottom (/data/projects/hanzi-pinyin-font/src/layouts.js:13:10)
    at Object.get base [as base] (/data/projects/hanzi-pinyin-font/src/config.js:17:26)
    at generateSvg (/data/projects/hanzi-pinyin-font/index.js:15:40)
    at /data/projects/hanzi-pinyin-font/index.js:39:5
    at /data/projects/hanzi-pinyin-font/node_modules/jsonfile/index.js:46:5
</code>```

Question

Why isn't this working?

答:
You have nested object literals.  The inner layout object literal does not know it has a parent so this in your getters for layout refers to config.layout.

You could use object shorthand syntax to make this better.

```<code>import path from "path";
import layouts from "./layouts";

const canvas = {
  canvas: { width: 80, height: 80 }
}

const layout = {
  get base() {
    return layouts.base.bottom(canvas);
  },
  get annotation() {
    return layouts.annotation.top(canvas);
  }
}

export default {
  canvas, layout
};
</code>```

Body:
I was looking for a way to self-reference an object to access it's property when I discover the ES5 getter feature (see. MDN).

I'm working with NPM module and can't access the canvas property.

config.js

import path from "path";
import layout from "./layouts";

const config = {
  canvas: { width: 80, height: 80 },
  layout: {
    get base() {
      console.log(this);
      console.log(this.canvas);
      return layout.base.bottom(this.canvas);
    },
    get annotation() {
      return layout.annotation.top(this.canvas);
    }
  }
};
export default config;

layouts.js

export default {
  annotation: {
    top: options => ({
      x: options.width / 2,
    })
  },
  base: {
    bottom: options => ({
      x: options.width / 2,
    })
  }
};

Error

{ base: [Getter], annotation: [Getter] }
undefined
TypeError: Cannot read property 'width' of undefined
    at Object.bottom (/data/projects/hanzi-pinyin-font/src/layouts.js:13:10)
    at Object.get base [as base] (/data/projects/hanzi-pinyin-font/src/config.js:17:26)
    at generateSvg (/data/projects/hanzi-pinyin-font/index.js:15:40)
    at /data/projects/hanzi-pinyin-font/index.js:39:5
    at /data/projects/hanzi-pinyin-font/node_modules/jsonfile/index.js:46:5

Question

Why isn't this working?

Body:
You have nested object literals.  The inner layout object literal does not know it has a parent so this in your getters for layout refers to config.layout.

You could use object shorthand syntax to make this better.

import path from "path";
import layouts from "./layouts";

const canvas = {
  canvas: { width: 80, height: 80 }
}

const layout = {
  get base() {
    return layouts.base.bottom(canvas);
  },
  get annotation() {
    return layouts.annotation.top(canvas);
  }
}

export default {
  canvas, layout
};


问:
Tkinter, How to make an array entry widget?
I want to add an entry widget in my tkinter window but i don't want a string var but an array with this shape: ([1,1,1],[1,1,1],[1,1,1]). Because I want to multiply the return value with an array.
How can I do this ?
Thank you</p>

```<code>value=([1,1,1],[1,1,1],[1,1,1])
entree = Entry(Mafenetre, textvariable=value, width=30)
entree.pack()
b = Button(Mafenetre, text="OK", command=ok)
b.pack()
def ok():
   v=entree.get()
   newarray=array*v
</code>```

答: You cannot do what you want. You can only enter strings in the entry widget. You will have to write code to convert the string to an array.</p>

Body:
I want to add an entry widget in my tkinter window but i don't want a string var but an array with this shape: ([1,1,1],[1,1,1],[1,1,1]). Because I want to multiply the return value with an array.
How can I do this ?
Thank you

value=([1,1,1],[1,1,1],[1,1,1])
entree = Entry(Mafenetre, textvariable=value, width=30)
entree.pack()
b = Button(Mafenetre, text="OK", command=ok)
b.pack()
def ok():
   v=entree.get()
   newarray=array*v


问:
Perfectly safe static/runtime numeric casts
I'm looking for a C++ feature/code, which I feel is very basic and demanded for generic programming: an ability to tell if some value of given numeric type (integer or float) is exactly representable by another given numeric type.

Long story short, I have a number of template classes, which operate on arbitrary numeric types and they have to interoperate properly. For instance, a memory stream may work with 32bit size type, but file stream has 64bit size type and passing data between them may result in overflow. Another example is geometry classes, one parametrized to work with 64bit floats, another parametrized to work with 64bit integers: passing data between them may result both in rounding errors (integer can't represent fractions) and overflow (integer has bigger value range than same-sized float).

So I wonder if should do my own implementation, or a solution is readily available (unfortunately, I can't use heavyweight libraries like Boost)?

Update: while typing my question, I decided to roll out my own implementation:

```<code>#include <limits>
#include <array>

enum class NumberClass {
    UNKNOWN, INTEGER, FLOAT
};

template <typename T> struct NumberClassResolver {
    static const NumberClass value = std::numeric_limits<T>::is_integer ? NumberClass::INTEGER : (std::numeric_limits<T>::is_iec559 ? NumberClass::FLOAT : NumberClass::UNKNOWN);
};

template <typename From, typename To> struct StaticIntegerCastCheck {
    static const bool value = std::is_same<From, To>::value || (sizeof(From) < sizeof(To)) || ((std::numeric_limits<From>::is_signed == std::numeric_limits<To>::is_signed) && (sizeof(From) <= sizeof(To)));
};
template <typename From, typename To> struct StaticFloatCastCheck {
    static const bool value = std::is_same<From, To>::value || (sizeof(From) < sizeof(To)); // NOTE Here we rely on the fact, that floats are IEEE-754 compliant and bigger ones has both bigger significand and exponent
};

template <NumberClass FromClass, NumberClass ToClass, typename From, typename To> struct StaticNumberCastCheckHelper;
template <typename From, typename To> struct StaticNumberCastCheckHelper<NumberClass::INTEGER, NumberClass::INTEGER, From, To> {
    static const bool value = StaticIntegerCastCheck<From, To>::value;
};
template <typename From, typename To> struct StaticNumberCastCheckHelper<NumberClass::INTEGER, NumberClass::FLOAT, From, To> {
    static const bool value = sizeof(To) > sizeof(From); // NOTE Here we rely on assumption, that sizes are POTs and significand part of a float never takes up less that half of it's size
};
template <typename From, typename To> struct StaticNumberCastCheckHelper<NumberClass::FLOAT, NumberClass::INTEGER, From, To> {
    static const bool value = false;
};
template <typename From, typename To> struct StaticNumberCastCheckHelper<NumberClass::FLOAT, NumberClass::FLOAT, From, To> {
    static const bool value = StaticFloatCastCheck<From, To>::value;
};

template <typename From, typename To> struct StaticNumberCastCheck {
    static const bool value = StaticNumberCastCheckHelper<NumberClassResolver<From>::value, NumberClassResolver<To>::value, From, To>::value;
};

template <bool isFromSigned, bool isToSigned, typename From, typename To> struct RuntimeIntegerCastCheckHelper {
    static bool check(From value) {
        return (value >= std::numeric_limits<To>::min()) && (value <= std::numeric_limits<To>::max()); // NOTE Compiler must eliminate comparisson to zero for unsigned types
    }
};

template <bool isStaticallySafeCastable, NumberClass FromClass, NumberClass ToClass, typename From, typename To> struct RuntimeNumberCastCheckHelper {
    static bool check(From value) {
        return false;
    }
};
template <NumberClass FromClass, NumberClass ToClass, typename From, typename To> struct RuntimeNumberCastCheckHelper<true, FromClass, ToClass, From, To> {
    static bool check(From value) {
        return true;
    }
};
template <typename From, typename To> struct RuntimeNumberCastCheckHelper<false, NumberClass::INTEGER, NumberClass::INTEGER, From, To> {
    static bool check(From value) {
        return RuntimeIntegerCastCheckHelper<std::numeric_limits<From>::is_signed, std::numeric_limits<To>::is_signed, From, To>::check(value);
    }
};
template <typename From, typename To> struct RuntimeNumberCastCheckHelper<false, NumberClass::FLOAT, NumberClass::FLOAT, From, To> {
    static bool check(From value) {
        To toValue = static_cast<To>(value);
        From fromValue = static_cast<From>(toValue);
        return value == fromValue;
    }
};
template <typename From, typename To> struct RuntimeNumberCastCheckHelper<false, NumberClass::INTEGER, NumberClass::FLOAT, From, To> {
    static bool check(From value) {
        To toValue = static_cast<To>(value);
        From fromValue = static_cast<From>(toValue);
        return value == fromValue;
    }
};
template <typename From, typename To> struct RuntimeNumberCastCheckHelper<false, NumberClass::FLOAT, NumberClass::INTEGER, From, To> {
    static bool check(From value) {
        To toValue = static_cast<To>(value);
        From fromValue = static_cast<From>(toValue);
        return value == fromValue;
    }
};

template <typename From, typename To> struct RuntimeNumberCastCheck {
    static bool check(From value) {
        return RuntimeNumberCastCheckHelper<StaticNumberCastCheck<From, To>::value, NumberClassResolver<From>::value, NumberClassResolver<To>::value, From, To>::check(value);
    }
};
</code>```

Intended usage:

```<code>StaticNumberCastCheck<uint8_t, float>::value; // can we safely cast all 8-bit unsigned integers to float?
RuntimeNumberCastCheck<float, uint8_t>::check(42); // can we safely cast 42 from float to 8-bit unsigned integer?
</code>```

It's based on some broad assumptions, so I also would be glad to hear if I'm missing something here (false positives, optimizations, etc).

答:
```<code>template<class From, class To>
using safe_convert_result_t = decltype(To{std::declval<From>()});

namespace details {
  template<class...>struct voider{using type=void;};
  template<class...Ts>using void_t=typename voider<Ts...>::type;

  template<template<class...>class Z, class, class...Ts>
  struct can_apply:std::false_type{};
  template<template<class...>class Z, class...Ts>
  struct can_apply<Z, void_t<Z<Ts...>>, Ts...>:std::true_type{};
}
template<template<class...>class Z, class...Ts>
using can_apply = details::can_apply<Z, void, Ts...>;

template<class From, class To>
using can_safely_convert = can_apply< safe_convert_result_t, From, To >;
</code>```

Then can_safely_convert should be true if and only if there is no narrowing conversion going from From to To.

This uses the C++ standard definition of narrowing conversion.

The trick is that C++ forbids {} based initialization to be a narrowing conversion.  We use SFINAE to detect if such conversion is legal, and return a truthy type if it is.

Live example.

The standard definition of a narrowing conversion may or may not exactly match what you want.  But it is a good place to start.

Body:
I'm looking for a C++ feature/code, which I feel is very basic and demanded for generic programming: an ability to tell if some value of given numeric type (integer or float) is exactly representable by another given numeric type.

Long story short, I have a number of template classes, which operate on arbitrary numeric types and they have to interoperate properly. For instance, a memory stream may work with 32bit size type, but file stream has 64bit size type and passing data between them may result in overflow. Another example is geometry classes, one parametrized to work with 64bit floats, another parametrized to work with 64bit integers: passing data between them may result both in rounding errors (integer can't represent fractions) and overflow (integer has bigger value range than same-sized float).

So I wonder if should do my own implementation, or a solution is readily available (unfortunately, I can't use heavyweight libraries like Boost)?

Update: while typing my question, I decided to roll out my own implementation:

#include <limits>
#include <array>

enum class NumberClass {
    UNKNOWN, INTEGER, FLOAT
};

template <typename T> struct NumberClassResolver {
    static const NumberClass value = std::numeric_limits<T>::is_integer ? NumberClass::INTEGER : (std::numeric_limits<T>::is_iec559 ? NumberClass::FLOAT : NumberClass::UNKNOWN);
};

template <typename From, typename To> struct StaticIntegerCastCheck {
    static const bool value = std::is_same<From, To>::value || (sizeof(From) < sizeof(To)) || ((std::numeric_limits<From>::is_signed == std::numeric_limits<To>::is_signed) && (sizeof(From) <= sizeof(To)));
};
template <typename From, typename To> struct StaticFloatCastCheck {
    static const bool value = std::is_same<From, To>::value || (sizeof(From) < sizeof(To)); // NOTE Here we rely on the fact, that floats are IEEE-754 compliant and bigger ones has both bigger significand and exponent
};

template <NumberClass FromClass, NumberClass ToClass, typename From, typename To> struct StaticNumberCastCheckHelper;
template <typename From, typename To> struct StaticNumberCastCheckHelper<NumberClass::INTEGER, NumberClass::INTEGER, From, To> {
    static const bool value = StaticIntegerCastCheck<From, To>::value;
};
template <typename From, typename To> struct StaticNumberCastCheckHelper<NumberClass::INTEGER, NumberClass::FLOAT, From, To> {
    static const bool value = sizeof(To) > sizeof(From); // NOTE Here we rely on assumption, that sizes are POTs and significand part of a float never takes up less that half of it's size
};
template <typename From, typename To> struct StaticNumberCastCheckHelper<NumberClass::FLOAT, NumberClass::INTEGER, From, To> {
    static const bool value = false;
};
template <typename From, typename To> struct StaticNumberCastCheckHelper<NumberClass::FLOAT, NumberClass::FLOAT, From, To> {
    static const bool value = StaticFloatCastCheck<From, To>::value;
};

template <typename From, typename To> struct StaticNumberCastCheck {
    static const bool value = StaticNumberCastCheckHelper<NumberClassResolver<From>::value, NumberClassResolver<To>::value, From, To>::value;
};

template <bool isFromSigned, bool isToSigned, typename From, typename To> struct RuntimeIntegerCastCheckHelper {
    static bool check(From value) {
        return (value >= std::numeric_limits<To>::min()) && (value <= std::numeric_limits<To>::max()); // NOTE Compiler must eliminate comparisson to zero for unsigned types
    }
};

template <bool isStaticallySafeCastable, NumberClass FromClass, NumberClass ToClass, typename From, typename To> struct RuntimeNumberCastCheckHelper {
    static bool check(From value) {
        return false;
    }
};
template <NumberClass FromClass, NumberClass ToClass, typename From, typename To> struct RuntimeNumberCastCheckHelper<true, FromClass, ToClass, From, To> {
    static bool check(From value) {
        return true;
    }
};
template <typename From, typename To> struct RuntimeNumberCastCheckHelper<false, NumberClass::INTEGER, NumberClass::INTEGER, From, To> {
    static bool check(From value) {
        return RuntimeIntegerCastCheckHelper<std::numeric_limits<From>::is_signed, std::numeric_limits<To>::is_signed, From, To>::check(value);
    }
};
template <typename From, typename To> struct RuntimeNumberCastCheckHelper<false, NumberClass::FLOAT, NumberClass::FLOAT, From, To> {
    static bool check(From value) {
        To toValue = static_cast<To>(value);
        From fromValue = static_cast<From>(toValue);
        return value == fromValue;
    }
};
template <typename From, typename To> struct RuntimeNumberCastCheckHelper<false, NumberClass::INTEGER, NumberClass::FLOAT, From, To> {
    static bool check(From value) {
        To toValue = static_cast<To>(value);
        From fromValue = static_cast<From>(toValue);
        return value == fromValue;
    }
};
template <typename From, typename To> struct RuntimeNumberCastCheckHelper<false, NumberClass::FLOAT, NumberClass::INTEGER, From, To> {
    static bool check(From value) {
        To toValue = static_cast<To>(value);
        From fromValue = static_cast<From>(toValue);
        return value == fromValue;
    }
};

template <typename From, typename To> struct RuntimeNumberCastCheck {
    static bool check(From value) {
        return RuntimeNumberCastCheckHelper<StaticNumberCastCheck<From, To>::value, NumberClassResolver<From>::value, NumberClassResolver<To>::value, From, To>::check(value);
    }
};

Intended usage:

StaticNumberCastCheck<uint8_t, float>::value; // can we safely cast all 8-bit unsigned integers to float?
RuntimeNumberCastCheck<float, uint8_t>::check(42); // can we safely cast 42 from float to 8-bit unsigned integer?

It's based on some broad assumptions, so I also would be glad to hear if I'm missing something here (false positives, optimizations, etc).

Body:
template<class From, class To>
using safe_convert_result_t = decltype(To{std::declval<From>()});

namespace details {
  template<class...>struct voider{using type=void;};
  template<class...Ts>using void_t=typename voider<Ts...>::type;

  template<template<class...>class Z, class, class...Ts>
  struct can_apply:std::false_type{};
  template<template<class...>class Z, class...Ts>
  struct can_apply<Z, void_t<Z<Ts...>>, Ts...>:std::true_type{};
}
template<template<class...>class Z, class...Ts>
using can_apply = details::can_apply<Z, void, Ts...>;

template<class From, class To>
using can_safely_convert = can_apply< safe_convert_result_t, From, To >;

Then can_safely_convert should be true if and only if there is no narrowing conversion going from From to To.

This uses the C++ standard definition of narrowing conversion.

The trick is that C++ forbids {} based initialization to be a narrowing conversion.  We use SFINAE to detect if such conversion is legal, and return a truthy type if it is.

Live example.

The standard definition of a narrowing conversion may or may not exactly match what you want.  But it is a good place to start.


问:
iOS: Cast result of coredata fetch to array and passing to another class
in my class I have a method to extract data from coredata. But I have a problem: I need to convert the result to an array, because then I'll have to use that array in an other class.

The method is:

```<code>    func loadQuestion() -> NSArray{
        let fetchRequest: NSFetchRequest<Questions> = Questions.fetchRequest()

        do {
            let array = try self.context.fetch(fetchRequest) as NSArray
            guard array.count > 0 else { print("[EHY!] Non ci sono elementi da leggere "); return array }

            return array
        } catch let errore {
            print("error FetchRequest")
        }

        return list
    }
</code>```

I can't figure out how to convert the variable array?

The result (wrong)

Edit: I write this because I want to convert the result of fetch into
  an array, so you can switch to another class

答:
fetch returns an (optional) array, so all you need to do is return that from your function.  Since fetch throws your function should either throw or at least return an optional, as the fetch can fail.

In Swift it is very rarely necessary to use NSArray; a properly typed Swift array will make your code clearer and safer. Since CoreData in Swift supports Generics, fetch will return the appropriate array type automatically, based on your NSFetchRequest.  Even if you are calling this function from Objective-C, it is best to let the compiler bridge the Swift array to an NSArray for you

Finally, you are using guard incorrectly; you attempt to return array in the case where it has 0 items,  otherwise you return some variable list which isn't declared in the code you have shown.

```<code>func loadQuestion() -> [Questions]? {
    let fetchRequest: NSFetchRequest<Questions> = Questions.fetchRequest()

    do {
        let array = try self.context.fetch(fetchRequest) as [Questions]
        return array
    } catch let errore {
        print("error FetchRequest \(errore)")
    }

    return nil
}
</code>```

Body:
in my class I have a method to extract data from coredata. But I have a problem: I need to convert the result to an array, because then I'll have to use that array in an other class.

The method is:

    func loadQuestion() -> NSArray{
        let fetchRequest: NSFetchRequest<Questions> = Questions.fetchRequest()

        do {
            let array = try self.context.fetch(fetchRequest) as NSArray
            guard array.count > 0 else { print("[EHY!] Non ci sono elementi da leggere "); return array }

            return array
        } catch let errore {
            print("error FetchRequest")
        }

        return list
    }

I can't figure out how to convert the variable array?

The result (wrong)

Edit: I write this because I want to convert the result of fetch into
  an array, so you can switch to another class

Body:
fetch returns an (optional) array, so all you need to do is return that from your function.  Since fetch throws your function should either throw or at least return an optional, as the fetch can fail.

In Swift it is very rarely necessary to use NSArray; a properly typed Swift array will make your code clearer and safer. Since CoreData in Swift supports Generics, fetch will return the appropriate array type automatically, based on your NSFetchRequest.  Even if you are calling this function from Objective-C, it is best to let the compiler bridge the Swift array to an NSArray for you

Finally, you are using guard incorrectly; you attempt to return array in the case where it has 0 items,  otherwise you return some variable list which isn't declared in the code you have shown.

func loadQuestion() -> [Questions]? {
    let fetchRequest: NSFetchRequest<Questions> = Questions.fetchRequest()

    do {
        let array = try self.context.fetch(fetchRequest) as [Questions]
        return array
    } catch let errore {
        print("error FetchRequest \(errore)")
    }

    return nil
}


问:
How to print number in triangle pattern using java
I am trying to print a number pattern like below

The condition is when user will enter 6 then only first three rows should display and if user enters 3 then only first two rows should display.

```<code>class Star
{
    public static void main(String[] args)
    {
        int i,  j;
        for(i=1; i<=6; i++)
        {
            for(j=1; j<i; j++)
            {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}
</code>```

```1
3  2
6  5  4
10  9   8  7
```

thanks in advance :)

答:
I have created something like this:

```<code>/**
 * Created by maciej.brzozowski.83@gmail.com on 2017-04-02.
 */
class Star
{
    public static void main(String[] args)
    {
        int userValue = 6;
        int counter = 1;

        for(int i=1; i<=userValue; i++)
        {
            for(int j=1; j<i; j++)
            {
                System.out.print(counter-j+" ");
            }
            System.out.println();
            counter +=i;
        }
    }
}
</code>```

output patern was:

```<code>1
3 2
6 5 4
10 9 8 7
15 14 13 12 11
</code>```

I've change a litile bit Your code - I add "counter" and for me it was the easyiest way to achive what You want.
For me alsow You should chane line

```<code>i<=userValue
</code>```

to

```<code>i<=userValue+1
</code>```

because user wants to print 6 line but in Your code prints only 5

All comments written in BrokenEnglish :)

Body:
I am trying to print a number pattern like below

The condition is when user will enter 6 then only first three rows should display and if user enters 3 then only first two rows should display.

class Star
{
    public static void main(String[] args)
    {
        int i,  j;
        for(i=1; i<=6; i++)
        {
            for(j=1; j<i; j++)
            {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}

1
3  2
6  5  4
10  9   8  7

thanks in advance :)

Body:
I have created something like this:

/**
 * Created by maciej.brzozowski.83@gmail.com on 2017-04-02.
 */
class Star
{
    public static void main(String[] args)
    {
        int userValue = 6;
        int counter = 1;

        for(int i=1; i<=userValue; i++)
        {
            for(int j=1; j<i; j++)
            {
                System.out.print(counter-j+" ");
            }
            System.out.println();
            counter +=i;
        }
    }
}

output patern was:

1
3 2
6 5 4
10 9 8 7
15 14 13 12 11

I've change a litile bit Your code - I add "counter" and for me it was the easyiest way to achive what You want.
For me alsow You should chane line

i<=userValue

to

i<=userValue+1

because user wants to print 6 line but in Your code prints only 5

All comments written in BrokenEnglish :)


问:
Include carriage returns when calculating substring
I have some data which is stored in a VARCHAR(MAX) column that contains the control characters CR & LF (CHAR(10) & CHAR(13)).

I have some start and end position numbers that I need to use to extract a substring from the text - but when I use SUBSTRING these control characters are ignored, which results in the substring being extracted incorrectly.

I wrote a query using a CTE that replaced all instances of CRLF with another character (¬¬) and then the substring works correctly - however I need to retain the CRLFs in the text as they are used for display purposes.

Can anyone think of a way I can get the SUBSTRING function to include the control characters when it is calculating which part of the string to extract?

答:
The SQL Server version of substring treats CRLF like other characters.  For example:

```<code>select substring('123' + char(10) + char(13) + '678',1,3)
-->
123

select substring('123' + char(10) + char(13) + '678',4,2)
-->
\r\n

select substring('123' + char(10) + char(13) + '678',6,3)
-->
678
</code>```

Check your code again, or post a more specific example of where substring does not work as expected.

Body:
The SQL Server version of substring treats CRLF like other characters.  For example:

select substring('123' + char(10) + char(13) + '678',1,3)
-->
123

select substring('123' + char(10) + char(13) + '678',4,2)
-->
\r\n

select substring('123' + char(10) + char(13) + '678',6,3)
-->
678

Check your code again, or post a more specific example of where substring does not work as expected.


问:
calendarextender causing postback in Opera when using with master page
I am having a very wired problem with calendar extender from ajax control toolkit in Opera. It's working fine in Chrome but in OPERA when I click on the image button to open calendar it will causing a post back and page get refreshed (calendar isn't opening).

If the page is simple page its working but if its a content page from a master page then the problem is there (for Opera).

答:
(Posted on behalf of the OP).

I resolved the issue. I was missing a JavaScript function which is called from server side and bind to scriptmanager.


问:
c++ command line macros preprocessor fails to replace word
I am working in a Linux terminal-command line environment, no IDE. I compile my c++ programs with g++. This one depends on using command line macros to execute different code statements without changing the source code itself. Here is the chunk of code where I have an issue. I have several different arrays that I want to perform a sorting on. Then I have functions somewhere else in the source code that perform that sorting and return the sorted array. I want to use command line macros to tell the preprocessor which array I want to use, and which sorting algorithm to use (which function to call). SORT_ALG should be replaced with the name of the function, and ARRAY should be replaced with the name of the array. So after preprocessing, the line should look like this:

```<code>int* sorted_array = BubbleSort(array1, array1_size);
</code>```

Here is the source code:

```<code>  int array1[] = {24, 13, 9, 64, 7, 23, 34, 47};
  int array1_size = sizeof(array1) / sizeof(array1[0]);

  // an already sorted array!
  int array2[] = {1, 2, 5, 8, 10, 15, 20, 25, 30};
  int array2_size = sizeof(array2) / sizeof(array2[0]);

  // a reverse sorted array!
  int array3[] = {75, 50, 45, 30, 25, 18, 17, 12, 10, 6, 5};
  int array3_size = sizeof(array3) / sizeof(array3[0]);

  /*
   * This code uses command line macros defined by g++
   * SORT_ALG should be one of the sorting function names such as:
   *   BubbleSort
   *   BubbleSortOptimized
   * ARRAY should be the name of one of the arrays, without the brackets:
   *   array1
   *   array2
   *   array3
   * Example of compiling the program with g++ using command line macros:
   *   g++ -D SORT_ALG=BubbleSort -D ARRAY=array1 sorting.cpp
   */
  int* sorted_array = SORT_ALG(ARRAY, ARRAY_size);
  cout << "The sorted array: ";
  PrintArray(sorted_array, ARRAY_size);
  cout << endl;
</code>```

When I try to compile the source code, the preprocessor doesn't recognize to replace ARRAY_size with the corresponding variable: array1_size.

```<code> $ g++ -D SORT_ALG=BubbleSort -D ARRAY=array1 sorting.cpp
sorting.cpp: In function ‘int main()’:
sorting.cpp:139:39: error: ‘ARRAY_size’ was not declared in this scope
   int* sorted_array = SORT_ALG(ARRAY, ARRAY_size);
</code>```

I think that the preprocessor should recognize the ARRAY being array1 and then replace ARRAY_size with array1_size. I think that it would be good to not have to define another command line macro to specify the size of the array because I would have to count the number of elements, and I'm going to be using this for situations where I don't know the size of the array in advance. So I have the compiler determine the size of the array. Is the underscore the reason why the preprocessor fails its job? It is better to use a different naming convention for the size of the array, to make it be preprocessed correctly? What other kind of approach would you suggest to fix this problem?

答:
From a preprocessor perspective, you can't define a macro FOO to be BAR and expect FOO_size to become BAR_size because FOO and FOO_size are different tokens.

You can, however, create a paste macro to stage this:

```<code>#define GLUE(a,b) GLUEI(a,b)
#define GLUEI(a,b) a##b
...
int* sorted_array = SORT_ALG(ARRAY, GLUE(ARRAY,_size));
</code>```

The macro needs to come in a pair with an indirect macro to allow its arguments to expand.  Due to macro expansion rules, ARRAY in the macro will expand first (given the indirection), which means if you define it to be something else that will apply before the pasting.

But outside the preprocessor perspective, why are you bothering to use the matching pair tokens anyway?  If array1_size is just going to be assigned to sizeof(array1) / sizeof(array1[0]), you could just change this to SORT_ALG(ARRAY, (sizeof(ARRAY)/sizeof(ARRAY[0]))).

(Also, what exactly are you doing here?  It looks like there could be a much better implementation in C++ if you're doing anything more complex than benchmarking something specific; and I'm puzzled why you're using the command line to switch between algorithms).

Body:
I am working in a Linux terminal-command line environment, no IDE. I compile my c++ programs with g++. This one depends on using command line macros to execute different code statements without changing the source code itself. Here is the chunk of code where I have an issue. I have several different arrays that I want to perform a sorting on. Then I have functions somewhere else in the source code that perform that sorting and return the sorted array. I want to use command line macros to tell the preprocessor which array I want to use, and which sorting algorithm to use (which function to call). SORT_ALG should be replaced with the name of the function, and ARRAY should be replaced with the name of the array. So after preprocessing, the line should look like this:

int* sorted_array = BubbleSort(array1, array1_size);

Here is the source code:

  int array1[] = {24, 13, 9, 64, 7, 23, 34, 47};
  int array1_size = sizeof(array1) / sizeof(array1[0]);

  // an already sorted array!
  int array2[] = {1, 2, 5, 8, 10, 15, 20, 25, 30};
  int array2_size = sizeof(array2) / sizeof(array2[0]);

  // a reverse sorted array!
  int array3[] = {75, 50, 45, 30, 25, 18, 17, 12, 10, 6, 5};
  int array3_size = sizeof(array3) / sizeof(array3[0]);

  /*
   * This code uses command line macros defined by g++
   * SORT_ALG should be one of the sorting function names such as:
   *   BubbleSort
   *   BubbleSortOptimized
   * ARRAY should be the name of one of the arrays, without the brackets:
   *   array1
   *   array2
   *   array3
   * Example of compiling the program with g++ using command line macros:
   *   g++ -D SORT_ALG=BubbleSort -D ARRAY=array1 sorting.cpp
   */
  int* sorted_array = SORT_ALG(ARRAY, ARRAY_size);
  cout << "The sorted array: ";
  PrintArray(sorted_array, ARRAY_size);
  cout << endl;

When I try to compile the source code, the preprocessor doesn't recognize to replace ARRAY_size with the corresponding variable: array1_size.

 $ g++ -D SORT_ALG=BubbleSort -D ARRAY=array1 sorting.cpp
sorting.cpp: In function ‘int main()’:
sorting.cpp:139:39: error: ‘ARRAY_size’ was not declared in this scope
   int* sorted_array = SORT_ALG(ARRAY, ARRAY_size);

I think that the preprocessor should recognize the ARRAY being array1 and then replace ARRAY_size with array1_size. I think that it would be good to not have to define another command line macro to specify the size of the array because I would have to count the number of elements, and I'm going to be using this for situations where I don't know the size of the array in advance. So I have the compiler determine the size of the array. Is the underscore the reason why the preprocessor fails its job? It is better to use a different naming convention for the size of the array, to make it be preprocessed correctly? What other kind of approach would you suggest to fix this problem?

Body:
From a preprocessor perspective, you can't define a macro FOO to be BAR and expect FOO_size to become BAR_size because FOO and FOO_size are different tokens.

You can, however, create a paste macro to stage this:

#define GLUE(a,b) GLUEI(a,b)
#define GLUEI(a,b) a##b
...
int* sorted_array = SORT_ALG(ARRAY, GLUE(ARRAY,_size));

The macro needs to come in a pair with an indirect macro to allow its arguments to expand.  Due to macro expansion rules, ARRAY in the macro will expand first (given the indirection), which means if you define it to be something else that will apply before the pasting.

But outside the preprocessor perspective, why are you bothering to use the matching pair tokens anyway?  If array1_size is just going to be assigned to sizeof(array1) / sizeof(array1[0]), you could just change this to SORT_ALG(ARRAY, (sizeof(ARRAY)/sizeof(ARRAY[0]))).

(Also, what exactly are you doing here?  It looks like there could be a much better implementation in C++ if you're doing anything more complex than benchmarking something specific; and I'm puzzled why you're using the command line to switch between algorithms).


问:
ConfORM Nhibernate OneToManyKeyColumnApplier Problem
I am using ConfORM Nhibernate  in one of my MVC project. And had problem with One to Many Mappings.

```<code>        IEnumerable<Type> domainEntities = this.GetDomainEntities();

        var relationalMapper = new ObjectRelationalMapper();
        relationalMapper.TablePerConcreteClass(domainEntities);
        relationalMapper.Patterns.PoidStrategies.Add(new NativePoidPattern());
        relationalMapper.Cascade<Category, Product>(Cascade.All);
        relationalMapper.ManyToMany<Category, Product>();
        relationalMapper.Cascade<Order, Product>(Cascade.Persist);

        var mapper = new Mapper(relationalMapper);
        var englishInflector = new EnglishInflector();

        mapper.PatternsAppliers.Merge(new ClassPluralizedTableApplier(englishInflector));
        mapper.PatternsAppliers.Merge(new OneToManyKeyColumnApplier(relationalMapper));
         .....

        HbmMapping mapping = mapper.CompileMappingFor(domainEntities);
</code>```

And classes Order and User: One User had many Orders.

```<code> public class Order : BaseEntity
{
    public Order(User user)
    {
        if (user == null)
        {
            throw new ArgumentNullException("user");
        }

        this.User = user;
    }

    protected Order()
    {
    }

    public virtual User User { get; protected set; }
}
</code>```

And Users:

```<code> public class User : BaseEntity
{
    public User()
    {
        this.Orders = new HashedSet<Order>();
    }

    public virtual string FirstName { get; set; }

    public virtual ISet<Order> Orders { get; protected set; }
}
</code>```

I expect relations like this: Orders.UserId -> User.Id in the DB. But when the Nhibernate had genereted DB we had this problem (See image):

UPS. Double reference User and UserId suddenly uppeared. And when we removed [user] Nhivernate can`t do inner join this tables. It sad that double time:
Invalid column name 'User'.
Invalid column name 'User'.

I think there is some problems with setuping ConfORM.
If I remove mapper.PatternsAppliers.Merge(new OneToManyKeyColumnApplier(relationalMapper));
ConfORM generete just [User] reference key.

Anyone know what the problem is here?
Thanks in Advance.

答:
You need to add the following applier

```<code>mapper.PatternsAppliers.Merge(new ManyToOneColumnApplier());
</code>```

Probably thats because column name has changed from Users side, but has not changed from Order side.

Body:
I am using ConfORM Nhibernate  in one of my MVC project. And had problem with One to Many Mappings.

        IEnumerable<Type> domainEntities = this.GetDomainEntities();

        var relationalMapper = new ObjectRelationalMapper();
        relationalMapper.TablePerConcreteClass(domainEntities);
        relationalMapper.Patterns.PoidStrategies.Add(new NativePoidPattern());
        relationalMapper.Cascade<Category, Product>(Cascade.All);
        relationalMapper.ManyToMany<Category, Product>();
        relationalMapper.Cascade<Order, Product>(Cascade.Persist);

        var mapper = new Mapper(relationalMapper);
        var englishInflector = new EnglishInflector();

        mapper.PatternsAppliers.Merge(new ClassPluralizedTableApplier(englishInflector));
        mapper.PatternsAppliers.Merge(new OneToManyKeyColumnApplier(relationalMapper));
         .....

        HbmMapping mapping = mapper.CompileMappingFor(domainEntities);

And classes Order and User: One User had many Orders.

 public class Order : BaseEntity
{
    public Order(User user)
    {
        if (user == null)
        {
            throw new ArgumentNullException("user");
        }

        this.User = user;
    }

    protected Order()
    {
    }

    public virtual User User { get; protected set; }
}

And Users:

 public class User : BaseEntity
{
    public User()
    {
        this.Orders = new HashedSet<Order>();
    }

    public virtual string FirstName { get; set; }

    public virtual ISet<Order> Orders { get; protected set; }
}

I expect relations like this: Orders.UserId -> User.Id in the DB. But when the Nhibernate had genereted DB we had this problem (See image):

UPS. Double reference User and UserId suddenly uppeared. And when we removed [user] Nhivernate can`t do inner join this tables. It sad that double time:
Invalid column name 'User'.
Invalid column name 'User'.

I think there is some problems with setuping ConfORM.
If I remove mapper.PatternsAppliers.Merge(new OneToManyKeyColumnApplier(relationalMapper));
ConfORM generete just [User] reference key.

Anyone know what the problem is here?
Thanks in Advance.

Body:
You need to add the following applier

mapper.PatternsAppliers.Merge(new ManyToOneColumnApplier());

Probably thats because column name has changed from Users side, but has not changed from Order side.


问:
Kotlin - creating a mutable list with repeating elements
What would be an idiomatic way to create a mutable list of a given length n with repeating elements of value v (e.g listOf(4,4,4,4,4)) as an expression.

I'm doing val list = listOf((0..n-1)).flatten().map{v} but it can only create an immutable list.

答:
Use:

```<code>val list = MutableList(n) {index -> v}
</code>```

or, since index is unused, you could omit it:

```<code>val list = MutableList(n) { v }
</code>```

Body:
Use:

val list = MutableList(n) {index -> v}

or, since index is unused, you could omit it:

val list = MutableList(n) { v }

ContentLicense: CC BY-SA 4.0


问:
Meteor-Angular2 - ReferenceError: System is not defined
Since I tried upgraded my project to support the last Angular2 router I completely broke my app.h

Nothing went smoot and it's been an amazing journey through all errors and problems that I have face. I managed to solve them all except this one.

I would be very appreciated if someone could give me a hint on what to do because I ran out of possibilities.

```<code>W20160905-02:19:05.541(1)? (STDERR) /home/workspace/.meteor/packages/meteor-tool/.1.4.1_1.crqcrg++os.linux.x86_64+web.browser+web.cordova/mt-os.linux.x86_64/dev_bundle/server-lib/node_modules/fibers/future.js:280
W20160905-02:19:05.652(1)? (STDERR)                             throw(ex);
W20160905-02:19:05.652(1)? (STDERR)                             ^
W20160905-02:19:05.653(1)? (STDERR)
W20160905-02:19:05.653(1)? (STDERR) ReferenceError: System is not defined
W20160905-02:19:05.653(1)? (STDERR)     at systemjs.config.js:40:26
W20160905-02:19:05.654(1)? (STDERR)     at meteorInstall.systemjs.config.js (systemjs.config.js:5:1)
W20160905-02:19:05.654(1)? (STDERR)     at fileEvaluate (packages/modules-runtime/.npm/package/node_modules/install/install.js:153:1)
W20160905-02:19:05.655(1)? (STDERR)     at require (packages/modules-runtime/.npm/package/node_modules/install/install.js:82:1)
W20160905-02:19:05.655(1)? (STDERR)     at server/main.ts:11:4
W20160905-02:19:05.655(1)? (STDERR)     at /home/workspace/meteor-angular/test-app-v1.0.3/.meteor/local/build/programs/server/boot.js:292:10
W20160905-02:19:05.656(1)? (STDERR)     at Array.forEach (native)
W20160905-02:19:05.656(1)? (STDERR)     at Function._.each._.forEach (/home/workspace/.meteor/packages/meteor-tool/.1.4.1_1.crqcrg++os.linux.x86_64+web.browser+web.cordova/mt-os.linux.x86_64/dev_bundle/server-lib/node_modules/underscore/underscore.js:79:11)
W20160905-02:19:05.656(1)? (STDERR)     at /home/workspace/meteor-angular/test-app-v1.0.3/.meteor/local/build/programs/server/boot.js:128:5
=> Exited with code: 1
</code>```

答:
If your are trying to use lazy loading on routes like this:

```<code>{ path: "myPath", loadChildren: "app/myModule/myModule.module#MyModule"}
</code>```

Sorry but it will not work as meteor doesn't support lazy loading.
Fortunately I managed to make it work with this:

```<code>{path: "myPath", loadChildren: ()=> require('./myModule/myModule.module')["MyModule"] }
</code>```

Hopefully will work for you as well. :)

Body:
Since I tried upgraded my project to support the last Angular2 router I completely broke my app.h

Nothing went smoot and it's been an amazing journey through all errors and problems that I have face. I managed to solve them all except this one.

I would be very appreciated if someone could give me a hint on what to do because I ran out of possibilities.

W20160905-02:19:05.541(1)? (STDERR) /home/workspace/.meteor/packages/meteor-tool/.1.4.1_1.crqcrg++os.linux.x86_64+web.browser+web.cordova/mt-os.linux.x86_64/dev_bundle/server-lib/node_modules/fibers/future.js:280
W20160905-02:19:05.652(1)? (STDERR)                             throw(ex);
W20160905-02:19:05.652(1)? (STDERR)                             ^
W20160905-02:19:05.653(1)? (STDERR)
W20160905-02:19:05.653(1)? (STDERR) ReferenceError: System is not defined
W20160905-02:19:05.653(1)? (STDERR)     at systemjs.config.js:40:26
W20160905-02:19:05.654(1)? (STDERR)     at meteorInstall.systemjs.config.js (systemjs.config.js:5:1)
W20160905-02:19:05.654(1)? (STDERR)     at fileEvaluate (packages/modules-runtime/.npm/package/node_modules/install/install.js:153:1)
W20160905-02:19:05.655(1)? (STDERR)     at require (packages/modules-runtime/.npm/package/node_modules/install/install.js:82:1)
W20160905-02:19:05.655(1)? (STDERR)     at server/main.ts:11:4
W20160905-02:19:05.655(1)? (STDERR)     at /home/workspace/meteor-angular/test-app-v1.0.3/.meteor/local/build/programs/server/boot.js:292:10
W20160905-02:19:05.656(1)? (STDERR)     at Array.forEach (native)
W20160905-02:19:05.656(1)? (STDERR)     at Function._.each._.forEach (/home/workspace/.meteor/packages/meteor-tool/.1.4.1_1.crqcrg++os.linux.x86_64+web.browser+web.cordova/mt-os.linux.x86_64/dev_bundle/server-lib/node_modules/underscore/underscore.js:79:11)
W20160905-02:19:05.656(1)? (STDERR)     at /home/workspace/meteor-angular/test-app-v1.0.3/.meteor/local/build/programs/server/boot.js:128:5
=> Exited with code: 1

Body:
If your are trying to use lazy loading on routes like this:

{ path: "myPath", loadChildren: "app/myModule/myModule.module#MyModule"}

Sorry but it will not work as meteor doesn't support lazy loading.
Fortunately I managed to make it work with this:

{path: "myPath", loadChildren: ()=> require('./myModule/myModule.module')["MyModule"] }

Hopefully will work for you as well. :)


问:
Efficient Multi-threading in C
I'm currently in the introductory stages of writing multi-threaded programs in C. I understand how to create separate threads with completely separate functions but I'm wanting to understand how programmers in the field break down a single task to take advantage of multi-threading. I've gone through several exercises for synchronizing separate threads but nothing good when it comes to breaking down a single task and making it quicker with multiple threads. I'd really appreciate some wisdom when it comes to solving these types of problems and explain how and why you would attack a problem in that particular way.

As an example, lets say this is the task I'm trying to tackle with multiple threads. [It multiplies two matrices together creating the c matrix with n x p dimensions.] And lets also say we can input how many threads we want to run between 1 and t (even though there won't be a significant performance difference in threads >= 4) so it's obvious how to attack it.

```<code> for (i = 0; i < n; i++){
     for (j = 0; j < p; j++){
         c[i][j] = 0;
         for (k = 0; k < m; k++){
             c[i][j] += a[i][k] * b[k][j];
         }
      }
  }
</code>```

My first thoughts are to basically divide each loop up according to how many threads. So, for t threads,

```<code> for (i = 0; i < n / t; i++){
     for (j = 0; j < p / t; j++){
         c[i][j] = 0;
         for (k = 0; k < m / t; k++){
             c[i][j] += a[i][k] * b[k][j];
         }
      }
  }
</code>```

And then synchronizing them with semaphores. But this would have to separate each part of the problem into t-cohesive threads that don't overlap or miss any of the matrices. This seems a little much and I have a feeling there's a better way to attack it. How would you guys go about this?

答: For matrix operations especially small matrices, you will probable be best off using SIMD. Threads really come into theirvown for largish long running tasks. For short tasks, tge overhead becomes prohibitive.</p>

Title: Efficient Multi-threading in C

Body:
I'm currently in the introductory stages of writing multi-threaded programs in C. I understand how to create separate threads with completely separate functions but I'm wanting to understand how programmers in the field break down a single task to take advantage of multi-threading. I've gone through several exercises for synchronizing separate threads but nothing good when it comes to breaking down a single task and making it quicker with multiple threads. I'd really appreciate some wisdom when it comes to solving these types of problems and explain how and why you would attack a problem in that particular way.

As an example, lets say this is the task I'm trying to tackle with multiple threads. [It multiplies two matrices together creating the c matrix with n x p dimensions.] And lets also say we can input how many threads we want to run between 1 and t (even though there won't be a significant performance difference in threads >= 4) so it's obvious how to attack it.

 for (i = 0; i < n; i++){
     for (j = 0; j < p; j++){
         c[i][j] = 0;
         for (k = 0; k < m; k++){
             c[i][j] += a[i][k] * b[k][j];
         }
      }
  }

My first thoughts are to basically divide each loop up according to how many threads. So, for t threads,

 for (i = 0; i < n / t; i++){
     for (j = 0; j < p / t; j++){
         c[i][j] = 0;
         for (k = 0; k < m / t; k++){
             c[i][j] += a[i][k] * b[k][j];
         }
      }
  }

And then synchronizing them with semaphores. But this would have to separate each part of the problem into t-cohesive threads that don't overlap or miss any of the matrices. This seems a little much and I have a feeling there's a better way to attack it. How would you guys go about this?


问:
PHP MySQL Binding Statement Situation
I have to create a web service in my application to pull data from a MySQL database using PHP.  I don't know if what I want to do will work or not as I am new to PHP.  Here is the code:

```<code>$queryString = "SELECT uniqueID, address FROM main WHERE (state = ?) AND (propType IN (?)";
$stmt = mysqli_prepare($this->connection, $queryString);
mysqli_stmt_bind_param($stmt, 'ss', $itemst, $itempt);
mysqli_stmt_execute($stmt);
</code>```

My question has to do with the binding statement for the propType column of my database.  In my application, there are like 8 different property types that a user can click a checkbox to search.  What I would like to do is to stitch the strings together into one value represented above by $itempt, and just bind this single string to the SQL statement, but I don't know if I can do this???

If I can't, then I have to do something like the following:

```<code>$queryString = "SELECT uniqueID, address FROM main WHERE (state = ?) AND (propType IN (?,?,?,?,?,?,?,?)";
</code>```

This could get complicated in the binding expression because I would have to test which property types were selected and come up with a variety of different queries/binding expressions, which would be laborious.

So my question is, with an "IN" clause, can I stitch all of the string values into a single comma-separated string, and then just bind this single value to my query, or do I have to pass a separate variable for each possible value and bind to them individually?

Thanks for any insight!

答:
I edited my answer since it did not work and rewrote the snippet in PDO style and tested it (just with a different table schema).

Here it is:

```<code>$servername = "localhost";
$username = "user";
$password = "pass";
$db = "stackoverflow";

try{
    $con = new PDO("mysql:host=$servername;dbname=$db", $username, $password);
    $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $con->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); // set this if you want to bind LIMIT values

}catch(PDOException $e){
    $error =  "Connection failed: " . $e->getMessage();
}

$itemst = ['active']; // cast search parameters as array so you can merge them
// watch the order in which you bind them! Else you will never find matching entries
$container = ['some title 1','some title 3','some title 5'];
$limit = [0,2];
$params = array_values(array_merge($itemst,$container,$limit));
$bindStr = implode(",", array_map(function($val) { return "?"; }, $container));
$queryString = "SELECT course_title FROM mysqli_quick WHERE state = ? AND course_title IN ({$bindStr}) LIMIT ?,?";

$stmt = $con->prepare($queryString);

$stmt->execute($params);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
var_dump($result);
</code>```

Prints

```<code>array (size=3)
  0 =>
    array (size=1)
      'course_title' => string 'some title 1' (length=12)
  1 =>
    array (size=1)
      'course_title' => string 'some title 3' (length=12)
</code>```

Title: PHP MySQL Binding Statement Situation

Body:
I have to create a web service in my application to pull data from a MySQL database using PHP.  I don't know if what I want to do will work or not as I am new to PHP.  Here is the code:

$queryString = "SELECT uniqueID, address FROM main WHERE (state = ?) AND (propType IN (?)";
$stmt = mysqli_prepare($this->connection, $queryString);
mysqli_stmt_bind_param($stmt, 'ss', $itemst, $itempt);
mysqli_stmt_execute($stmt);

My question has to do with the binding statement for the propType column of my database.  In my application, there are like 8 different property types that a user can click a checkbox to search.  What I would like to do is to stitch the strings together into one value represented above by $itempt, and just bind this single string to the SQL statement, but I don't know if I can do this???

If I can't, then I have to do something like the following:

$queryString = "SELECT uniqueID, address FROM main WHERE (state = ?) AND (propType IN (?,?,?,?,?,?,?,?)";

This could get complicated in the binding expression because I would have to test which property types were selected and come up with a variety of different queries/binding expressions, which would be laborious.

So my question is, with an "IN" clause, can I stitch all of the string values into a single comma-separated string, and then just bind this single value to my query, or do I have to pass a separate variable for each possible value and bind to them individually?

Thanks for any insight!

Body:
I edited my answer since it did not work and rewrote the snippet in PDO style and tested it (just with a different table schema).

Here it is:

$servername = "localhost";
$username = "user";
$password = "pass";
$db = "stackoverflow";

try{
    $con = new PDO("mysql:host=$servername;dbname=$db", $username, $password);
    $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $con->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); // set this if you want to bind LIMIT values

}catch(PDOException $e){
    $error =  "Connection failed: " . $e->getMessage();
}

$itemst = ['active']; // cast search parameters as array so you can merge them
// watch the order in which you bind them! Else you will never find matching entries
$container = ['some title 1','some title 3','some title 5'];
$limit = [0,2];
$params = array_values(array_merge($itemst,$container,$limit));
$bindStr = implode(",", array_map(function($val) { return "?"; }, $container));
$queryString = "SELECT course_title FROM mysqli_quick WHERE state = ? AND course_title IN ({$bindStr}) LIMIT ?,?";

$stmt = $con->prepare($queryString);

$stmt->execute($params);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
var_dump($result);

Prints

array (size=3)
  0 =>
    array (size=1)
      'course_title' => string 'some title 1' (length=12)
  1 =>
    array (size=1)
      'course_title' => string 'some title 3' (length=12)