问:
Spring/LDAP - Invoking setter methods in beans configuration
I am writing a Spring LDAP application and I have to set the authentication strategy for my ContextSource. I would like to do this in my beans XML file. The JavaDoc for ContextSource says that it has a setter method called

```<code>setAuthenticationStrategy(
    DirContextAuthenticationStrategy authenticationStrategy
)
</code>```

To invoke this setter from my beans file, is the following XML sufficient?

```<code><bean id="authStrategy"
    class="org.springframework...DefaultTlsDirContextAuthenticationStrategy">
 ...
</bean>

<bean id="contextSource"
    class="org.springframework.ldap.core.support.LdapContextSource">

    <property name="url" ... />
    <property name="base" ... />
     ...
    <property name="authenticationStrategy" ref="authStrategy" />
</bean>
</code>```

That is to say, what exactly determines the invocation of the method setAuthenticationStrategy? Is it that my property name is authenticationStrategy? Does Spring automatically translate property names to the appropriate setter method?

答:
Actually, you misunderstood the meaning of the word 'property' in the JavaBean context.

Bean Properties vs Fields

The JavaBeans standard (which Spring follows closely) defines a Bean property as something that has a Getter method and / or a Setter method that follows a certain naming convention:

for a property 'Bar foo', either the getter Bar getFoo() (or isFoo() for boolean properties) or the setter setFoo(Bar) must be present (or both), but there does not have to be a field named "foo". Per convention, there usually is a field with the same name as the property, but it's by no means required.

E.g. the following class (which conforms to the JavaBeans standard) has a bean property "foo" of type Integer, although the underlying field is called iAmNotFoo and is of type String.

```<code>public class Dummy {
    private String  iAmNotFoo;
    public Integer getFoo() {
        return  Integer.valueOf(this.iAmNotFoo);
    }

    public void setFoo(final Integer foo) {
        this.iAmNotFoo = foo.toString();
    }
}
</code>```

We can test this assumption with the following code:

```<code>public static void main(final String[] args) throws Exception {
    for (final PropertyDescriptor descriptor :
        Introspector
            .getBeanInfo(Dummy.class, Object.class)
            .getPropertyDescriptors()) {
        System.out.println(
            "Property: "
            + descriptor.getName()
            + ", type: "
            + descriptor.getPropertyType()
        );
    }
    for (final Field field : Dummy.class.getDeclaredFields()) {
        System.out.println(
            "Field: "
            + field.getName()
            + ", type: "
            + field.getType());
    }
}
</code>```

Output:

Property: foo, type: class java.lang.Integer

  Field: iAmNotFoo, type: class java.lang.String

Properties in Spring

As I said above, Spring uses this exact mechanism to set properties. So when you configure a bean like this

```<code><bean class="Dummy">
    <property name="foo" value="123" />
</bean>
</code>```

"foo" refers to the bean property "foo" and hence to the setter setFoo()

Which makes constructs like the following possible:

```<code>public class Dummy2 {
    private List<String> foos;
    public void setFoos(List<String> foos) {
        this.foos = foos;
    }
    public void setFoo(String foo){
        this.foos = Collections.singletonList(foo);
    }
}
</code>```

You can wire this as follows

```<code><bean class="Dummy2">
    <!-- either set a single value -->
    <property name="foo" value="123" />
    <!-- or a list of values -->
    <property name="foos">
        <util:list>
            <value>Abc</value>
            <value>Xyz</value>
            <value>123</value>
            <value>789</value>
        </util:list>
    </property>
</bean>
</code>```

As you can see, the setter methods are relevant to Spring, not the actual fields.

So, in JavaBeans speak: Field != Property, although in most cases a field of the same type and name as the property exists.

Body:
I am writing a Spring LDAP application and I have to set the authentication strategy for my ContextSource. I would like to do this in my beans XML file. The JavaDoc for ContextSource says that it has a setter method called

setAuthenticationStrategy(
    DirContextAuthenticationStrategy authenticationStrategy
)

To invoke this setter from my beans file, is the following XML sufficient?

<bean id="authStrategy"
    class="org.springframework...DefaultTlsDirContextAuthenticationStrategy">
 ...
</bean>

<bean id="contextSource"
    class="org.springframework.ldap.core.support.LdapContextSource">

    <property name="url" ... />
    <property name="base" ... />
     ...
    <property name="authenticationStrategy" ref="authStrategy" />
</bean>

That is to say, what exactly determines the invocation of the method setAuthenticationStrategy? Is it that my property name is authenticationStrategy? Does Spring automatically translate property names to the appropriate setter method?

Body:
Actually, you misunderstood the meaning of the word 'property' in the JavaBean context.

Bean Properties vs Fields

The JavaBeans standard (which Spring follows closely) defines a Bean property as something that has a Getter method and / or a Setter method that follows a certain naming convention:

for a property 'Bar foo', either the getter Bar getFoo() (or isFoo() for boolean properties) or the setter setFoo(Bar) must be present (or both), but there does not have to be a field named "foo". Per convention, there usually is a field with the same name as the property, but it's by no means required.

E.g. the following class (which conforms to the JavaBeans standard) has a bean property "foo" of type Integer, although the underlying field is called iAmNotFoo and is of type String.

public class Dummy {
    private String  iAmNotFoo;
    public Integer getFoo() {
        return  Integer.valueOf(this.iAmNotFoo);
    }

    public void setFoo(final Integer foo) {
        this.iAmNotFoo = foo.toString();
    }
}

We can test this assumption with the following code:

public static void main(final String[] args) throws Exception {
    for (final PropertyDescriptor descriptor :
        Introspector
            .getBeanInfo(Dummy.class, Object.class)
            .getPropertyDescriptors()) {
        System.out.println(
            "Property: "
            + descriptor.getName()
            + ", type: "
            + descriptor.getPropertyType()
        );
    }
    for (final Field field : Dummy.class.getDeclaredFields()) {
        System.out.println(
            "Field: "
            + field.getName()
            + ", type: "
            + field.getType());
    }
}

Output:

Property: foo, type: class java.lang.Integer

  Field: iAmNotFoo, type: class java.lang.String

Properties in Spring

As I said above, Spring uses this exact mechanism to set properties. So when you configure a bean like this

<bean class="Dummy">
    <property name="foo" value="123" />
</bean>

"foo" refers to the bean property "foo" and hence to the setter setFoo()

Which makes constructs like the following possible:

public class Dummy2 {
    private List<String> foos;
    public void setFoos(List<String> foos) {
        this.foos = foos;
    }
    public void setFoo(String foo){
        this.foos = Collections.singletonList(foo);
    }
}

You can wire this as follows

<bean class="Dummy2">
    <!-- either set a single value -->
    <property name="foo" value="123" />
    <!-- or a list of values -->
    <property name="foos">
        <util:list>
            <value>Abc</value>
            <value>Xyz</value>
            <value>123</value>
            <value>789</value>
        </util:list>
    </property>
</bean>

As you can see, the setter methods are relevant to Spring, not the actual fields.

So, in JavaBeans speak: Field != Property, although in most cases a field of the same type and name as the property exists.


来源: stackexchange

问:
How to create high res JPEG with Wand from binary string

I'm trying to convert some PDFs to high res jpegs using imagemagick . I'm working on win 10, 64 with python 3.62 - 64 bit and wand 0.4.4. At the command line I have :

```<code>$ /e/ImageMagick-6.9.9-Q16-HDRI/convert.exe -density 400 myfile.pdf -scale 2000x1000 test3.jpg.
</code>```

which is working well for me.

In python:

```<code>from wand.image import Image

file_path = os.path.dirname(os.path.abspath(__file__))+os.sep+"myfile.pdf"

with Image(filename=file_path, resolution=400) as image:
    image.save()
    image_jpeg = image.convert('jpeg')
</code>```

Which is giving me low res JPEGs . How do I translate this into my wand code to do the same thing?

edit:

I realized that the problem is that the input pdf has to be read into the Image object as a binary string, so based on http://docs.wand-py.org/en/0.4.4/guide/read.html#read-blob I tried:

```<code>with open(file_path,'rb') as f:
    image_binary = f.read()

f.close()

with Image(blob=image_binary,resolution=400) as img:
    img.transform('2000x1000', '100%')
    img.make_blob('jpeg')
    img.save(filename='out.jpg')
</code>```

This reads the file in ok, but the output is split into 10 files. Why? I need to get this into 1 high res jpeg.

EDIT:

I need to send the jpeg to an OCR api, so I was wondering if I could write the output to a file like object. Looking at  https://www.imagemagick.org/api/magick-image.php#MagickWriteImageFile, I tried :

```<code>emptyFile =  Image(width=1500, height=2000)

with Image(filename=file_path, resolution=400) as image:

    library.MagickResetIterator(image.wand)
    # Call C-API Append method.
    resource_pointer = library.MagickAppendImages(image.wand,
                                                  True)

    library.MagickWriteImagesFile(resource_pointer,emptyFile)
</code>```

This gives:

```<code> File "E:/ENVS/r3/pdfminer.six/ocr_space.py", line 113, in <module>
test_file = ocr_stream(filename='test4.jpg')
 File "E:/ENVS/r3/pdfminer.six/ocr_space.py", line 96, in ocr_stream
library.MagickWriteImagesFile(resource_pointer,emptyFile)
ctypes.ArgumentError: argument 2: <class 'TypeError'>: wrong type
</code>```

How can I get this working?

答:
Why? I need to get this into 1 high res jpeg.

The PDF contains pages that ImageMagick considers individual images in a "stack". The wand library provides a wand.image.Image.sequance to work with each page.

However, to append all images into a single JPEG. You can either iterate over each page & stitch them together, or call C-API's method MagickAppendImages.

from wand.image import Image
from wand.api import library
import ctypes

# Map C-API not provided by wand library.
library.MagickAppendImages.argtypes = [ctypes.c_void_p, ctypes.c_int]
library.MagickAppendImages.restype = ctypes.c_void_p

with Image(filename="path_to_document.pdf", resolution=400) as image:
    # Do all your preprocessing first
    # Ether word directly on the wand instance, or iterate over each page.
    # ...
    # To write all "pages" into a single image.
    # Reset the stack iterator.
    library.MagickResetIterator(image.wand)
    # Call C-API Append method.
    resource_pointer = library.MagickAppendImages(image.wand,
                                                  True)
    # Write C resource directly to disk.
    library.MagickWriteImages(resource_pointer,
                              "output.jpeg".encode("ASCII"),
                              False)
```

<p><strong>Update:</strong></p>

<blockquote>
  <p>I need to send the jpeg to an OCR api ...</p>
</blockquote>

<p>Assuming your using OpenCV's python API, you'll only need to iterate over each page, and pass the image-file data to the OCR via numpy buffers.</p>

<pre class="lang-py prettyprint-override"><code>from wand.image import Image
import numpy
import cv2

def ocr_process(file_data_buffer):
     """ Replace with whatever your OCR-API calls for """
     mat_instance = cv2.imdecode(file_data_buffer)
     # ... work ...

source_image="path_to_document.pdf"
with Image(filename=source_image, resolution=400) as img:
    for page in img.sequence:
        file_buffer = numpy.asarray(bytearray(page.make_blob("JPEG")),
                                    dtype=numpy.uint8)
        ocr_process(file_buffer)
</code>```

so I was wondering if I could write the output to a file like object

Don't assume that python "image" objects (or underlining C structures) from different libraries are comparable with each other.

Without knowing the OCR api, I can't help you past the wand part, but I can suggest one of the following...

Use temporary intermediate files. (slower I/O, but easier to learn/develop/debug)

```<code>with Image(filename=INPUT_PATH) as img:
    # work
    img.save(filename=OUTPUT_PATH)
# OCR work on OUTPUT_PATH
</code>```

Use file descriptors if the OCR API supports it. (Same as above)

```<code>with open(INPUT_PATH, 'rb') as fd:
    with Image(file=fd) as img:
        # work
        # OCR work ???
</code>```

Use blobs. (faster I/O but need a lot more memory)

```<code>buffer = None
with Image(filename=INPUT_PATH) as img:
    # work
    buffer = img.make_blob(FORMAT)
if buffer:
    # OCR work ???
</code>```

Even More Updates

Wrapping all the comments together, a solution might be...

from wand.image import Image
from wand.api import library
import ctypes
import requests

# Map C-API not provided by wand library.
library.MagickAppendImages.argtypes = [ctypes.c_void_p, ctypes.c_int]
library.MagickAppendImages.restype = ctypes.c_void_p

with Image(filename='path_to_document.pdf', resolution=400) as image:
    # ... Do pre-processing ...
    # Reset the stack iterator.
    library.MagickResetIterator(image.wand)
    # Call C-API Append method.
    resource_pointer = library.MagickAppendImages(image.wand, True)
    # Convert to JPEG.
    library.MagickSetImageFormat(resource_pointer, b'JPEG')
    # Create size sentinel.
    length = ctypes.c_size_t()
    # Write image blob to memory.
    image_data_pointer = library.MagickGetImagesBlob(resource_pointer,
                                                     ctypes.byref(length))
    # Ensure success
    if image_data_pointer and length.value:
        # Create buffer from memory address
        payload = ctypes.string_at(image_data_pointer, length.value)
        # Define local filename.
        payload_filename = 'my_hires_image.jpg'
        # Post payload as multipart encoded image file with filename.
        requests.post(THE_URL, files={'file': (payload_filename, payload)})
```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to convert some PDFs to high res jpegs using imagemagick . I'm working on win 10, 64 with python 3.62 - 64 bit and wand 0.4.4. At the command line I have :

$ /e/ImageMagick-6.9.9-Q16-HDRI/convert.exe -density 400 myfile.pdf -scale 2000x1000 test3.jpg.

which is working well for me.

In python:

from wand.image import Image

file_path = os.path.dirname(os.path.abspath(__file__))+os.sep+"myfile.pdf"

with Image(filename=file_path, resolution=400) as image:
    image.save()
    image_jpeg = image.convert('jpeg')

Which is giving me low res JPEGs . How do I translate this into my wand code to do the same thing?

edit:

I realized that the problem is that the input pdf has to be read into the Image object as a binary string, so based on http://docs.wand-py.org/en/0.4.4/guide/read.html#read-blob I tried:

with open(file_path,'rb') as f:
    image_binary = f.read()

f.close()

with Image(blob=image_binary,resolution=400) as img:
    img.transform('2000x1000', '100%')
    img.make_blob('jpeg')
    img.save(filename='out.jpg')

This reads the file in ok, but the output is split into 10 files. Why? I need to get this into 1 high res jpeg.

EDIT:

I need to send the jpeg to an OCR api, so I was wondering if I could write the output to a file like object. Looking at  https://www.imagemagick.org/api/magick-image.php#MagickWriteImageFile, I tried :

emptyFile =  Image(width=1500, height=2000)

with Image(filename=file_path, resolution=400) as image:

    library.MagickResetIterator(image.wand)
    # Call C-API Append method.
    resource_pointer = library.MagickAppendImages(image.wand,
                                                  True)

    library.MagickWriteImagesFile(resource_pointer,emptyFile)

This gives:

 File "E:/ENVS/r3/pdfminer.six/ocr_space.py", line 113, in <module>
test_file = ocr_stream(filename='test4.jpg')
 File "E:/ENVS/r3/pdfminer.six/ocr_space.py", line 96, in ocr_stream
library.MagickWriteImagesFile(resource_pointer,emptyFile)
ctypes.ArgumentError: argument 2: <class 'TypeError'>: wrong type

How can I get this working?

Body:
Why? I need to get this into 1 high res jpeg.

The PDF contains pages that ImageMagick considers individual images in a "stack". The wand library provides a wand.image.Image.sequance to work with each page.

However, to append all images into a single JPEG. You can either iterate over each page & stitch them together, or call C-API's method MagickAppendImages.

from wand.image import Image
from wand.api import library
import ctypes

# Map C-API not provided by wand library.
library.MagickAppendImages.argtypes = [ctypes.c_void_p, ctypes.c_int]
library.MagickAppendImages.restype = ctypes.c_void_p

with Image(filename="path_to_document.pdf", resolution=400) as image:
    # Do all your preprocessing first
    # Ether word directly on the wand instance, or iterate over each page.
    # ...
    # To write all "pages" into a single image.
    # Reset the stack iterator.
    library.MagickResetIterator(image.wand)
    # Call C-API Append method.
    resource_pointer = library.MagickAppendImages(image.wand,
                                                  True)
    # Write C resource directly to disk.
    library.MagickWriteImages(resource_pointer,
                              "output.jpeg".encode("ASCII"),
                              False)

Update:

I need to send the jpeg to an OCR api ...

Assuming your using OpenCV's python API, you'll only need to iterate over each page, and pass the image-file data to the OCR via numpy buffers.

from wand.image import Image
import numpy
import cv2

def ocr_process(file_data_buffer):
     """ Replace with whatever your OCR-API calls for """
     mat_instance = cv2.imdecode(file_data_buffer)
     # ... work ...

source_image="path_to_document.pdf"
with Image(filename=source_image, resolution=400) as img:
    for page in img.sequence:
        file_buffer = numpy.asarray(bytearray(page.make_blob("JPEG")),
                                    dtype=numpy.uint8)
        ocr_process(file_buffer)

so I was wondering if I could write the output to a file like object

Don't assume that python "image" objects (or underlining C structures) from different libraries are comparable with each other.

Without knowing the OCR api, I can't help you past the wand part, but I can suggest one of the following...

Use temporary intermediate files. (slower I/O, but easier to learn/develop/debug)

with Image(filename=INPUT_PATH) as img:
    # work
    img.save(filename=OUTPUT_PATH)
# OCR work on OUTPUT_PATH

Use file descriptors if the OCR API supports it. (Same as above)

with open(INPUT_PATH, 'rb') as fd:
    with Image(file=fd) as img:
        # work
        # OCR work ???

Use blobs. (faster I/O but need a lot more memory)

buffer = None
with Image(filename=INPUT_PATH) as img:
    # work
    buffer = img.make_blob(FORMAT)
if buffer:
    # OCR work ???

Even More Updates

Wrapping all the comments together, a solution might be...

from wand.image import Image
from wand.api import library
import ctypes
import requests

# Map C-API not provided by wand library.
library.MagickAppendImages.argtypes = [ctypes.c_void_p, ctypes.c_int]
library.MagickAppendImages.restype = ctypes.c_void_p

with Image(filename='path_to_document.pdf', resolution=400) as image:
    # ... Do pre-processing ...
    # Reset the stack iterator.
    library.MagickResetIterator(image.wand)
    # Call C-API Append method.
    resource_pointer = library.MagickAppendImages(image.wand, True)
    # Convert to JPEG.
    library.MagickSetImageFormat(resource_pointer, b'JPEG')
    # Create size sentinel.
    length = ctypes.c_size_t()
    # Write image blob to memory.
    image_data_pointer = library.MagickGetImagesBlob(resource_pointer,
                                                     ctypes.byref(length))
    # Ensure success
    if image_data_pointer and length.value:
        # Create buffer from memory address
        payload = ctypes.string_at(image_data_pointer, length.value)
        # Define local filename.
        payload_filename = 'my_hires_image.jpg'
        # Post payload as multipart encoded image file with filename.
        requests.post(THE_URL, files={'file': (payload_filename, payload)})


问:
Ruby on Docker: determining which image I need
I've got a Sinatra app and I want to start doing development and production in Docker.  Seeing blogs like this: https://blog.codeship.com/build-minimal-docker-container-ruby-apps/ which advocate using slimmed-down Alpine image.  I understand the value of having a smaller image, however in my research on this subject I can't find a clear explanation on exactly how to know whether I will need, now or in the future, the full docker ruby image? Do I start with Alpine for dev and prod, and then assume that if I later need the bigger image, I'll switch to that?  What would be an example of the kind of new requirement that could come up that would require the larger docker ruby image?  thanks</p>

答:
Well it depends of your project's dependencies and of your workflow with your project. And so far you're the only one knowing that here

You can still install some though during the building process later with a Dockerfile, like the Ruby Package Manager (rpm) (which would probably be already present in many images though) and some ruby packages that wouldn't necessarly be present even if you use a larger ruby base image (therefore, a larger image wouldn't help for these dependencies, you'd still have to install them).

Other services (like databases for instance) could (and should) easily be handled by other containers such as mysql and therefore wouldn't require to expand your ruby image.

That question is very broad, therefore it's difficult to give a very specific answer.


问:
Why is the result of code snippt is not true according the define about classmethod in python(2.7)?
```<code>class Pizza(object):
   radius = 2
   @classmethod
   def get_radius(self):
      return self.radius
>>>print Pizza.get_radius is Pizza().get_radius
   False
</code>```

<p>I think the result is True,because the classmedthod belongs to the class object.  </p>

答:
```<code>>>> Pizza.get_radius()
2

>>> Pizza().get_radius
<bound method type.get_radius of <class 'Pizza'>>
</code>```

When you type Pizza.get_radius(),you call the function and you get your result.
When you type Pizza().get_radius ,first of all you initiate a new Pizza object and you don't call the function really.

Body:
class Pizza(object):
   radius = 2
   @classmethod
   def get_radius(self):
      return self.radius
>>>print Pizza.get_radius is Pizza().get_radius
   False

I think the result is True,because the classmedthod belongs to the class object.

Body:
>>> Pizza.get_radius()
2

>>> Pizza().get_radius
<bound method type.get_radius of <class 'Pizza'>>

When you type Pizza.get_radius(),you call the function and you get your result.
When you type Pizza().get_radius ,first of all you initiate a new Pizza object and you don't call the function really.


问:
StopPropagation in HTML with Angular
I am having a problem with stopPropagation, I don't know how to write in html and typescript for angular.
It opens the dialog but at the same time makes a propagation.

Here is my code in HTML:

```<code><label for="tab-two">PROJECTS
    <a class="plus" (click)="opentestdialog()">+</a>
</label>
</code>```

And here is my code in TypeScript:

```<code>opentestdialog() {
    this.dialog.open(TestdialogComponent);
}
</code>```

答:
thank's for your time but I have found the problem.
I just wrote.

```<code><a class="plus" (click)="opentestdialog(); false">+</a>
</code>```

Thank you so much, maybe it will be helpfull for someone.

Title: StopPropagation in HTML with Angular

Body:
I am having a problem with stopPropagation, I don't know how to write in html and typescript for angular.
It opens the dialog but at the same time makes a propagation.

Here is my code in HTML:

PROJECTS
    +

And here is my code in TypeScript:

opentestdialog() {
    this.dialog.open(TestdialogComponent);
}

Body:
thank's for your time but I have found the problem.
I just wrote.

<a class="plus" (click)="opentestdialog(); false">+</a>

Thank you so much, maybe it will be helpfull for someone.


问:
Python: If any value(Y) from a list is smaller than a constant, remove Y's corresponding index from another list
My question is: If any value from my aList is smaller than a constant variable, I want to take index of that lower value and delete sth from a bList corresponding to that index. Shortly, I want to compare all the values in aList to a constant and if there is a lower value in aList than constant. I will get the index of these and using that index making bList[index]= 0.

Example:

Lets say

```<code>constantToCompare=8
aList=[13, 12, 11, 9, 7]
bList=[100, 200, 300, 400, 500]
</code>```

So 5th element of aList is smaller than constantToCompare

I want to make bList = [100, 200, 300, 400, 0]

By the way this constantToCompare will increase by +1 up to some  so that a loop required to do this process.

Thank you.
I hope I am clear.

答:
Please go through below code .This is tested code hope this will solve your  problem.</p>

```<code>constantToCompare=8
aList=[13, 12, 11, 9, 7,1,2,2]
bList=[100, 200, 300, 400, 500,12,3,56]
for i in range(0,len(aList)):
    if(constantToCompare>aList[i]):
        bList[i]=0
print(bList)
</code>```

Body:
My question is: If any value from my aList is smaller than a constant variable, I want to take index of that lower value and delete sth from a bList corresponding to that index. Shortly, I want to compare all the values in aList to a constant and if there is a lower value in aList than constant. I will get the index of these and using that index making bList[index]= 0.

Example:

Lets say

constantToCompare=8
aList=[13, 12, 11, 9, 7]
bList=[100, 200, 300, 400, 500]

So 5th element of aList is smaller than constantToCompare

I want to make bList = [100, 200, 300, 400, 0]

By the way this constantToCompare will increase by +1 up to some  so that a loop required to do this process.

Thank you.
I hope I am clear.

Body:
Please go through below code .This is tested code hope this will solve your  problem.

constantToCompare=8
aList=[13, 12, 11, 9, 7,1,2,2]
bList=[100, 200, 300, 400, 500,12,3,56]
for i in range(0,len(aList)):
    if(constantToCompare>aList[i]):
        bList[i]=0
print(bList)


问:
xgboost: AttributeError: 'DMatrix' object has no attribute 'handle'
The problem is really strange, because that piece of worked pretty fine with other dataset.

The full code:

```<code>import numpy as np
import pandas as pd
import xgboost as xgb
from sklearn.cross_validation import train_test_split

# # Split the Learning Set
X_fit, X_eval, y_fit, y_eval= train_test_split(
    train, target, test_size=0.2, random_state=1
)

clf = xgb.XGBClassifier(missing=np.nan, max_depth=6,
                        n_estimators=5, learning_rate=0.15,
                        subsample=1, colsample_bytree=0.9, seed=1400)

# fitting
clf.fit(X_fit, y_fit, early_stopping_rounds=50, eval_metric="logloss", eval_set=[(X_eval, y_eval)])
#print y_pred
y_pred= clf.predict_proba(test)[:,1]
</code>```

Last line causes the error below (full output provided):

```<code>Will train until validation_0 error hasn't decreased in 50 rounds.
[0] validation_0-logloss:0.554366
[1] validation_0-logloss:0.451454
[2] validation_0-logloss:0.372142
[3] validation_0-logloss:0.309450
[4] validation_0-logloss:0.259002
Traceback (most recent call last):
  File "../src/script.py", line 57, in
    y_pred= clf.predict_proba(test)[:,1]
  File "/opt/conda/lib/python3.4/site-packages/xgboost-0.4-py3.4.egg/xgboost/sklearn.py", line 435, in predict_proba
    test_dmatrix = DMatrix(data, missing=self.missing)
  File "/opt/conda/lib/python3.4/site-packages/xgboost-0.4-py3.4.egg/xgboost/core.py", line 220, in __init__
    feature_types)
  File "/opt/conda/lib/python3.4/site-packages/xgboost-0.4-py3.4.egg/xgboost/core.py", line 147, in _maybe_pandas_data
    raise ValueError('DataFrame.dtypes for data must be int, float or bool')
ValueError: DataFrame.dtypes for data must be int, float or bool
Exception ignored in: >
Traceback (most recent call last):
  File "/opt/conda/lib/python3.4/site-packages/xgboost-0.4-py3.4.egg/xgboost/core.py", line 289, in __del__
    _check_call(_LIB.XGDMatrixFree(self.handle))
AttributeError: 'DMatrix' object has no attribute 'handle'
</code>```

What is wrong here? I have no idea how to fix that

UPD1: Acctually this is kaggle problem: https://www.kaggle.com/insaff/bnp-paribas-cardif-claims-management/xgboost

答:
You might also want to take a look at categorical variable solution as shown below:

```<code>for col in train.select_dtypes(include=['object']).columns:
    train[col] = train[col].astype('category')
    test[col] = test[col].astype('category')

# Encoding categorical features
for col in train.select_dtypes(include=['category']).columns:
    train[col] = train[col].cat.codes
    test[col] = test[col].cat.codes

train.fillna((-999), inplace=True)
test.fillna((-999), inplace=True)

train=np.array(train)
test=np.array(test)
</code>```

Body:
The problem is really strange, because that piece of worked pretty fine with other dataset.

The full code:

import numpy as np
import pandas as pd
import xgboost as xgb
from sklearn.cross_validation import train_test_split

# # Split the Learning Set
X_fit, X_eval, y_fit, y_eval= train_test_split(
    train, target, test_size=0.2, random_state=1
)

clf = xgb.XGBClassifier(missing=np.nan, max_depth=6,
                        n_estimators=5, learning_rate=0.15,
                        subsample=1, colsample_bytree=0.9, seed=1400)

# fitting
clf.fit(X_fit, y_fit, early_stopping_rounds=50, eval_metric="logloss", eval_set=[(X_eval, y_eval)])
#print y_pred
y_pred= clf.predict_proba(test)[:,1]

Last line causes the error below (full output provided):

Will train until validation_0 error hasn't decreased in 50 rounds.
[0] validation_0-logloss:0.554366
[1] validation_0-logloss:0.451454
[2] validation_0-logloss:0.372142
[3] validation_0-logloss:0.309450
[4] validation_0-logloss:0.259002
Traceback (most recent call last):
  File "../src/script.py", line 57, in
    y_pred= clf.predict_proba(test)[:,1]
  File "/opt/conda/lib/python3.4/site-packages/xgboost-0.4-py3.4.egg/xgboost/sklearn.py", line 435, in predict_proba
    test_dmatrix = DMatrix(data, missing=self.missing)
  File "/opt/conda/lib/python3.4/site-packages/xgboost-0.4-py3.4.egg/xgboost/core.py", line 220, in __init__
    feature_types)
  File "/opt/conda/lib/python3.4/site-packages/xgboost-0.4-py3.4.egg/xgboost/core.py", line 147, in _maybe_pandas_data
    raise ValueError('DataFrame.dtypes for data must be int, float or bool')
ValueError: DataFrame.dtypes for data must be int, float or bool
Exception ignored in: >
Traceback (most recent call last):
  File "/opt/conda/lib/python3.4/site-packages/xgboost-0.4-py3.4.egg/xgboost/core.py", line 289, in __del__
    _check_call(_LIB.XGDMatrixFree(self.handle))
AttributeError: 'DMatrix' object has no attribute 'handle'

What is wrong here? I have no idea how to fix that

UPD1: Acctually this is kaggle problem: https://www.kaggle.com/insaff/bnp-paribas-cardif-claims-management/xgboost

Body:
You might also want to take a look at categorical variable solution as shown below:

for col in train.select_dtypes(include=['object']).columns:
    train[col] = train[col].astype('category')
    test[col] = test[col].astype('category')

# Encoding categorical features
for col in train.select_dtypes(include=['category']).columns:
    train[col] = train[col].cat.codes
    test[col] = test[col].cat.codes

train.fillna((-999), inplace=True)
test.fillna((-999), inplace=True)

train=np.array(train)
test=np.array(test)


问:
Unity UI zoom in/out, adjust scroll position
I'm trying to make something similar to Paint in Unity.
I want to add functionality for zoom in/out. For this purpose, I've added paint area into into ScrollRect and change localScale of paint area on mouse wheel event.

```<code>var scrollDelta = Input.GetAxis("Mouse ScrollWheel");
var scale = _editableArea.localScale.x + scrollDelta;
_editableArea.localScale = new Vector3(scale, scale, scale);
</code>```

There are also additional checks, but I omit them.

For now I'm trying to adjust scrollbars position, so after zoom mouse will be under the same element it was before. And...
I stuck with formula to calculate new position of scrollbars. Probably, I reinvent the wheel and there is already a way to do this by native functions in Unity. Could you show me right way?

Thanks

答:
I've finally came to working solution, hope it'll help somebody:</p>

```<code>var scale = _editableArea.localScale.x;

//mousePosition contains position of mouse inside scaled area in percentages
var mousePosition = (Vector2) (Input.mousePosition - _editableArea.position) - _editableArea.rect.position * scale;
mousePosition.x /= _editableArea.rect.width * scale;
mousePosition.y /= _editableArea.rect.height * scale;

var contentSize = _scrollRect.content.rect;
var shiftX = -scaleDelta* contentSize.width * (mousePosition.x - 0.5f);
var shiftY = -scaleDelta* contentSize.height * (mousePosition.y - 0.5f);
var currPos = _scrollRect.content.localPosition;
_scrollRect.content.localPosition = new Vector3(currPos.x + shiftX, currPos.y + shiftY, currPos.z);
</code>```

Body:
I'm trying to make something similar to Paint in Unity.
I want to add functionality for zoom in/out. For this purpose, I've added paint area into into ScrollRect and change localScale of paint area on mouse wheel event.

var scrollDelta = Input.GetAxis("Mouse ScrollWheel");
var scale = _editableArea.localScale.x + scrollDelta;
_editableArea.localScale = new Vector3(scale, scale, scale);

There are also additional checks, but I omit them.

For now I'm trying to adjust scrollbars position, so after zoom mouse will be under the same element it was before. And...
I stuck with formula to calculate new position of scrollbars. Probably, I reinvent the wheel and there is already a way to do this by native functions in Unity. Could you show me right way?

Thanks

Body:
I've finally came to working solution, hope it'll help somebody:

var scale = _editableArea.localScale.x;

//mousePosition contains position of mouse inside scaled area in percentages
var mousePosition = (Vector2) (Input.mousePosition - _editableArea.position) - _editableArea.rect.position * scale;
mousePosition.x /= _editableArea.rect.width * scale;
mousePosition.y /= _editableArea.rect.height * scale;

var contentSize = _scrollRect.content.rect;
var shiftX = -scaleDelta* contentSize.width * (mousePosition.x - 0.5f);
var shiftY = -scaleDelta* contentSize.height * (mousePosition.y - 0.5f);
var currPos = _scrollRect.content.localPosition;
_scrollRect.content.localPosition = new Vector3(currPos.x + shiftX, currPos.y + shiftY, currPos.z);


问:
SQL Table Locking
I have an SQL Server locking question regarding an application we have in house. The application takes submissions of data and persists them into an SQL Server table. Each submission is also assigned a special catalog number (unrelated to the identity field in the table) which is a sequential alpha numeric number. These numbers are pulled from another table and are not generated at run time. So the steps are

Insert Data into Submission Table

Grab next Unassigned Catalog
Number from Catalog Table

Assign the Catalog Number to the
Submission in the Submission table

All these steps happen sequentially in the same stored procedure.

Its, rate but sometimes we manage to get two submission at the same second and they both get assigned the same Catalog Number which causes a localized version of the Apocalypse in our company for a small while.

What can we do to limit the over assignment of the catalog numbers?

答: I like araqnid's response.  You could also use an insert trigger on the submission table to accomplish this.  The trigger would be in the scope of the insert, and you would effectively embed the logic to assign the catalog_number in the trigger.  Just wanted to put your options up here.</p>

ContentLicense: CC BY-SA 2.5

Title: SQL Table Locking


问:
Can't find containerView Xcode 6.4
Today I tried to use a container view in Xcode and when I searched in the bar at the bottom of the Library menu, I could not find it. I have also searched through the entire list and can not find it.

Does anyone have any idea what might be occurring. I am using Xcode 6.4.

Any suggestions will be much appreciated.

答: Like kriztho said, container view won't be listed in the object library when viewing storyboard from the assistant editor for some stupid reason. I'm using Xcode 9, and this is still an issue. Right when I switched storyboard to the standard editor (Cmd + return on Mac), the container view was listed once again in the object library.</p>

Title: Can't find containerView Xcode 6.4


问:
DataTable add other column in table
I created this table and the result is as follows.

The code I used to create this table is as follows.
and it works for me correctly

```<code>DataTable dt1 = new DataTable("Table1");

dt1.Columns.Add("Num", typeof(Int32));
dt1.Columns.Add("date", typeof(string));
dt1.Columns.Add("name", typeof(string));
dt1.Columns.Add("product1a", typeof(Int32));
dt1.Columns.Add("product1b", typeof(Int32));
dt1.Columns.Add("total1", typeof(Int32));
dt1.Columns.Add("product2a", typeof(Int32));
dt1.Columns.Add("product2b", typeof(Int32));
dt1.Columns.Add("product2c", typeof(Int32));
dt1.Columns.Add("total2", typeof(Int32));

object[] o1 = { 1, "10/10/2017", "name 1", 1, 2, 3, 1, 1, 1, 3 };
object[] o2 = { 2, "20/10/2017", "name 2", 2, 2, 4, 2, 1, 2, 5 };
object[] o3 = { 3, "15/08/2017", "name 3", 1, 3, 4, 4, 0, 0, 4 };

dt1.Rows.Add(o1);
dt1.Rows.Add(o2);
dt1.Rows.Add(o3);

var grid = new GridView();
grid.DataSource = dt1;
grid.DataBind();

Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=ExportFetsVinculats.xls");
Response.ContentType = "application/ms-excel";

Response.Charset = "";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);

grid.RenderControl(htw);

Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
return Content("");
</code>```

up to here everything is correct, but you would have to implement the table of the following way.

Is it possible to add two more columns that act as headers?

答:
This is the code with the simple solution:

```<code>DataTable dt1 = new DataTable("Table1");

dt1.Columns.Add("Num", typeof(Int32));
dt1.Columns.Add("date", typeof(string));
dt1.Columns.Add("name", typeof(string));
dt1.Columns.Add("product1a", typeof(Int32));
dt1.Columns.Add("product1b", typeof(Int32));
dt1.Columns.Add("total1", typeof(Int32));
dt1.Columns.Add("product2a", typeof(Int32));
dt1.Columns.Add("product2b", typeof(Int32));
dt1.Columns.Add("product2c", typeof(Int32));
dt1.Columns.Add("total2", typeof(Int32));

object[] o1 = { 1, "10/10/2017", "name 1", 1, 2, 3, 1, 1, 1, 3 };
object[] o2 = { 2, "20/10/2017", "name 2", 2, 2, 4, 2, 1, 2, 5 };
object[] o3 = { 3, "15/08/2017", "name 3", 1, 3, 4, 4, 0, 0, 4 };

dt1.Rows.Add(o1);
dt1.Rows.Add(o2);
dt1.Rows.Add(o3);

GridView grid = new GridView();

grid.DataSource = dt1;
grid.DataBind();

GridView HeaderGrid = grid;
GridViewRow HeaderGridRow = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert);

TableCell HeaderCell = new TableCell();
HeaderCell.Text = "";
HeaderCell.ColumnSpan = 3;
HeaderGridRow.Cells.Add(HeaderCell);

HeaderCell = new TableCell();
HeaderCell.Text = "Head Products 1";
HeaderCell.ColumnSpan = 3;
HeaderCell.Font.Bold = true;
HeaderCell.HorizontalAlign = HorizontalAlign.Center;
HeaderGridRow.Cells.Add(HeaderCell);

HeaderCell = new TableCell();
HeaderCell.Text = "Head Products 2";
HeaderCell.ColumnSpan = 4;
HeaderCell.Font.Bold = true;
HeaderCell.HorizontalAlign = HorizontalAlign.Center;
HeaderGridRow.Cells.Add(HeaderCell);

HeaderGrid.Controls[0].Controls.AddAt(0, HeaderGridRow);

Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=ExportFetsVinculats.xls");
Response.ContentType = "application/ms-excel";

Response.Charset = "";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);

grid.RenderControl(htw);

Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
return Content("");
</code>```

Or:

```<code>public ActionResult retorna_excel()
{
     DataTable dt1 = new DataTable("Table1");

     dt1.Columns.Add("Num", typeof(Int32));
     dt1.Columns.Add("date", typeof(string));
     dt1.Columns.Add("name", typeof(string));
     dt1.Columns.Add("product1a", typeof(Int32));
     dt1.Columns.Add("product1b", typeof(Int32));
     dt1.Columns.Add("total1", typeof(Int32));
     dt1.Columns.Add("product2a", typeof(Int32));
     dt1.Columns.Add("product2b", typeof(Int32));
     dt1.Columns.Add("product2c", typeof(Int32));
     dt1.Columns.Add("total2", typeof(Int32));

     object[] o1 = { 1, "10/10/2017", "name 1", 1, 2, 3, 1, 1, 1, 3 };
     object[] o2 = { 2, "20/10/2017", "name 2", 2, 2, 4, 2, 1, 2, 5 };
     object[] o3 = { 3, "15/08/2017", "name 3", 1, 3, 4, 4, 0, 0, 4 };

     dt1.Rows.Add(o1);
     dt1.Rows.Add(o2);
     dt1.Rows.Add(o3);

     GridView grid = new GridView();

     grid.DataSource = dt1;
     grid.DataBind();

     List<Tuple<string, int, bool, HorizontalAlign>> list_header = new List<Tuple<string, int, bool, HorizontalAlign>>();
     list_header.Add(new Tuple<string, int, bool, HorizontalAlign>("", 3, false, HorizontalAlign.Center));
     list_header.Add(new Tuple<string, int, bool, HorizontalAlign>("Head Products 1", 3, true, HorizontalAlign.Center));
     list_header.Add(new Tuple<string, int, bool, HorizontalAlign>("Head Products 2", 4, true, HorizontalAlign.Center));

     get_header_table(grid, list_header);

     Response.ClearContent();
     Response.Buffer = true;
     Response.AddHeader("content-disposition", "attachment; filename=ExportFetsVinculats.xls");
     Response.ContentType = "application/ms-excel";

     Response.Charset = "";
     StringWriter sw = new StringWriter();
     HtmlTextWriter htw = new HtmlTextWriter(sw);

     grid.RenderControl(htw);

     Response.Output.Write(sw.ToString());
     Response.Flush();
     Response.End();
     return Content("");
}

private void get_header_table(GridView grid, List<Tuple<string, int, bool, HorizontalAlign>> list_header)
{
    GridView HeaderGrid = grid;
    GridViewRow HeaderGridRow = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert);

    TableCell HeaderCell = new TableCell();

    foreach (Tuple<string, int, bool, HorizontalAlign> item in list_header)
    {
        HeaderCell = new TableCell();
        HeaderCell.Text = item.Item1;
        HeaderCell.ColumnSpan = item.Item2;
        HeaderCell.Font.Bold = item.Item3;
        HeaderCell.HorizontalAlign = item.Item4;
        HeaderGridRow.Cells.Add(HeaderCell);
    }

    HeaderGrid.Controls[0].Controls.AddAt(0, HeaderGridRow);
}
</code>```

Title: DataTable add other column in table

Body:
I created this table and the result is as follows.

The code I used to create this table is as follows.
and it works for me correctly

DataTable dt1 = new DataTable("Table1");

dt1.Columns.Add("Num", typeof(Int32));
dt1.Columns.Add("date", typeof(string));
dt1.Columns.Add("name", typeof(string));
dt1.Columns.Add("product1a", typeof(Int32));
dt1.Columns.Add("product1b", typeof(Int32));
dt1.Columns.Add("total1", typeof(Int32));
dt1.Columns.Add("product2a", typeof(Int32));
dt1.Columns.Add("product2b", typeof(Int32));
dt1.Columns.Add("product2c", typeof(Int32));
dt1.Columns.Add("total2", typeof(Int32));

object[] o1 = { 1, "10/10/2017", "name 1", 1, 2, 3, 1, 1, 1, 3 };
object[] o2 = { 2, "20/10/2017", "name 2", 2, 2, 4, 2, 1, 2, 5 };
object[] o3 = { 3, "15/08/2017", "name 3", 1, 3, 4, 4, 0, 0, 4 };

dt1.Rows.Add(o1);
dt1.Rows.Add(o2);
dt1.Rows.Add(o3);

var grid = new GridView();
grid.DataSource = dt1;
grid.DataBind();

Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=ExportFetsVinculats.xls");
Response.ContentType = "application/ms-excel";

Response.Charset = "";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);

grid.RenderControl(htw);

Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
return Content("");

up to here everything is correct, but you would have to implement the table of the following way.

Is it possible to add two more columns that act as headers?

Body:
This is the code with the simple solution:

DataTable dt1 = new DataTable("Table1");

dt1.Columns.Add("Num", typeof(Int32));
dt1.Columns.Add("date", typeof(string));
dt1.Columns.Add("name", typeof(string));
dt1.Columns.Add("product1a", typeof(Int32));
dt1.Columns.Add("product1b", typeof(Int32));
dt1.Columns.Add("total1", typeof(Int32));
dt1.Columns.Add("product2a", typeof(Int32));
dt1.Columns.Add("product2b", typeof(Int32));
dt1.Columns.Add("product2c", typeof(Int32));
dt1.Columns.Add("total2", typeof(Int32));

object[] o1 = { 1, "10/10/2017", "name 1", 1, 2, 3, 1, 1, 1, 3 };
object[] o2 = { 2, "20/10/2017", "name 2", 2, 2, 4, 2, 1, 2, 5 };
object[] o3 = { 3, "15/08/2017", "name 3", 1, 3, 4, 4, 0, 0, 4 };

dt1.Rows.Add(o1);
dt1.Rows.Add(o2);
dt1.Rows.Add(o3);

GridView grid = new GridView();

grid.DataSource = dt1;
grid.DataBind();

GridView HeaderGrid = grid;
GridViewRow HeaderGridRow = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert);

TableCell HeaderCell = new TableCell();
HeaderCell.Text = "";
HeaderCell.ColumnSpan = 3;
HeaderGridRow.Cells.Add(HeaderCell);

HeaderCell = new TableCell();
HeaderCell.Text = "Head Products 1";
HeaderCell.ColumnSpan = 3;
HeaderCell.Font.Bold = true;
HeaderCell.HorizontalAlign = HorizontalAlign.Center;
HeaderGridRow.Cells.Add(HeaderCell);

HeaderCell = new TableCell();
HeaderCell.Text = "Head Products 2";
HeaderCell.ColumnSpan = 4;
HeaderCell.Font.Bold = true;
HeaderCell.HorizontalAlign = HorizontalAlign.Center;
HeaderGridRow.Cells.Add(HeaderCell);

HeaderGrid.Controls[0].Controls.AddAt(0, HeaderGridRow);

Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=ExportFetsVinculats.xls");
Response.ContentType = "application/ms-excel";

Response.Charset = "";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);

grid.RenderControl(htw);

Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
return Content("");

Or:

public ActionResult retorna_excel()
{
     DataTable dt1 = new DataTable("Table1");

     dt1.Columns.Add("Num", typeof(Int32));
     dt1.Columns.Add("date", typeof(string));
     dt1.Columns.Add("name", typeof(string));
     dt1.Columns.Add("product1a", typeof(Int32));
     dt1.Columns.Add("product1b", typeof(Int32));
     dt1.Columns.Add("total1", typeof(Int32));
     dt1.Columns.Add("product2a", typeof(Int32));
     dt1.Columns.Add("product2b", typeof(Int32));
     dt1.Columns.Add("product2c", typeof(Int32));
     dt1.Columns.Add("total2", typeof(Int32));

     object[] o1 = { 1, "10/10/2017", "name 1", 1, 2, 3, 1, 1, 1, 3 };
     object[] o2 = { 2, "20/10/2017", "name 2", 2, 2, 4, 2, 1, 2, 5 };
     object[] o3 = { 3, "15/08/2017", "name 3", 1, 3, 4, 4, 0, 0, 4 };

     dt1.Rows.Add(o1);
     dt1.Rows.Add(o2);
     dt1.Rows.Add(o3);

     GridView grid = new GridView();

     grid.DataSource = dt1;
     grid.DataBind();

     List<Tuple<string, int, bool, HorizontalAlign>> list_header = new List<Tuple<string, int, bool, HorizontalAlign>>();
     list_header.Add(new Tuple<string, int, bool, HorizontalAlign>("", 3, false, HorizontalAlign.Center));
     list_header.Add(new Tuple<string, int, bool, HorizontalAlign>("Head Products 1", 3, true, HorizontalAlign.Center));
     list_header.Add(new Tuple<string, int, bool, HorizontalAlign>("Head Products 2", 4, true, HorizontalAlign.Center));

     get_header_table(grid, list_header);

     Response.ClearContent();
     Response.Buffer = true;
     Response.AddHeader("content-disposition", "attachment; filename=ExportFetsVinculats.xls");
     Response.ContentType = "application/ms-excel";

     Response.Charset = "";
     StringWriter sw = new StringWriter();
     HtmlTextWriter htw = new HtmlTextWriter(sw);

     grid.RenderControl(htw);

     Response.Output.Write(sw.ToString());
     Response.Flush();
     Response.End();
     return Content("");
}

private void get_header_table(GridView grid, List<Tuple<string, int, bool, HorizontalAlign>> list_header)
{
    GridView HeaderGrid = grid;
    GridViewRow HeaderGridRow = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert);

    TableCell HeaderCell = new TableCell();

    foreach (Tuple<string, int, bool, HorizontalAlign> item in list_header)
    {
        HeaderCell = new TableCell();
        HeaderCell.Text = item.Item1;
        HeaderCell.ColumnSpan = item.Item2;
        HeaderCell.Font.Bold = item.Item3;
        HeaderCell.HorizontalAlign = item.Item4;
        HeaderGridRow.Cells.Add(HeaderCell);
    }

    HeaderGrid.Controls[0].Controls.AddAt(0, HeaderGridRow);
}

ContentLicense: CC BY-SA 4.0


问:
Multi Day Vehicle Routing - Use Vehicle With Smaller Day Index
I try to build a multi day vehicle routing based on optaplanner vehicle routing examples. I create VehicleDay class to model a vehicle for a single day trip. The VehicleDay class was a join of Vehicle object and Day object.
Here is the classes:

```<code>public class Day extends AbstractPersistable {
    protected int dayIndex;
    protected int dayInt;
    protected String day;

    // getter and setter methods
    ...
}

public class Vehicle extends AbstractPersistable {
    protected int capacity;
    protected Depot depot;

    // getter and setter methods
    ...
}

public class VehicleDay extends AbstractPersistable implements Standstill {
    protected Vehicle vehicle;
    protected Day day;

    // Shadow variables
    protected Customer nextCustomer;

    // getter and setter methods
    ...
}
</code>```

I moved the planning entity from Vehicle to VehicleDay. Then I tried to create a sample dataset (cvrp-72customers-edited.xml) which consist of 8 vehicle days and 71 customers. I take this sample dataset from cvrp-72customers and modify the vehicle capacity to only 3/4 (22000) of the original data. 8 vehicle days are consist of :

Vehicle id 1 with Day 1 (MONDAY)

Vehicle id 1 with Day 2 (TUESDAY)

Vehicle id 2 with Day 1 (MONDAY)

Vehicle id 2 with Day 2 (TUESDAY)

Vehicle id 3 with Day 1 (MONDAY)

Vehicle id 3 with Day 2 (TUESDAY)

Vehicle id 4 with Day 1 (MONDAY)

Vehicle id 4 with Day 2 (TUESDAY)

But when I tried to run it, the result is some vehicle from Day 1 are not used, and instead planner use some vehicle from Day 2 (cvrp-72customers-edited-solved.xml).  What I try to achieve is, the planner use the vehicle with Day 1 first, after all vehicle with Day 1 used, then planner start to use the vehicle on Day 2. I tried to use Comparator and created StandstillDifficultyComparator class :

```<code>public class StandstillDifficultyComparator implements Comparator<Standstill>, Serializable {

    @Override
    public int compare(Standstill a, Standstill b) {
        if (a instanceof Customer) {
            return new CompareToBuilder()
                    .append(((Customer)a).getId(), ((Customer)b).getId())
                    .toComparison();
        } else {
            return new CompareToBuilder()
                    .append(((VehicleDay)a).getDay().getDayIndex(), ((VehicleDay)b).getDay().getDayIndex())
                    .append(((VehicleDay)a).getId(), ((VehicleDay)b).getId())
                    .toComparison();
        }
    }

}
</code>```

Then at the unionMoveSelector configuration, I add my comparator class like this:

```<code><unionMoveSelector>
      <changeMoveSelector>
        <entitySelector>
            <cacheType>PHASE</cacheType>
            <selectionOrder>SORTED</selectionOrder>
            <sorterComparatorClass>org.optaplanner.examples.vehiclerouting.domain.solver.StandstillDifficultyComparator</sorterComparatorClass>
            <sorterOrder>ASCENDING</sorterOrder>
        </entitySelector>
      </changeMoveSelector>
      <swapMoveSelector>
        <entitySelector>
            <cacheType>PHASE</cacheType>
            <selectionOrder>SORTED</selectionOrder>
            <sorterComparatorClass>org.optaplanner.examples.vehiclerouting.domain.solver.StandstillDifficultyComparator</sorterComparatorClass>
            <sorterOrder>ASCENDING</sorterOrder>
        </entitySelector>
      </swapMoveSelector>
      <tailChainSwapMoveSelector>
        <entitySelector>
            <cacheType>PHASE</cacheType>
            <selectionOrder>SORTED</selectionOrder>
            <sorterComparatorClass>org.optaplanner.examples.vehiclerouting.domain.solver.StandstillDifficultyComparator</sorterComparatorClass>
            <sorterOrder>ASCENDING</sorterOrder>
        </entitySelector>
      </tailChainSwapMoveSelector>
      <subChainChangeMoveSelector>
        <selectReversingMoveToo>true</selectReversingMoveToo>
        <entitySelector>
            <cacheType>PHASE</cacheType>
            <selectionOrder>SORTED</selectionOrder>
            <sorterComparatorClass>org.optaplanner.examples.vehiclerouting.domain.solver.StandstillDifficultyComparator</sorterComparatorClass>
            <sorterOrder>ASCENDING</sorterOrder>
        </entitySelector>
      </subChainChangeMoveSelector>
      <subChainSwapMoveSelector>
        <selectReversingMoveToo>true</selectReversingMoveToo>
        <entitySelector>
            <cacheType>PHASE</cacheType>
            <selectionOrder>SORTED</selectionOrder>
            <sorterComparatorClass>org.optaplanner.examples.vehiclerouting.domain.solver.StandstillDifficultyComparator</sorterComparatorClass>
            <sorterOrder>ASCENDING</sorterOrder>
        </entitySelector>
      </subChainSwapMoveSelector>
    </unionMoveSelector>
</code>```

When I run it, an exception was throw like this:

```<code>Exception in thread "main" java.lang.IllegalArgumentException: Unmarshalling of solverConfigResource (org/optaplanner/examples/vehiclerouting/solver/vehicleRoutingSolverConfig.xml) fails on line number (53).
    at org.optaplanner.core.impl.solver.XStreamXmlSolverFactory.configure(XStreamXmlSolverFactory.java:123)
    at org.optaplanner.core.api.solver.SolverFactory.createFromXmlResource(SolverFactory.java:90)
    at org.optaplanner.examples.common.app.CommonApp.createSolver(CommonApp.java:102)
    at org.optaplanner.examples.common.app.CommonApp.createSolutionBusiness(CommonApp.java:97)
    at org.optaplanner.examples.common.app.CommonApp.init(CommonApp.java:84)
    at org.optaplanner.examples.common.app.CommonApp.init(CommonApp.java:80)
    at org.optaplanner.examples.vehiclerouting.app.VehicleRoutingApp.main(VehicleRoutingApp.java:34)
Caused by: " com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter$UnknownFieldException: No such field org.optaplanner.core.config.heuristic.selector.move.generic.chained.SubChainChangeMoveSelectorConfig.entitySelector
---- Debugging information ----
message             : No such field org.optaplanner.core.config.heuristic.selector.move.generic.chained.SubChainChangeMoveSelectorConfig.entitySelector
field               : entitySelector
class               : org.optaplanner.core.config.heuristic.selector.move.generic.chained.SubChainChangeMoveSelectorConfig
required-type       : org.optaplanner.core.config.heuristic.selector.move.generic.chained.SubChainChangeMoveSelectorConfig
converter-type      : com.thoughtworks.xstream.converters.reflection.ReflectionConverter
line number         : 53
class[1]            : org.optaplanner.core.config.heuristic.selector.move.composite.UnionMoveSelectorConfig
class[2]            : org.optaplanner.core.config.localsearch.LocalSearchPhaseConfig
class[3]            : org.optaplanner.core.config.solver.SolverConfig
version             : 1.4.10
-------------------------------
    at org.optaplanner.core.impl.solver.XStreamXmlSolverFactory.configure(XStreamXmlSolverFactory.java:123)
    at org.optaplanner.core.api.solver.SolverFactory.createFromXmlResource(SolverFactory.java:90)
    at org.optaplanner.examples.common.app.CommonApp.createSolver(CommonApp.java:102)
    at org.optaplanner.examples.common.app.CommonApp.createSolutionBusiness(CommonApp.java:97)
    at org.optaplanner.examples.common.app.CommonApp.init(CommonApp.java:84)
    at org.optaplanner.examples.common.app.CommonApp.init(CommonApp.java:80)
    at org.optaplanner.examples.vehiclerouting.app.VehicleRoutingApp.main(VehicleRoutingApp.java:34)
</code>```

How can I make planner use all the vehicle on day 1 first, and then after that use vehicle on day 2?

答: I think you need to create a scoring rule that rewards OptaPlanner for scheduling the days in order. So in the rule you could say that for every vehicle scheduled on day X deduct one point if  Day X-1 is not yet full. </p>

Body:
I try to build a multi day vehicle routing based on optaplanner vehicle routing examples. I create VehicleDay class to model a vehicle for a single day trip. The VehicleDay class was a join of Vehicle object and Day object.
Here is the classes:

public class Day extends AbstractPersistable {
    protected int dayIndex;
    protected int dayInt;
    protected String day;

    // getter and setter methods
    ...
}

public class Vehicle extends AbstractPersistable {
    protected int capacity;
    protected Depot depot;

    // getter and setter methods
    ...
}

public class VehicleDay extends AbstractPersistable implements Standstill {
    protected Vehicle vehicle;
    protected Day day;

    // Shadow variables
    protected Customer nextCustomer;

    // getter and setter methods
    ...
}

I moved the planning entity from Vehicle to VehicleDay. Then I tried to create a sample dataset (cvrp-72customers-edited.xml) which consist of 8 vehicle days and 71 customers. I take this sample dataset from cvrp-72customers and modify the vehicle capacity to only 3/4 (22000) of the original data. 8 vehicle days are consist of :

Vehicle id 1 with Day 1 (MONDAY)

Vehicle id 1 with Day 2 (TUESDAY)

Vehicle id 2 with Day 1 (MONDAY)

Vehicle id 2 with Day 2 (TUESDAY)

Vehicle id 3 with Day 1 (MONDAY)

Vehicle id 3 with Day 2 (TUESDAY)

Vehicle id 4 with Day 1 (MONDAY)

Vehicle id 4 with Day 2 (TUESDAY)

But when I tried to run it, the result is some vehicle from Day 1 are not used, and instead planner use some vehicle from Day 2 (cvrp-72customers-edited-solved.xml).  What I try to achieve is, the planner use the vehicle with Day 1 first, after all vehicle with Day 1 used, then planner start to use the vehicle on Day 2. I tried to use Comparator and created StandstillDifficultyComparator class :

public class StandstillDifficultyComparator implements Comparator<Standstill>, Serializable {

    @Override
    public int compare(Standstill a, Standstill b) {
        if (a instanceof Customer) {
            return new CompareToBuilder()
                    .append(((Customer)a).getId(), ((Customer)b).getId())
                    .toComparison();
        } else {
            return new CompareToBuilder()
                    .append(((VehicleDay)a).getDay().getDayIndex(), ((VehicleDay)b).getDay().getDayIndex())
                    .append(((VehicleDay)a).getId(), ((VehicleDay)b).getId())
                    .toComparison();
        }
    }

}

Then at the unionMoveSelector configuration, I add my comparator class like this:

<unionMoveSelector>
      <changeMoveSelector>
        <entitySelector>
            <cacheType>PHASE</cacheType>
            <selectionOrder>SORTED</selectionOrder>
            <sorterComparatorClass>org.optaplanner.examples.vehiclerouting.domain.solver.StandstillDifficultyComparator</sorterComparatorClass>
            <sorterOrder>ASCENDING</sorterOrder>
        </entitySelector>
      </changeMoveSelector>
      <swapMoveSelector>
        <entitySelector>
            <cacheType>PHASE</cacheType>
            <selectionOrder>SORTED</selectionOrder>
            <sorterComparatorClass>org.optaplanner.examples.vehiclerouting.domain.solver.StandstillDifficultyComparator</sorterComparatorClass>
            <sorterOrder>ASCENDING</sorterOrder>
        </entitySelector>
      </swapMoveSelector>
      <tailChainSwapMoveSelector>
        <entitySelector>
            <cacheType>PHASE</cacheType>
            <selectionOrder>SORTED</selectionOrder>
            <sorterComparatorClass>org.optaplanner.examples.vehiclerouting.domain.solver.StandstillDifficultyComparator</sorterComparatorClass>
            <sorterOrder>ASCENDING</sorterOrder>
        </entitySelector>
      </tailChainSwapMoveSelector>
      <subChainChangeMoveSelector>
        <selectReversingMoveToo>true</selectReversingMoveToo>
        <entitySelector>
            <cacheType>PHASE</cacheType>
            <selectionOrder>SORTED</selectionOrder>
            <sorterComparatorClass>org.optaplanner.examples.vehiclerouting.domain.solver.StandstillDifficultyComparator</sorterComparatorClass>
            <sorterOrder>ASCENDING</sorterOrder>
        </entitySelector>
      </subChainChangeMoveSelector>
      <subChainSwapMoveSelector>
        <selectReversingMoveToo>true</selectReversingMoveToo>
        <entitySelector>
            <cacheType>PHASE</cacheType>
            <selectionOrder>SORTED</selectionOrder>
            <sorterComparatorClass>org.optaplanner.examples.vehiclerouting.domain.solver.StandstillDifficultyComparator</sorterComparatorClass>
            <sorterOrder>ASCENDING</sorterOrder>
        </entitySelector>
      </subChainSwapMoveSelector>
    </unionMoveSelector>

When I run it, an exception was throw like this:

Exception in thread "main" java.lang.IllegalArgumentException: Unmarshalling of solverConfigResource (org/optaplanner/examples/vehiclerouting/solver/vehicleRoutingSolverConfig.xml) fails on line number (53).
    at org.optaplanner.core.impl.solver.XStreamXmlSolverFactory.configure(XStreamXmlSolverFactory.java:123)
    at org.optaplanner.core.api.solver.SolverFactory.createFromXmlResource(SolverFactory.java:90)
    at org.optaplanner.examples.common.app.CommonApp.createSolver(CommonApp.java:102)
    at org.optaplanner.examples.common.app.CommonApp.createSolutionBusiness(CommonApp.java:97)
    at org.optaplanner.examples.common.app.CommonApp.init(CommonApp.java:84)
    at org.optaplanner.examples.common.app.CommonApp.init(CommonApp.java:80)
    at org.optaplanner.examples.vehiclerouting.app.VehicleRoutingApp.main(VehicleRoutingApp.java:34)
Caused by: " com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter$UnknownFieldException: No such field org.optaplanner.core.config.heuristic.selector.move.generic.chained.SubChainChangeMoveSelectorConfig.entitySelector
---- Debugging information ----
message             : No such field org.optaplanner.core.config.heuristic.selector.move.generic.chained.SubChainChangeMoveSelectorConfig.entitySelector
field               : entitySelector
class               : org.optaplanner.core.config.heuristic.selector.move.generic.chained.SubChainChangeMoveSelectorConfig
required-type       : org.optaplanner.core.config.heuristic.selector.move.generic.chained.SubChainChangeMoveSelectorConfig
converter-type      : com.thoughtworks.xstream.converters.reflection.ReflectionConverter
line number         : 53
class[1]            : org.optaplanner.core.config.heuristic.selector.move.composite.UnionMoveSelectorConfig
class[2]            : org.optaplanner.core.config.localsearch.LocalSearchPhaseConfig
class[3]            : org.optaplanner.core.config.solver.SolverConfig
version             : 1.4.10
-------------------------------
    at org.optaplanner.core.impl.solver.XStreamXmlSolverFactory.configure(XStreamXmlSolverFactory.java:123)
    at org.optaplanner.core.api.solver.SolverFactory.createFromXmlResource(SolverFactory.java:90)
    at org.optaplanner.examples.common.app.CommonApp.createSolver(CommonApp.java:102)
    at org.optaplanner.examples.common.app.CommonApp.createSolutionBusiness(CommonApp.java:97)
    at org.optaplanner.examples.common.app.CommonApp.init(CommonApp.java:84)
    at org.optaplanner.examples.common.app.CommonApp.init(CommonApp.java:80)
    at org.optaplanner.examples.vehiclerouting.app.VehicleRoutingApp.main(VehicleRoutingApp.java:34)

How can I make planner use all the vehicle on day 1 first, and then after that use vehicle on day 2?


问:
Javascript change cursor icon to local icon.jpg
I am trying to change my cursor icon in a paint appliation using Javascript.
The jpeg icon which I want to use for that purpose is saved locally.
Can I use the following line to make this work?

```<code>document.body.style.cursor = "server/icon.jpg";
</code>```

How could I make it work using a url alternatively?

答:
Use the url property instead:

```<code>document.body.style.cursor = "url('server/icon.jpg'), auto"
</code>```

You may want to check MDN for documentation related with cursor css.

Body:
I am trying to change my cursor icon in a paint appliation using Javascript.
The jpeg icon which I want to use for that purpose is saved locally.
Can I use the following line to make this work?

document.body.style.cursor = "server/icon.jpg";

How could I make it work using a url alternatively?

Body:
Use the url property instead:

document.body.style.cursor = "url('server/icon.jpg'), auto"

You may want to check MDN for documentation related with cursor css.


问:
Create a grid inside a shapefile
I am trying to crate a grid inside a shapefile, something like this. However, I am unable to generate such grid. I was wondering if anyone has an idea on how to accomplish this.

Here is my code -

```<code>WWWL.Shape<- readOGR("E:/Juan Arango", "WWL_Commerce_OK")
WWWL.Shape
plot(WWWL.Shape)
proj4string(WWWL.Shape)

bb <- bbox(WWWL.Shape)
cs <- c(3.28084, 3.28084)*6000  # cell size
cc <- bb[, 1] + (cs/2)  # cell offset
cd <- ceiling(diff(t(bb))/cs)  # number of cells per direction
grd <- GridTopology(cellcentre.offset=cc, cellsize=cs, cells.dim=cd)
grd
sp_grd <- SpatialGridDataFrame(grd,
                               data=data.frame(id=1:prod(cd)),
                               proj4string=CRS(proj4string(WWWL.Shape)))
plot(sp_grd)
</code>```

Output of WWL.Shape

```<code>class       : SpatialPolygonsDataFrame
features    : 1
extent      : 334367, 334498.7, 4088915, 4089057  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=utm +zone=15 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0
variables   : 1
names       : Id
min values  :  0
max values  :  0
</code>```

答:
sf version

see rgdal version below

First, we start of with a shapefile. You might probably load it from any geospatial file using st_read.

```<code>library(sf)
library(raster)
library(ggplot2)

# load some spatial data. Administrative Boundary
shp <- getData('GADM', country = 'aut', level = 0)
shp <- st_as_sf(shp)
# ggplot() +
  # geom_sf(data = shp)
</code>```

Now the only thing you need is a combination of st_make_grid and st_intersection:

```<code>grid <- shp %>%
  st_make_grid(cellsize = 0.1, what = "centers") %>% # grid of points
  st_intersection(shp)                               # only within the polygon

# ggplot() +
  # geom_sf(data = shp) +
  # geom_sf(data = grid)
</code>```

rgdal and version

To create a grid of pixels you can use the sp::makegrid function.

Let's start with a reproducible example:

```<code>library(raster)
shp <- getData(country = "FRA", level = 0)
</code>```

So now we have a (multi)polygon. Let's transform it to a metric coordinate system (since your data and cell sizes were also metric):

```<code>shp <- spTransform(shp, CRSobj = "+proj=utm +zone=32 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0")
plot(shp)
</code>```

Afterwards, we create a grid within this polygon with your specified cell size.

```<code>cs <- c(3.28084, 3.28084)*6000
grdpts <- makegrid(shp, cellsize = cs)
</code>```

Then, we convert this grid (which basically is a matrix of center points) to a SpatialPoints object:

```<code>spgrd <- SpatialPoints(grdpts, proj4string = CRS(proj4string(shp)))
</code>```

This can then be converted into a SpatialPixels object. (Note: adding the subset [shp, ] only selects points within the original polygons)

```<code>spgrdWithin <- SpatialPixels(spgrd[shp,])
plot(spgrdWithin, add = T)
</code>```

If you need the grid as Polygons or Grid you can use

```<code>spgrdWithin <- as(spgrdWithin, "SpatialPolygons")
# or
spgrdWithin <- as(spgrdWithin, "SpatialGrid")
</code>```

Title: Create a grid inside a shapefile

Body:
I am trying to crate a grid inside a shapefile, something like this. However, I am unable to generate such grid. I was wondering if anyone has an idea on how to accomplish this.

Here is my code -

WWWL.Shape<- readOGR("E:/Juan Arango", "WWL_Commerce_OK")
WWWL.Shape
plot(WWWL.Shape)
proj4string(WWWL.Shape)

bb <- bbox(WWWL.Shape)
cs <- c(3.28084, 3.28084)*6000  # cell size
cc <- bb[, 1] + (cs/2)  # cell offset
cd <- ceiling(diff(t(bb))/cs)  # number of cells per direction
grd <- GridTopology(cellcentre.offset=cc, cellsize=cs, cells.dim=cd)
grd
sp_grd <- SpatialGridDataFrame(grd,
                               data=data.frame(id=1:prod(cd)),
                               proj4string=CRS(proj4string(WWWL.Shape)))
plot(sp_grd)

Output of WWL.Shape

class       : SpatialPolygonsDataFrame
features    : 1
extent      : 334367, 334498.7, 4088915, 4089057  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=utm +zone=15 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0
variables   : 1
names       : Id
min values  :  0
max values  :  0

Body:
sf version

see rgdal version below

First, we start of with a shapefile. You might probably load it from any geospatial file using st_read.

library(sf)
library(raster)
library(ggplot2)

# load some spatial data. Administrative Boundary
shp <- getData('GADM', country = 'aut', level = 0)
shp <- st_as_sf(shp)
# ggplot() +
  # geom_sf(data = shp)

Now the only thing you need is a combination of st_make_grid and st_intersection:

grid <- shp %>%
  st_make_grid(cellsize = 0.1, what = "centers") %>% # grid of points
  st_intersection(shp)                               # only within the polygon

# ggplot() +
  # geom_sf(data = shp) +
  # geom_sf(data = grid)

rgdal and version

To create a grid of pixels you can use the sp::makegrid function.

Let's start with a reproducible example:

library(raster)
shp <- getData(country = "FRA", level = 0)

So now we have a (multi)polygon. Let's transform it to a metric coordinate system (since your data and cell sizes were also metric):

shp <- spTransform(shp, CRSobj = "+proj=utm +zone=32 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0")
plot(shp)

Afterwards, we create a grid within this polygon with your specified cell size.

cs <- c(3.28084, 3.28084)*6000
grdpts <- makegrid(shp, cellsize = cs)

Then, we convert this grid (which basically is a matrix of center points) to a SpatialPoints object:

spgrd <- SpatialPoints(grdpts, proj4string = CRS(proj4string(shp)))

This can then be converted into a SpatialPixels object. (Note: adding the subset [shp, ] only selects points within the original polygons)

spgrdWithin <- SpatialPixels(spgrd[shp,])
plot(spgrdWithin, add = T)

If you need the grid as Polygons or Grid you can use

spgrdWithin <- as(spgrdWithin, "SpatialPolygons")
# or
spgrdWithin <- as(spgrdWithin, "SpatialGrid")


问:
How do I find all the US Census Tracts in a Place in R?
There are several R packages that make working with US Census data easier. The two I use most frequently are tigris(for loading the spatial data) and acs (for loading the tabular data).

However, one problem I keep running into is that I can't figure out an efficient, reliable way to determine all of the tracts (or block groups, zip codes, etc.) within a Place without leaving the R console.

For instance, if I wanted to work with census block data in Seattle I would begin by using tigris::tracts to download the spatial data for King County, WA:

```<code>library(tigris)
tr <- tigris::tracts(state = "WA", county = "King")
</code>```

But unfortunately there's no obvious way to subset this data to include only the tracts in Seattle.

```<code>glimpse(tr)
Observations: 398
Variables: 12
$ STATEFP  (chr) "53", "53", "53", "53", "53", "53", "53", ...
$ COUNTYFP (chr) "033", "033", "033", "033", "033", "033", ...
$ TRACTCE  (chr) "003800", "021500", "032704", "026200", "0...
$ GEOID    (chr) "53033003800", "53033021500", "53033032704...
$ NAME     (chr) "38", "215", "327.04", "262", "327.03", "3...
$ NAMELSAD (chr) "Census Tract 38", "Census Tract 215", "Ce...
$ MTFCC    (chr) "G5020", "G5020", "G5020", "G5020", "G5020...
$ FUNCSTAT (chr) "S", "S", "S", "S", "S", "S", "S", "S", "S...
$ ALAND    (dbl) 624606, 3485578, 17160645, 15242622, 10319...
$ AWATER   (dbl) 0, 412526, 447367, 526886, 175464, 0, 4360...
$ INTPTLAT (chr) "+47.6794093", "+47.7643848", "+47.4940877...
$ INTPTLON (chr) "-122.2955292", "-122.2737863", "-121.7717...
</code>```

Similarly, the acs package allows users to create subsets of census data using the geo.make function, but in my example this won't help me if I don't already have the list of tracts GEOIDs for all of the Seattle tracts.

For the record, I am aware that it is possible to determine this information elsewhere. This page in the Census.gov FAQ gives clear instructions on how to determine all the tracts in a given census Place. But given that this is a crucial step in many census-related analyses, it would be best if there was a convenient way to do it from the R console.

Thanks in advance.

Edit

Although this question deals with spatial data, I am most interested in finding a non-spatial solution. For instance, I would prefer to a solution that queries the Census API and returns the returns a vector of the desired GEOIDs to a solution that employs a spatial analysis tool (e.g., rgeos::intersects) to create the vector. Why? Because spatial approaches are simply more prone to error in this process and this is known information we're talking about, not something that needs to be inferred spatially.

答:
I often need the same kind of data so I wrote a R package to do this job. This package is called totalcensus. You can find it here https://github.com/GL-Li/totalcensus.

With this package, you can get data at tract, block group, or block level of towns, cities, counties, metro areas and all other geographic areas very easily. For example if you want to get the race data at block group level of various areas from 2011-2015 ACS 5-year survey, simply run code like below:

```<code>mixed <- read_acs5year(
    year = 2015,
    states = c("ut", "ri"),
    table_contents = c(
        "white = B02001_002",
        "black = B02001_003",
        "asian = B02001_005"
    ),
    areas = c(
        "Lincoln town, RI",
        "Salt Lake City city, UT",
        "Salt Lake City metro",
        "Kent county, RI",
        "COUNTY = UT001",
        "PLACE = UT62360"
    ),
    summary_level = "block group"
)
</code>```

It returns data like:

```<code>#                      area               GEOID        lon      lat state population white black asian GEOCOMP SUMLEV                                                             NAME
#    1:    Lincoln town, RI 15000US440070115001  -71.46686 41.94419    RI       1561  1386   128    47     all    150 Block Group 1, Census Tract 115, Providence County, Rhode Island
#    2:    Lincoln town, RI 15000US440070115002  -71.47159 41.96754    RI        916   806    97     0     all    150 Block Group 2, Census Tract 115, Providence County, Rhode Island
#    3:    Lincoln town, RI 15000US440070115003  -71.47820 41.96364    RI       2622  2373    77    86     all    150 Block Group 3, Census Tract 115, Providence County, Rhode Island
#    4:    Lincoln town, RI 15000US440070115004  -71.47830 41.97346    RI       1605  1516    43     0     all    150 Block Group 4, Census Tract 115, Providence County, Rhode Island
#    5:    Lincoln town, RI 15000US440070116001  -71.44665 41.93120    RI        948   764     0     0     all    150 Block Group 1, Census Tract 116, Providence County, Rhode Island
# ---
# 1129: Providence city, UT 15000US490050012011 -111.82424 41.69198    UT       2018  1877     0     0     all    150            Block Group 1, Census Tract 12.01, Cache County, Utah
# 1130: Providence city, UT 15000US490050012012 -111.80736 41.69323    UT       1486  1471     0     0     all    150            Block Group 2, Census Tract 12.01, Cache County, Utah
# 1131: Providence city, UT 15000US490050012013 -111.81310 41.65837    UT       1563  1440    15     0     all    150            Block Group 3, Census Tract 12.01, Cache County, Utah
# 1132: Providence city, UT 15000US490050012022 -111.85231 41.68674    UT       3894  3594     0     0     all    150            Block Group 2, Census Tract 12.02, Cache County, Utah
# 1133: Providence city, UT 15000US490059801001 -111.64525 41.67498    UT        118   118     0     0     all    150             Block Group 1, Census Tract 9801, Cache County, Utah
</code>```

Body:
There are several R packages that make working with US Census data easier. The two I use most frequently are tigris(for loading the spatial data) and acs (for loading the tabular data).

However, one problem I keep running into is that I can't figure out an efficient, reliable way to determine all of the tracts (or block groups, zip codes, etc.) within a Place without leaving the R console.

For instance, if I wanted to work with census block data in Seattle I would begin by using tigris::tracts to download the spatial data for King County, WA:

library(tigris)
tr <- tigris::tracts(state = "WA", county = "King")

But unfortunately there's no obvious way to subset this data to include only the tracts in Seattle.

glimpse(tr)
Observations: 398
Variables: 12
$ STATEFP  (chr) "53", "53", "53", "53", "53", "53", "53", ...
$ COUNTYFP (chr) "033", "033", "033", "033", "033", "033", ...
$ TRACTCE  (chr) "003800", "021500", "032704", "026200", "0...
$ GEOID    (chr) "53033003800", "53033021500", "53033032704...
$ NAME     (chr) "38", "215", "327.04", "262", "327.03", "3...
$ NAMELSAD (chr) "Census Tract 38", "Census Tract 215", "Ce...
$ MTFCC    (chr) "G5020", "G5020", "G5020", "G5020", "G5020...
$ FUNCSTAT (chr) "S", "S", "S", "S", "S", "S", "S", "S", "S...
$ ALAND    (dbl) 624606, 3485578, 17160645, 15242622, 10319...
$ AWATER   (dbl) 0, 412526, 447367, 526886, 175464, 0, 4360...
$ INTPTLAT (chr) "+47.6794093", "+47.7643848", "+47.4940877...
$ INTPTLON (chr) "-122.2955292", "-122.2737863", "-121.7717...

Similarly, the acs package allows users to create subsets of census data using the geo.make function, but in my example this won't help me if I don't already have the list of tracts GEOIDs for all of the Seattle tracts.

For the record, I am aware that it is possible to determine this information elsewhere. This page in the Census.gov FAQ gives clear instructions on how to determine all the tracts in a given census Place. But given that this is a crucial step in many census-related analyses, it would be best if there was a convenient way to do it from the R console.

Thanks in advance.

Edit

Although this question deals with spatial data, I am most interested in finding a non-spatial solution. For instance, I would prefer to a solution that queries the Census API and returns the returns a vector of the desired GEOIDs to a solution that employs a spatial analysis tool (e.g., rgeos::intersects) to create the vector. Why? Because spatial approaches are simply more prone to error in this process and this is known information we're talking about, not something that needs to be inferred spatially.

Body:
I often need the same kind of data so I wrote a R package to do this job. This package is called totalcensus. You can find it here https://github.com/GL-Li/totalcensus.

With this package, you can get data at tract, block group, or block level of towns, cities, counties, metro areas and all other geographic areas very easily. For example if you want to get the race data at block group level of various areas from 2011-2015 ACS 5-year survey, simply run code like below:

mixed <- read_acs5year(
    year = 2015,
    states = c("ut", "ri"),
    table_contents = c(
        "white = B02001_002",
        "black = B02001_003",
        "asian = B02001_005"
    ),
    areas = c(
        "Lincoln town, RI",
        "Salt Lake City city, UT",
        "Salt Lake City metro",
        "Kent county, RI",
        "COUNTY = UT001",
        "PLACE = UT62360"
    ),
    summary_level = "block group"
)

It returns data like:

#                      area               GEOID        lon      lat state population white black asian GEOCOMP SUMLEV                                                             NAME
#    1:    Lincoln town, RI 15000US440070115001  -71.46686 41.94419    RI       1561  1386   128    47     all    150 Block Group 1, Census Tract 115, Providence County, Rhode Island
#    2:    Lincoln town, RI 15000US440070115002  -71.47159 41.96754    RI        916   806    97     0     all    150 Block Group 2, Census Tract 115, Providence County, Rhode Island
#    3:    Lincoln town, RI 15000US440070115003  -71.47820 41.96364    RI       2622  2373    77    86     all    150 Block Group 3, Census Tract 115, Providence County, Rhode Island
#    4:    Lincoln town, RI 15000US440070115004  -71.47830 41.97346    RI       1605  1516    43     0     all    150 Block Group 4, Census Tract 115, Providence County, Rhode Island
#    5:    Lincoln town, RI 15000US440070116001  -71.44665 41.93120    RI        948   764     0     0     all    150 Block Group 1, Census Tract 116, Providence County, Rhode Island
# ---
# 1129: Providence city, UT 15000US490050012011 -111.82424 41.69198    UT       2018  1877     0     0     all    150            Block Group 1, Census Tract 12.01, Cache County, Utah
# 1130: Providence city, UT 15000US490050012012 -111.80736 41.69323    UT       1486  1471     0     0     all    150            Block Group 2, Census Tract 12.01, Cache County, Utah
# 1131: Providence city, UT 15000US490050012013 -111.81310 41.65837    UT       1563  1440    15     0     all    150            Block Group 3, Census Tract 12.01, Cache County, Utah
# 1132: Providence city, UT 15000US490050012022 -111.85231 41.68674    UT       3894  3594     0     0     all    150            Block Group 2, Census Tract 12.02, Cache County, Utah
# 1133: Providence city, UT 15000US490059801001 -111.64525 41.67498    UT        118   118     0     0     all    150             Block Group 1, Census Tract 9801, Cache County, Utah


问:
How to pass parameter to a function
I am new to javascript. In the below posted code, I created a function caleed "func", but as shown it does not accept any parameters. what i want to is, to make "func" accepts a parameter
that should be passed to "fs.readdir". in other words, it should be something like the following:

```<code>var func(path) = fs.readdir(path, (err, file)......);
</code>```

so that, each time i call func with a different parameter, fs.readdir should be called with the new parameter

how can i do that.

code:

```<code>var func = fs.readdir(p, (err, files) => {
if (err) {
console.log('ERROR: ' + err.message);
} else {
    files.filter( (file)=> {
      console.log(file + '____' + fs.statSync(file).size);
    });
  }
});
</code>```

答:
You should define func as a new function. You can use the arrow function syntax but using the function keyword is more explicit.

```<code>var func = function (path) {
    fs.readdir(path, (err, files) => {
    if (err) {
        console.log('ERROR: ' + err.message);
    } else {
        files.filter( (file)=> {
            console.log(file + '____' + fs.statSync(file).size);
        });
    }
    });
}
</code>```

Title: How to pass parameter to a function

Body:
I am new to javascript. In the below posted code, I created a function caleed "func", but as shown it does not accept any parameters. what i want to is, to make "func" accepts a parameter
that should be passed to "fs.readdir". in other words, it should be something like the following:

var func(path) = fs.readdir(path, (err, file)......);

so that, each time i call func with a different parameter, fs.readdir should be called with the new parameter

how can i do that.

code:

var func = fs.readdir(p, (err, files) => {
if (err) {
console.log('ERROR: ' + err.message);
} else {
    files.filter( (file)=> {
      console.log(file + '____' + fs.statSync(file).size);
    });
  }
});

Body:
You should define func as a new function. You can use the arrow function syntax but using the function keyword is more explicit.

var func = function (path) {
    fs.readdir(path, (err, files) => {
    if (err) {
        console.log('ERROR: ' + err.message);
    } else {
        files.filter( (file)=> {
            console.log(file + '____' + fs.statSync(file).size);
        });
    }
    });
}


问:
How do I dynamically set validations fields in vuelidate
I'm using VueJS2 with vuelidate library. I can validate the fields based on the validation objects. The validation will execute during computed time. But My validations objects is fixed, instead of dynamic. I have some fields will hide based on the selection.

```<code>import { validationMixin } from 'vuelidate'
import { required, maxLength, email } from 'vuelidate/lib/validators'

export default {
mixins: [validationMixin],
validations: {
  company_name: { required },
  company_position_title: { required }
},
methods: {
  submit(){
    this.$v.touch();
    if(this.$v.$invalid == false){
      // All validation fields success
    }
  }
}
}
</code>```

HTML

```<code><v-select
  label="Who are you?"
  v-model="select" // can be 'company' or 'others'
  :items="items"
  :error-messages="selectErrors"
  @change="$v.select.$touch();resetInfoFields();"
  @blur="$v.select.$touch()"
  required
></v-select>

<v-text-field
  label="Company Name"
  v-model="company_name"
  :error-messages="companyNameErrors"
  :counter="150"
  @input="$v.companyName.$touch()"
  @blur="$v.companyName.$touch()"
  v-show="select == 'Company'"
></v-text-field>

<v-text-field
  label="Company Position Title"
  v-model="company_position_title"
  :error-messages="companyPositionErrors"
  :counter="150"
  @input="$v.companyPosition.$touch()"
  @blur="$v.companyPosition.$touch()"
  v-show="select == 'Company'"
></v-text-field>

<v-btn @click="submit">submit</v-btn>
</code>```

Problem

When I select 'other' option and click submit, the this.$v.$invalid is still true. It should be false as there is no validation fields required.
When I select 'company', that two fields must required and validated.

答:
you need a dynamic validation schema

```<code>validations () {
  if (!this.select === 'company') {
    return {
      company_name: { required },
      company_position_title: { required }
    }
  }
}
</code>```

More info: Dynamic validation schema

Body:
I'm using VueJS2 with vuelidate library. I can validate the fields based on the validation objects. The validation will execute during computed time. But My validations objects is fixed, instead of dynamic. I have some fields will hide based on the selection.

import { validationMixin } from 'vuelidate'
import { required, maxLength, email } from 'vuelidate/lib/validators'

export default {
mixins: [validationMixin],
validations: {
  company_name: { required },
  company_position_title: { required }
},
methods: {
  submit(){
    this.$v.touch();
    if(this.$v.$invalid == false){
      // All validation fields success
    }
  }
}
}

HTML

<v-select
  label="Who are you?"
  v-model="select" // can be 'company' or 'others'
  :items="items"
  :error-messages="selectErrors"
  @change="$v.select.$touch();resetInfoFields();"
  @blur="$v.select.$touch()"
  required
></v-select>

<v-text-field
  label="Company Name"
  v-model="company_name"
  :error-messages="companyNameErrors"
  :counter="150"
  @input="$v.companyName.$touch()"
  @blur="$v.companyName.$touch()"
  v-show="select == 'Company'"
></v-text-field>

<v-text-field
  label="Company Position Title"
  v-model="company_position_title"
  :error-messages="companyPositionErrors"
  :counter="150"
  @input="$v.companyPosition.$touch()"
  @blur="$v.companyPosition.$touch()"
  v-show="select == 'Company'"
></v-text-field>

<v-btn @click="submit">submit</v-btn>

Problem

When I select 'other' option and click submit, the this.$v.$invalid is still true. It should be false as there is no validation fields required.
When I select 'company', that two fields must required and validated.

Body:
you need a dynamic validation schema

validations () {
  if (!this.select === 'company') {
    return {
      company_name: { required },
      company_position_title: { required }
    }
  }
}

More info: Dynamic validation schema


问:
UnitofWork [aspnetboilerplate] Transaction Management
I am currently working on implementing aspnetboilerplate's transaction management

Below is the method I am using to insert a order and products associated with the order

```<code>public class OrderController
{
    IOrderAppService _orderAppService;
    public OrderController(IOrderAppService orderAppService)
    {
        _orderAppService = orderAppService;
    }
    public void TestOrder()
    {
        _orderAppService.TestTransaction();
    }
}

public class OrderAppService : IOrderAppService
{
    //repositories are injected here

    public void TestTransaction()
    {
        //Created 'order' and 'products' here

        //Committing the created objects
        CommitOrderTransaction();

    }

    private void CommitOrderTransaction()
    {
        using (var unitOfWork = _unitOfWorkManager.Begin())
        {
            //Inserts the Order record
            CommitInsertOrderHeader(); // Order Header is saved in database by using SaveChanges() method

            //Inserts the Product records associated with OrderId
            CommitInsertOrderDetails();

            unitOfWork.Complete();
        }
    }
}
</code>```

As the aspnetboilerplate documentation tells that,
"if current unit of work is transactional, all changes in the transaction are rolled back if an exception occurs, even saved changes."

In my case when an exception occurs on inserting the OrderDetails, I would like the header record to be rolled back as well but I still have the Order header record in database.

答: If you are calling SaveChanges() twice and you aren't using a TransactionScope across both, then you won't be able to rollback the first call.  I don't know what UnitOfWork is doing here, but if the DbContext you are working with isn't being used in that UoW, then nothing is going to happen.  DbContext is technically its own Unit of Work already.  You should be adding Orders and Order Details to the same DbContext and calling SaveChanges() just once.  Then you'd be able to roll back both in that scenario.</p>

Body:
I am currently working on implementing aspnetboilerplate's transaction management

Below is the method I am using to insert a order and products associated with the order

public class OrderController
{
    IOrderAppService _orderAppService;
    public OrderController(IOrderAppService orderAppService)
    {
        _orderAppService = orderAppService;
    }
    public void TestOrder()
    {
        _orderAppService.TestTransaction();
    }
}

public class OrderAppService : IOrderAppService
{
    //repositories are injected here

    public void TestTransaction()
    {
        //Created 'order' and 'products' here

        //Committing the created objects
        CommitOrderTransaction();

    }

    private void CommitOrderTransaction()
    {
        using (var unitOfWork = _unitOfWorkManager.Begin())
        {
            //Inserts the Order record
            CommitInsertOrderHeader(); // Order Header is saved in database by using SaveChanges() method

            //Inserts the Product records associated with OrderId
            CommitInsertOrderDetails();

            unitOfWork.Complete();
        }
    }
}

As the aspnetboilerplate documentation tells that,
"if current unit of work is transactional, all changes in the transaction are rolled back if an exception occurs, even saved changes."

In my case when an exception occurs on inserting the OrderDetails, I would like the header record to be rolled back as well but I still have the Order header record in database.


问:
Apply customized width to a prime-ng p-column in html template in angular
I want to apply a different width to each column of my columns using [style] as shown in the example, I tried [style]="{'width.px':'column.length + 10'}" but column.length isn't working on the template, below an example of my template

```<code><p-column *ngFor="let column of columns"
        [field]="column"
        [header]="label[column] ? label[column] : column"
        [style]="{'width.px':'column.length + 10'}"></p-column>
</code>```

thanks in advance.

答:
I think it is generally not a good idea to put a lot of evaluations in the template :

In your component you can map your columns and do your calculations there, assuming columns is and array of objects . You map and add a new property columnWidth  where you do your do your evaluations.

```<code>//assuming you have an array of objects.
    var columns = [
      {
      id : 1},
      {id: 2},
      {id :3}
    ];

        var columnWithExtraProperty = columns.map( (column : any) => {
          return{
            ...column,
            columnWidth : column.length  + 10 + 'px'
          }

        });

       // console.log(columnWithExtraProperty);
</code>```

Then try this in the template :

```<code><p-column *ngFor="let column of columnWithExtraProperty"
        [field]="column"
        [header]="label[column] ? label[column] : column"
        [style]="{'width.px':column.columnWidth}"></p-column>
</code>```

Body:
I want to apply a different width to each column of my columns using [style] as shown in the example, I tried [style]="{'width.px':'column.length + 10'}" but column.length isn't working on the template, below an example of my template

thanks in advance.

Body:
I think it is generally not a good idea to put a lot of evaluations in the template :

In your component you can map your columns and do your calculations there, assuming columns is and array of objects . You map and add a new property columnWidth  where you do your do your evaluations.

//assuming you have an array of objects.
    var columns = [
      {
      id : 1},
      {id: 2},
      {id :3}
    ];

        var columnWithExtraProperty = columns.map( (column : any) => {
          return{
            ...column,
            columnWidth : column.length  + 10 + 'px'
          }

        });

       // console.log(columnWithExtraProperty);

Then try this in the template :

<p-column *ngFor="let column of columnWithExtraProperty"
        [field]="column"
        [header]="label[column] ? label[column] : column"
        [style]="{'width.px':column.columnWidth}"></p-column>