问:
Compare different ArrayList elements
Ok so, I have several text documents containing similar format as below:

```<code>    497 Q0 WTX091-B06-138 0 0.415344133 GROUP001
    497 Q0 WTX091-B09-92 1 0.362342072 GROUP001
    497 Q0 WTX091-B09-76 2 0.354034424 GROUP001
    497 Q0 WTX091-B09-57 3 0.349649535 GROUP001
    497 Q0 WTX091-B43-79 4 0.3217919 GROUP001
    497 Q0 WTX091-B43-56 5 0.321450733 GROUP001
    .
    .
    .
    (actually there are 1000 lines in each text document)
</code>```

I have stored each document into an arraylist separated by line. The challenging part is that I have to look for the third column (WTX***-B**-**) in each document and if they are the same then I have to add their fifth (0.3********) column together.

How do I compare the third column in different text documents?

答:
As I assume your text file lines are space separated, this should do it. It assumes you are using Java 8. You could easily upgrade this solution to read the files directly, since Java 8 provides Files.lines - method.

So the solution splits every line of your document by a whitespace separator.

```<code>List<String> list = Arrays.asList(
            "497 Q0 WTX091-B06-138 0 0.415344133 GROUP001",
            "497 Q0 WTX091-B09-92 1 0.362342072 GROUP001",
            "497 Q0 WTX091-B09-76 2 0.354034424 GROUP001",
            "497 Q0 WTX091-B09-57 3 0.349649535 GROUP001",
            "497 Q0 WTX091-B43-79 4 0.3217919 GROUP001",
            "497 Q0 WTX091-B43-56 5 0.321450733 GROUP001");

Map<String, Double> sumMap = list.stream()
            .map(s -> s.split("\\s+"))
            .collect(groupingBy(s -> s[2],
                 summingDouble(s -> Double.valueOf(s[4]))));

System.out.println(sumMap);
</code>```

To process all files, you could read all files contents into list or you begin with a stream of files and do a flatMap for each files contents.

Title: Compare different ArrayList elements

Body:
Ok so, I have several text documents containing similar format as below:

    497 Q0 WTX091-B06-138 0 0.415344133 GROUP001
    497 Q0 WTX091-B09-92 1 0.362342072 GROUP001
    497 Q0 WTX091-B09-76 2 0.354034424 GROUP001
    497 Q0 WTX091-B09-57 3 0.349649535 GROUP001
    497 Q0 WTX091-B43-79 4 0.3217919 GROUP001
    497 Q0 WTX091-B43-56 5 0.321450733 GROUP001
    .
    .
    .
    (actually there are 1000 lines in each text document)

I have stored each document into an arraylist separated by line. The challenging part is that I have to look for the third column (WTX***-B**-**) in each document and if they are the same then I have to add their fifth (0.3********) column together.

How do I compare the third column in different text documents?

Body:
As I assume your text file lines are space separated, this should do it. It assumes you are using Java 8. You could easily upgrade this solution to read the files directly, since Java 8 provides Files.lines - method.

So the solution splits every line of your document by a whitespace separator.

List<String> list = Arrays.asList(
            "497 Q0 WTX091-B06-138 0 0.415344133 GROUP001",
            "497 Q0 WTX091-B09-92 1 0.362342072 GROUP001",
            "497 Q0 WTX091-B09-76 2 0.354034424 GROUP001",
            "497 Q0 WTX091-B09-57 3 0.349649535 GROUP001",
            "497 Q0 WTX091-B43-79 4 0.3217919 GROUP001",
            "497 Q0 WTX091-B43-56 5 0.321450733 GROUP001");

Map<String, Double> sumMap = list.stream()
            .map(s -> s.split("\\s+"))
            .collect(groupingBy(s -> s[2],
                 summingDouble(s -> Double.valueOf(s[4]))));

System.out.println(sumMap);

To process all files, you could read all files contents into list or you begin with a stream of files and do a flatMap for each files contents.


来源: stackexchange

问:
JQuery ajax call default timeout value
I got a bug report that I can't duplicate, but ajax-call timeout is the current best guess.

So I'm trying to find out the default value for timeout of a jQuery $.ajax() call. Anybody have an idea? Couldn't find it in jQuery documentation.

答:
The XMLHttpRequest.timeout property represents a number of milliseconds a request can take before automatically being terminated. The default value is 0, which means there is no timeout. An important note  the timeout shouldn't be used for synchronous XMLHttpRequests requests, used in a document environment or it will throw an InvalidAccessError exception. You may not use a timeout for synchronous requests with an owning window.

IE10 and 11 do not support synchronous requests, with support being phased out in other browsers too. This is due to detrimental effects resulting from making them.

More info can be found here.

ContentLicense: CC BY-SA 4.0

Title: JQuery ajax call default timeout value

ContentLicense: CC BY-SA 3.0


问:
Open windows form from link in outlook?
I would please like to find out how I can launch a windows form written in c# from a link in outlook. Changes in my db will send n mail from which my application should be able to open so that the user can upload documents to a shared folder on a server.

Can someone please advise me on this thank you

答:
You can register application with your custom protocol. In example, you can create protocol myAppProtocoland associate it with your application (ie. c:\apps\myApp.exe). Then, you can send link in mail which looks like myAppProtocol:something. When user clicks on that link, it will open your application with passed parameter something.

Take a look at following resources:

MSDN article

SO question

or use third-party solution

Title: Open windows form from link in outlook?


问:
How can I check if a letter in a string is uppercase using the power of TypeScript?
My question is very brief. I am new to TypeScript, been searching around here and there but didn't find yet an answer.

I have this code written in C#

```<code>private bool MaskValidateChar(KeyPressEventArgs e, int index)
{
    string c = e.KeyChar.ToString();
    if (Char.IsUpper(c[0])) //Need to this with TypeScript :-\
    {
        //Do Something....
    }
}
</code>```

When I convert above code into Type script, I can simply write a code something like if (c[0] == c[0].toUpperCase())

I just need to know whether there is a built in method in Typescript to check whether a given character is uppercase. I couldn't find such thing on the internet, but I doubt it.

Please advise.

答:
No. JavaScript (which is what TypeScript compiles to) does not have a built-in method similar to char.IsUpper/char.IsLower. You will have to compare it like:

```<code>c[0] === c[0].toUpperCase() // c[0] is uppercase
c[0] === c[0].toLowerCase() // c[0] is lowercase
</code>```

Body:
My question is very brief. I am new to TypeScript, been searching around here and there but didn't find yet an answer.

I have this code written in C#

private bool MaskValidateChar(KeyPressEventArgs e, int index)
{
    string c = e.KeyChar.ToString();
    if (Char.IsUpper(c[0])) //Need to this with TypeScript :-\
    {
        //Do Something....
    }
}

When I convert above code into Type script, I can simply write a code something like if (c[0] == c[0].toUpperCase())

I just need to know whether there is a built in method in Typescript to check whether a given character is uppercase. I couldn't find such thing on the internet, but I doubt it.

Please advise.

Body:
No. JavaScript (which is what TypeScript compiles to) does not have a built-in method similar to char.IsUpper/char.IsLower. You will have to compare it like:

c[0] === c[0].toUpperCase() // c[0] is uppercase
c[0] === c[0].toLowerCase() // c[0] is lowercase


问:
Laravel: How to insert multi select2 dropdown selected data to mysql database?
I am trying to insert data into database. But i don't know how to insert multi select data into the mysql database.</p>

答:
Let's say you've got a table that have 2 columns :

```<code>CREATE TABLE table(
    id int not null primary key auto_increment,
    selectValue /*Whatever*/
)
</code>```

And you've got a select named "MultipleValues[]" (<select name='MultipleValues[]' multiple='multiple'/>) so at your controller :

```<code>public function update(Request $request)
{
    $insertData = [];
    $multipleValues = $request->get('MultipleValues');
    foreach($multipleValues as $value)
    {
        $insertData['selectValue'] = $value;
    }
    DB::table('table')->insert($insertData);
}
</code>```

Body:
Let's say you've got a table that have 2 columns :

CREATE TABLE table(
    id int not null primary key auto_increment,
    selectValue /*Whatever*/
)

And you've got a select named "MultipleValues[]" (<select name='MultipleValues[]' multiple='multiple'/>) so at your controller :

public function update(Request $request)
{
    $insertData = [];
    $multipleValues = $request->get('MultipleValues');
    foreach($multipleValues as $value)
    {
        $insertData['selectValue'] = $value;
    }
    DB::table('table')->insert($insertData);
}


问:
Country state concept in codeigniter
This is My View Page

```<code> <select name="category" value="c_id" onChange="getsubcategorydetails(this.value)" style="display:">
                                                   <option value="" selected="selected" >Select Categories</option>
            <?php if(isset($categories)) : foreach($categories as $row) :?>
                <option value=<?php echo $row->c_id; ?>><?php echo $row->c_name; ?></option>
                <?php endforeach;?>
                <?php else :
                endif;
                ?>
          </select>
                 </div>
               </div>
                 </div>
                </div>
                                <div class="row">
                                   <div class="input-field col s12">
                                   <tr>

                                            <td>

    <select name=" select id="subcategory">
 <option value="" selected="selected" >Select Sub Category</option>
 <?php foreach($sub_categories as $stt): ?>
  <option value="<?php echo $stt->s_c_id; ?>"><?php echo $stt->s_c_name; ?></option>
 <?php endforeach; ?>
 </select>
                                                </select></td>
                                                </tr>
</code>```

This is My Controller

```<code>    public function getsubcategorydetails($c_id)
    {

      $c_id = $this->uri->segment(3);
      //  echo  $c_id;
        $data['sub_categories'] = $this->m_category->getsubcategorydetails($c_id);
        //print_r($data['sub_category']);
       $this->load->view('my_admin/newpost_1',$data);
    }
</code>```

This is My Model

```<code>    function getsubcategorydetails($c_id='')
 {
    $this -> db -> select('*');
    $this -> db -> where('c_id', $c_id);
    $query = $this -> db -> get('subcategories');
    return $query->result();
 }
</code>```

When i Click Category Select Box The Values returned from Controller ... But It Not Displayed On View ... What's Wrong With That .... Thanks In Advance

答: Better option is Fetch data using AJAX and Append that to dependent select box  onChange Event.</p>

Title: Country state concept in codeigniter

Body:
This is My View Page

 <select name="category" value="c_id" onChange="getsubcategorydetails(this.value)" style="display:">
                                                   <option value="" selected="selected" >Select Categories</option>
            <?php if(isset($categories)) : foreach($categories as $row) :?>
                <option value=<?php echo $row->c_id; ?>><?php echo $row->c_name; ?></option>
                <?php endforeach;?>
                <?php else :
                endif;
                ?>
          </select>

    <select name=" select id="subcategory">
 <option value="" selected="selected" >Select Sub Category</option>
 <?php foreach($sub_categories as $stt): ?>
  <option value="<?php echo $stt->s_c_id; ?>"><?php echo $stt->s_c_name; ?></option>
 <?php endforeach; ?>
 </select>
                                                </select>

This is My Controller

    public function getsubcategorydetails($c_id)
    {

      $c_id = $this->uri->segment(3);
      //  echo  $c_id;
        $data['sub_categories'] = $this->m_category->getsubcategorydetails($c_id);
        //print_r($data['sub_category']);
       $this->load->view('my_admin/newpost_1',$data);
    }

This is My Model

    function getsubcategorydetails($c_id='')
 {
    $this -> db -> select('*');
    $this -> db -> where('c_id', $c_id);
    $query = $this -> db -> get('subcategories');
    return $query->result();
 }

When i Click Category Select Box The Values returned from Controller ... But It Not Displayed On View ... What's Wrong With That .... Thanks In Advance


问:
How to compile c program with HDF5 source code?
I have the specific requirement where I want to compile and execute some code which has HDF5 dependencies.
I don't want to use the hdf5 compiler, but I want to compile the HDF5 Source code.

I am very new on how to link the HDF5 to my C program. Please can you explain in detail how to do so, such that I can execute this program using c compiler and linking the source files which is downloaded from here.

Sample C program -

```<code>/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * Copyright by The HDF Group.                                               *
 * Copyright by the Board of Trustees of the University of Illinois.         *
 * All rights reserved.                                                      *
 *                                                                           *
 * This file is part of HDF5.  The full HDF5 copyright notice, including     *
 * terms governing use, modification, and redistribution, is contained in    *
 * the files COPYING and Copyright.html.  COPYING can be found at the root   *
 * of the source code distribution tree; Copyright.html can be found at the  *
 * root level of an installed copy of the electronic HDF5 document set and   *
 * is linked from the top-level documents page.  It can also be found at     *
 * http://hdfgroup.org/HDF5/doc/Copyright.html.  If you do not have          *
 * access to either file, you may request a copy from help@hdfgroup.org.     *
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

/*
 *  This example illustrates how to create a dataset that is a 4 x 6
 *  array.  It is used in the HDF5 Tutorial.
 */

#include "hdf5.h"
#define FILE "dset.h5"

int main() {

   hid_t       file_id, dataset_id, dataspace_id;  /* identifiers */
   hsize_t     dims[2];
   herr_t      status;

   /* Create a new file using default properties. */
   file_id = H5Fcreate(FILE, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);

   /* Create the data space for the dataset. */
   dims[0] = 4;
   dims[1] = 6;
   dataspace_id = H5Screate_simple(2, dims, NULL);

   /* Create the dataset. */
   dataset_id = H5Dcreate2(file_id, "/dset", H5T_STD_I32BE, dataspace_id,
                          H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);

   /* End access to the dataset and release resources used by it. */
   status = H5Dclose(dataset_id);

   /* Terminate access to the data space. */
   status = H5Sclose(dataspace_id);

   /* Close the file. */
   status = H5Fclose(file_id);
}
</code>```

答:
For compiling, it is necessary to have the -I flag point to the include directory of HDF5. For a system install, it will typically be /usr/include but there are many variations depending on whether HDF5 is installed in serial or parallel, 32/64-bit, etc. For linking the -L and -l flags are the ones that matter. -L should point to the directory holding the .so,.dll or .dylib files of the HDF5 libraries (again, there can be variations) and -l simply gives the library names, -lhdf5 and others (I believe that -lz and -lm are almost always used). If you use the high-level library, -lhdf5_hl is needed.

The simplest way to check those flags is to call

```<code>h5cc -show
</code>```

that will list them all.

PS: you can compile and link in a single step (from .c to executable file) or first compile (.c to .o) then link (.o to executable file). In the first case all -I, -L and -l flags are needed.

Body:
I have the specific requirement where I want to compile and execute some code which has HDF5 dependencies.
I don't want to use the hdf5 compiler, but I want to compile the HDF5 Source code.

I am very new on how to link the HDF5 to my C program. Please can you explain in detail how to do so, such that I can execute this program using c compiler and linking the source files which is downloaded from here.

Sample C program -

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * Copyright by The HDF Group.                                               *
 * Copyright by the Board of Trustees of the University of Illinois.         *
 * All rights reserved.                                                      *
 *                                                                           *
 * This file is part of HDF5.  The full HDF5 copyright notice, including     *
 * terms governing use, modification, and redistribution, is contained in    *
 * the files COPYING and Copyright.html.  COPYING can be found at the root   *
 * of the source code distribution tree; Copyright.html can be found at the  *
 * root level of an installed copy of the electronic HDF5 document set and   *
 * is linked from the top-level documents page.  It can also be found at     *
 * http://hdfgroup.org/HDF5/doc/Copyright.html.  If you do not have          *
 * access to either file, you may request a copy from help@hdfgroup.org.     *
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

/*
 *  This example illustrates how to create a dataset that is a 4 x 6
 *  array.  It is used in the HDF5 Tutorial.
 */

#include "hdf5.h"
#define FILE "dset.h5"

int main() {

   hid_t       file_id, dataset_id, dataspace_id;  /* identifiers */
   hsize_t     dims[2];
   herr_t      status;

   /* Create a new file using default properties. */
   file_id = H5Fcreate(FILE, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);

   /* Create the data space for the dataset. */
   dims[0] = 4;
   dims[1] = 6;
   dataspace_id = H5Screate_simple(2, dims, NULL);

   /* Create the dataset. */
   dataset_id = H5Dcreate2(file_id, "/dset", H5T_STD_I32BE, dataspace_id,
                          H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);

   /* End access to the dataset and release resources used by it. */
   status = H5Dclose(dataset_id);

   /* Terminate access to the data space. */
   status = H5Sclose(dataspace_id);

   /* Close the file. */
   status = H5Fclose(file_id);
}

Body:
For compiling, it is necessary to have the -I flag point to the include directory of HDF5. For a system install, it will typically be /usr/include but there are many variations depending on whether HDF5 is installed in serial or parallel, 32/64-bit, etc. For linking the -L and -l flags are the ones that matter. -L should point to the directory holding the .so,.dll or .dylib files of the HDF5 libraries (again, there can be variations) and -l simply gives the library names, -lhdf5 and others (I believe that -lz and -lm are almost always used). If you use the high-level library, -lhdf5_hl is needed.

The simplest way to check those flags is to call

h5cc -show

that will list them all.

PS: you can compile and link in a single step (from .c to executable file) or first compile (.c to .o) then link (.o to executable file). In the first case all -I, -L and -l flags are needed.


问:
How does cloud foundry's domain and DNS domain connected?
When I read cloud foundry document about Domains, it mentions that the term of "Domain" differs from its common use and is specific to Cloud Foundry.

THen when I am using PWS, cf domains shows:

```<code>name            status   type
cfapps.io       shared
cf-tcpapps.io   shared   tcp
</code>```

I assume the domains here are Cloud foundry domains. I can access my app by below URL:

```<code>https://browser-kissable-dizziness.cfapps.io
</code>```

here "cfapps.io" I guess it's a DNS domain name because it's on the public internet.

how do the cloud foundry domain and the DNS domain name connect? or is there a connection between them? or they are just two things which have the same name?

if I want to have multiple share HTTP cloud foundry domains? I can use cf create-shared-domain shared-domain.example.com to create one, but how can I make it usable by public internet?

Guess I want to understand the basic knowledge about how to make a cloud foundry instance accessible from the internet.

答:
You would need to set wildcard DNS entry on your dns servers (*.yourdomain) pointing to the go-router/routers/LB VIP of them on your Cloud Foundry platform. https://docs.cloudfoundry.org/concepts/architecture/router.html

Then you can create-shared-domain and assign application routes from it.

Body:
When I read cloud foundry document about Domains, it mentions that the term of "Domain" differs from its common use and is specific to Cloud Foundry.

THen when I am using PWS, cf domains shows:

name            status   type
cfapps.io       shared
cf-tcpapps.io   shared   tcp

I assume the domains here are Cloud foundry domains. I can access my app by below URL:

https://browser-kissable-dizziness.cfapps.io

here "cfapps.io" I guess it's a DNS domain name because it's on the public internet.

how do the cloud foundry domain and the DNS domain name connect? or is there a connection between them? or they are just two things which have the same name?

if I want to have multiple share HTTP cloud foundry domains? I can use cf create-shared-domain shared-domain.example.com to create one, but how can I make it usable by public internet?

Guess I want to understand the basic knowledge about how to make a cloud foundry instance accessible from the internet.


问:
Order model objects by properties of nullable child objects in QueryDSL
My requirement is to retrieve all image (WAHImage) objects whether the specimen (SpecimenImpl) is null or not, whether the taxon name (WACensusImpl) is null or not, and ordering the result by specimen name or taxon name, if available, and displaying the image objects with a null specimen and a null taxon name first.

Using the code below, I get an error No property coalesce(wAHimage found for type WAHImage.

It is pretty clear that my use case is not (yet) fully supported in QueryDSL, namely the ability to query for an entity and order the resulting objects by properties of its nullable child objects. This is because QueryDSL uses CROSS JOINs rather than LEFT JOINs, and you can't order by child object properties with a CROSS JOIN. This seems to be the source of my frustration, and I'm now looking around for other solutions, rather than sticking with QueryDSL.

Spring Data JPA Repository:

```<code>public interface ImageRepository extends JpaRepository<WAHImage, Long>,
        QueryDslPredicateExecutor<WAHImage> {
    Page<WAHImage> findAllByIsDeleted(boolean isDeleted, Pageable page);
}
</code>```

Spring Boot (1.5.1) Service, which has ImageRepository autowired in its constructor:

```<code>@Service
public class ImageService {
    private ImageRepository imageRepository;
    public Page<WAHImage> get(Pageable pageable) {
        return imageRepository.findAllByIsDeleted(false, ImagePredicates.orderByName(pageable));
    }
</code>```

ImagePredicates.orderByName(Pageable):

```<code>static QPageRequest orderByName(Pageable page) {

    QWAHImage image = QWAHImage.wAHImage;
    QWACensusImpl name = image.census;
    QSpecimenImpl specimen = image.specimen;
    OrderSpecifier genus = name.name1.coalesce(specimen.genus).asc();
    OrderSpecifier species = name.name2.coalesce(specimen.species).asc();
    OrderSpecifier rank = name.rank4.coalesce(
            name.rank3.coalesce(specimen.rank)).asc();
    OrderSpecifier infraspecies = name.name4.coalesce(
            name.name3.coalesce(specimen.infraspecies)).asc();

    OrderSpecifier[] sort = new OrderSpecifier[] {
            genus, species, rank, infraspecies
    };

    return new QPageRequest(page.getPageNumber(), page.getPageSize(), sort);
}
</code>```

Controller:

```<code>@Controller
public class ImageController {
    @GetMapping("/list")
    public String list(Pageable pageable, Model model) {
        Page<WAHImage> searchResult = imageService.get(pageable);
    }
}
</code>```

The error:

```<code>org.springframework.data.mapping.PropertyReferenceException: No property coalesce(wAHImage found for type WAHImage!
at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:77)
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:329)
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:309)
at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:272)
at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:243)
at org.springframework.data.jpa.repository.query.QueryUtils.toJpaOrder(QueryUtils.java:542)
at org.springframework.data.jpa.repository.query.QueryUtils.toOrders(QueryUtils.java:496)
at org.springframework.data.jpa.repository.query.JpaQueryCreator.complete(JpaQueryCreator.java:195)
at org.springframework.data.jpa.repository.query.JpaQueryCreator.complete(JpaQueryCreator.java:143)
at org.springframework.data.jpa.repository.query.JpaQueryCreator.complete(JpaQueryCreator.java:52)
at org.springframework.data.repository.query.parser.AbstractQueryCreator.createQuery(AbstractQueryCreator.java:88)
at org.springframework.data.jpa.repository.query.PartTreeJpaQuery$QueryPreparer.createQuery(PartTreeJpaQuery.java:144)
at org.springframework.data.jpa.repository.query.PartTreeJpaQuery.doCreateQuery(PartTreeJpaQuery.java:79)
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.createQuery(AbstractJpaQuery.java:190)
at org.springframework.data.jpa.repository.query.JpaQueryExecution$PagedExecution.doExecute(JpaQueryExecution.java:184)
at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:85)
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:116)
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:106)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:483)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:461)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:133)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:57)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
at com.sun.proxy.$Proxy143.findAllByIsDeleted(Unknown Source)
at x.y.z.image.ImageService.get(ImageService.java:120)
at x.y.z.image.ImageService$$FastClassBySpringCGLIB$$6d3a7999.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:652)
at x.y.z.image.ImageService$$EnhancerBySpringCGLIB$$21037cfe.get(<generated>)
at x.y.z.controller.image.ImageController.list(ImageController.java:132)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
</code>```

Relevant parts of WAHImage model class.

```<code>@Entity
@Table(name = "image")
public class WAHImage extends PersistentImpl {
    private WACensusImpl census = new WACensusImpl();
    private SpecimenImpl specimen = new SpecimenImpl();
    private boolean isDeleted = Boolean.FALSE;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "census_id", nullable = true)
    public WACensusImpl getCensus() {
        return census;
    }

    public void setCensus(WACensusImpl census) {
        this.census = census;
    }

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "specimen_id", nullable = true)
    public SpecimenImpl getSpecimen() {
        return specimen;
    }

    public void setSpecimen(SpecimenImpl specimen) {
        this.specimen = specimen;
    }

    @Column(name = "is_deleted")
    public boolean getIsDeleted() {
        return isDeleted;
    }

    public void setIsDeleted(boolean isDeleted) {
        this.isDeleted = isDeleted;
    }

}
</code>```

Relevant parts of QWAHImage QueryDSL class.

```<code>/**
 * QWAHImage is a Querydsl query type for WAHImage
 */
@Generated("com.querydsl.codegen.EntitySerializer")
public class QWAHImage extends EntityPathBase<WAHImage> {

    public static final QWAHImage wAHImage = new QWAHImage("wAHImage");

    public final x.y.z.db.impl.QPersistentImpl _super = new x.y.z.db.impl.QPersistentImpl(this);

    public final x.y.z.reference.census.impl.QWACensusImpl census;

    //inherited
    public final NumberPath<Long> id = _super.id;

    public final BooleanPath isDeleted = createBoolean("isDeleted");

    public final x.y.z.reference.specimen.impl.QSpecimenImpl specimen;
}
</code>```

Relevant parts of QWACensusImpl:

```<code>/**
 * QWACensusImpl is a Querydsl query type for WACensusImpl
 */
@Generated("com.querydsl.codegen.EntitySerializer")
public class QWACensusImpl extends EntityPathBase<WACensusImpl> {

    public static final QWACensusImpl wACensusImpl = new QWACensusImpl("wACensusImpl");

    public final x.y.z.db.impl.QPersistentWithIDImpl _super = new x.y.z.db.impl.QPersistentWithIDImpl(this);

    //inherited
    public final NumberPath<Long> id = _super.id;

    public final StringPath name1 = createString("name1");

    public final StringPath name2 = createString("name2");

    public final StringPath name3 = createString("name3");

    public final StringPath name4 = createString("name4");

    // extraneous parts omitted.
}
</code>```

答:
After some extensive background research, it appears that my use case has a long history and remains a common one.

To fix this, I could (a) get access to the EntityManager in Spring Data JPA and from there build the query with LEFT JOINs, after that I should be able to use the COALESCE keyword in ImagePredicates.orderByName(Pageable).

Alternatively, (and the approach I've decided to use) I use a Spring Data @Query on ImageRepository.findAllByIsDeleted(boolean, Pageable):

```<code>public interface ImageRepository extends JpaRepository<WAHImage, Long>,
        QueryDslPredicateExecutor<WAHImage> {
    @Query("select i from WAHImage i " +
            "left join i.specimen s " +
            "left join i.census c " +
            "left join i.author a " +
            "left join i.copyright co " +
            "left join i.allowedUse au " +
            "where i.isDeleted = ?1 " +
            "order by coalesce(s.genus, c.name1) asc, " +
            "coalesce(s.species, c.name2) asc, " +
            "coalesce(s.infraspecies, c.name4, c.name3) asc")
    Page<WAHImage> findAllByIsDeleted(boolean isDeleted, Pageable page);
}
</code>```

Body:
My requirement is to retrieve all image (WAHImage) objects whether the specimen (SpecimenImpl) is null or not, whether the taxon name (WACensusImpl) is null or not, and ordering the result by specimen name or taxon name, if available, and displaying the image objects with a null specimen and a null taxon name first.

Using the code below, I get an error No property coalesce(wAHimage found for type WAHImage.

It is pretty clear that my use case is not (yet) fully supported in QueryDSL, namely the ability to query for an entity and order the resulting objects by properties of its nullable child objects. This is because QueryDSL uses CROSS JOINs rather than LEFT JOINs, and you can't order by child object properties with a CROSS JOIN. This seems to be the source of my frustration, and I'm now looking around for other solutions, rather than sticking with QueryDSL.

Spring Data JPA Repository:

public interface ImageRepository extends JpaRepository<WAHImage, Long>,
        QueryDslPredicateExecutor<WAHImage> {
    Page<WAHImage> findAllByIsDeleted(boolean isDeleted, Pageable page);
}

Spring Boot (1.5.1) Service, which has ImageRepository autowired in its constructor:

@Service
public class ImageService {
    private ImageRepository imageRepository;
    public Page<WAHImage> get(Pageable pageable) {
        return imageRepository.findAllByIsDeleted(false, ImagePredicates.orderByName(pageable));
    }

ImagePredicates.orderByName(Pageable):

static QPageRequest orderByName(Pageable page) {

    QWAHImage image = QWAHImage.wAHImage;
    QWACensusImpl name = image.census;
    QSpecimenImpl specimen = image.specimen;
    OrderSpecifier genus = name.name1.coalesce(specimen.genus).asc();
    OrderSpecifier species = name.name2.coalesce(specimen.species).asc();
    OrderSpecifier rank = name.rank4.coalesce(
            name.rank3.coalesce(specimen.rank)).asc();
    OrderSpecifier infraspecies = name.name4.coalesce(
            name.name3.coalesce(specimen.infraspecies)).asc();

    OrderSpecifier[] sort = new OrderSpecifier[] {
            genus, species, rank, infraspecies
    };

    return new QPageRequest(page.getPageNumber(), page.getPageSize(), sort);
}

Controller:

@Controller
public class ImageController {
    @GetMapping("/list")
    public String list(Pageable pageable, Model model) {
        Page<WAHImage> searchResult = imageService.get(pageable);
    }
}

The error:

org.springframework.data.mapping.PropertyReferenceException: No property coalesce(wAHImage found for type WAHImage!
at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:77)
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:329)
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:309)
at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:272)
at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:243)
at org.springframework.data.jpa.repository.query.QueryUtils.toJpaOrder(QueryUtils.java:542)
at org.springframework.data.jpa.repository.query.QueryUtils.toOrders(QueryUtils.java:496)
at org.springframework.data.jpa.repository.query.JpaQueryCreator.complete(JpaQueryCreator.java:195)
at org.springframework.data.jpa.repository.query.JpaQueryCreator.complete(JpaQueryCreator.java:143)
at org.springframework.data.jpa.repository.query.JpaQueryCreator.complete(JpaQueryCreator.java:52)
at org.springframework.data.repository.query.parser.AbstractQueryCreator.createQuery(AbstractQueryCreator.java:88)
at org.springframework.data.jpa.repository.query.PartTreeJpaQuery$QueryPreparer.createQuery(PartTreeJpaQuery.java:144)
at org.springframework.data.jpa.repository.query.PartTreeJpaQuery.doCreateQuery(PartTreeJpaQuery.java:79)
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.createQuery(AbstractJpaQuery.java:190)
at org.springframework.data.jpa.repository.query.JpaQueryExecution$PagedExecution.doExecute(JpaQueryExecution.java:184)
at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:85)
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:116)
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:106)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:483)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:461)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:133)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:57)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
at com.sun.proxy.$Proxy143.findAllByIsDeleted(Unknown Source)
at x.y.z.image.ImageService.get(ImageService.java:120)
at x.y.z.image.ImageService$$FastClassBySpringCGLIB$$6d3a7999.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:652)
at x.y.z.image.ImageService$$EnhancerBySpringCGLIB$$21037cfe.get(<generated>)
at x.y.z.controller.image.ImageController.list(ImageController.java:132)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)

Relevant parts of WAHImage model class.

@Entity
@Table(name = "image")
public class WAHImage extends PersistentImpl {
    private WACensusImpl census = new WACensusImpl();
    private SpecimenImpl specimen = new SpecimenImpl();
    private boolean isDeleted = Boolean.FALSE;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "census_id", nullable = true)
    public WACensusImpl getCensus() {
        return census;
    }

    public void setCensus(WACensusImpl census) {
        this.census = census;
    }

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "specimen_id", nullable = true)
    public SpecimenImpl getSpecimen() {
        return specimen;
    }

    public void setSpecimen(SpecimenImpl specimen) {
        this.specimen = specimen;
    }

    @Column(name = "is_deleted")
    public boolean getIsDeleted() {
        return isDeleted;
    }

    public void setIsDeleted(boolean isDeleted) {
        this.isDeleted = isDeleted;
    }

}

Relevant parts of QWAHImage QueryDSL class.

/**
 * QWAHImage is a Querydsl query type for WAHImage
 */
@Generated("com.querydsl.codegen.EntitySerializer")
public class QWAHImage extends EntityPathBase<WAHImage> {

    public static final QWAHImage wAHImage = new QWAHImage("wAHImage");

    public final x.y.z.db.impl.QPersistentImpl _super = new x.y.z.db.impl.QPersistentImpl(this);

    public final x.y.z.reference.census.impl.QWACensusImpl census;

    //inherited
    public final NumberPath<Long> id = _super.id;

    public final BooleanPath isDeleted = createBoolean("isDeleted");

    public final x.y.z.reference.specimen.impl.QSpecimenImpl specimen;
}

Relevant parts of QWACensusImpl:

/**
 * QWACensusImpl is a Querydsl query type for WACensusImpl
 */
@Generated("com.querydsl.codegen.EntitySerializer")
public class QWACensusImpl extends EntityPathBase<WACensusImpl> {

    public static final QWACensusImpl wACensusImpl = new QWACensusImpl("wACensusImpl");

    public final x.y.z.db.impl.QPersistentWithIDImpl _super = new x.y.z.db.impl.QPersistentWithIDImpl(this);

    //inherited
    public final NumberPath<Long> id = _super.id;

    public final StringPath name1 = createString("name1");

    public final StringPath name2 = createString("name2");

    public final StringPath name3 = createString("name3");

    public final StringPath name4 = createString("name4");

    // extraneous parts omitted.
}

Body:
After some extensive background research, it appears that my use case has a long history and remains a common one.

To fix this, I could (a) get access to the EntityManager in Spring Data JPA and from there build the query with LEFT JOINs, after that I should be able to use the COALESCE keyword in ImagePredicates.orderByName(Pageable).

Alternatively, (and the approach I've decided to use) I use a Spring Data @Query on ImageRepository.findAllByIsDeleted(boolean, Pageable):

public interface ImageRepository extends JpaRepository<WAHImage, Long>,
        QueryDslPredicateExecutor<WAHImage> {
    @Query("select i from WAHImage i " +
            "left join i.specimen s " +
            "left join i.census c " +
            "left join i.author a " +
            "left join i.copyright co " +
            "left join i.allowedUse au " +
            "where i.isDeleted = ?1 " +
            "order by coalesce(s.genus, c.name1) asc, " +
            "coalesce(s.species, c.name2) asc, " +
            "coalesce(s.infraspecies, c.name4, c.name3) asc")
    Page<WAHImage> findAllByIsDeleted(boolean isDeleted, Pageable page);
}


问:
How to declare a parent application context
I find myself using two identical beans in my applicationContext.xml and my applicationContext-test.xml. I'd like my test context to be able to inherit from my app context, to avoid repeating myself.

I've seen plenty of material indicating that you can declare a parent application context and reference beans from that context, but I can't find a useful example. Can anyone help?

Update
As some background info, my normal application context is being loaded in web.xml:

```<code><context-param>
    <description>Application Contexts for Spring</description>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/classes/applicationContext.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</code>```

My test application context is loaded in my unit tests:

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/applicationContext-test.xml")
</code>```

So let's say I have a bean in my regular context:

```<code><bean name="someBean" class="com.foo.MyClass" />
</code>```

Then, in my test application context, I'd like to refer to this bean. How do I do it?

Update

Per skaffman's suggestion, I've moved the bean into a SharedBeans.xml file and imported it into my applicationContext.xml. However, this causes a SAXParser exception:

```<code>org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Failed to import bean definitions from URL location [classpath:SharedBeans.xml]
Offending resource: ServletContext resource [/WEB-INF/classes/applicationContext.xml]; nested exception is org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 1 in XML document from class path resource [SharedBeans.xml] is invalid; nested exception is org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the declaration of element 'bean'.
    at org.springframework.beans.factory.parsing.FailFastProblemReporter.error(FailFastProblemReporter.java:68)
</code>```

I can't be sure what I'm doing wrong. The bean was working fine in my context file, and all I did was cut and paste into the new file. Here are the contents of SharedBeans.xml in its entirety:

```<code><bean name="properties" class="com.foo.Properties">
    <constructor-arg><value>${module.name}</value></constructor-arg>
    <constructor-arg><value>${businessUnit}</value></constructor-arg>
    <constructor-arg><value>${product}</value></constructor-arg>
    <constructor-arg><value>${env}</value></constructor-arg>
    <constructor-arg><value>${machineName}</value></constructor-arg>
    <constructor-arg><value>${collectionSet.company}</value></constructor-arg>
    <constructor-arg><value>${route.tag}</value></constructor-arg>
    <constructor-arg><value>${timeout}</value></constructor-arg>
</bean>
</code>```

答:
This doesn't strike me as a particularly good use-case for a parent context, which is useful mainly to set up a hierarchy (e.g. one root webapp context, multiple child servlet contexts).

For your situation, it's going to be simpler and easier to understand if you just extract the common bean definitions into a separate file, and then <import> them into each context file that needs it.  You could do this with parent-child contexts, but it's going to be harder to understand, unnecessarily so.

OK, so an example, put your shared bean definition into a file called shared-beans.xml, and put it (for now) at the top-level of your classpath, containing:

```<code><bean name="someBean" class="com.foo.MyClass" />
</code>```

Then, inside applicationContext-test.xml and /WEB-INF/classes/applicationContext.xml, add the following:

```<code><import resource="classpath:/shared-beans.xml" />
</code>```

All of the bean definitions in shared-beans.xml will now be imported into each app context. You don't get a third app-context by doing this, you just import the bean definitions from another file.

ContentLicense: CC BY-SA 2.5

Body:
I find myself using two identical beans in my applicationContext.xml and my applicationContext-test.xml. I'd like my test context to be able to inherit from my app context, to avoid repeating myself.

I've seen plenty of material indicating that you can declare a parent application context and reference beans from that context, but I can't find a useful example. Can anyone help?

Update
As some background info, my normal application context is being loaded in web.xml:

<context-param>
    <description>Application Contexts for Spring</description>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/classes/applicationContext.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

My test application context is loaded in my unit tests:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/applicationContext-test.xml")

So let's say I have a bean in my regular context:

<bean name="someBean" class="com.foo.MyClass" />

Then, in my test application context, I'd like to refer to this bean. How do I do it?

Update

Per skaffman's suggestion, I've moved the bean into a SharedBeans.xml file and imported it into my applicationContext.xml. However, this causes a SAXParser exception:

org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Failed to import bean definitions from URL location [classpath:SharedBeans.xml]
Offending resource: ServletContext resource [/WEB-INF/classes/applicationContext.xml]; nested exception is org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 1 in XML document from class path resource [SharedBeans.xml] is invalid; nested exception is org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the declaration of element 'bean'.
    at org.springframework.beans.factory.parsing.FailFastProblemReporter.error(FailFastProblemReporter.java:68)

I can't be sure what I'm doing wrong. The bean was working fine in my context file, and all I did was cut and paste into the new file. Here are the contents of SharedBeans.xml in its entirety:

<bean name="properties" class="com.foo.Properties">
    <constructor-arg><value>${module.name}</value></constructor-arg>
    <constructor-arg><value>${businessUnit}</value></constructor-arg>
    <constructor-arg><value>${product}</value></constructor-arg>
    <constructor-arg><value>${env}</value></constructor-arg>
    <constructor-arg><value>${machineName}</value></constructor-arg>
    <constructor-arg><value>${collectionSet.company}</value></constructor-arg>
    <constructor-arg><value>${route.tag}</value></constructor-arg>
    <constructor-arg><value>${timeout}</value></constructor-arg>
</bean>

Body:
This doesn't strike me as a particularly good use-case for a parent context, which is useful mainly to set up a hierarchy (e.g. one root webapp context, multiple child servlet contexts).

For your situation, it's going to be simpler and easier to understand if you just extract the common bean definitions into a separate file, and then <import> them into each context file that needs it.  You could do this with parent-child contexts, but it's going to be harder to understand, unnecessarily so.

OK, so an example, put your shared bean definition into a file called shared-beans.xml, and put it (for now) at the top-level of your classpath, containing:

<bean name="someBean" class="com.foo.MyClass" />

Then, inside applicationContext-test.xml and /WEB-INF/classes/applicationContext.xml, add the following:

<import resource="classpath:/shared-beans.xml" />

All of the bean definitions in shared-beans.xml will now be imported into each app context. You don't get a third app-context by doing this, you just import the bean definitions from another file.


问:
Breaking a line every 46 characters using Javascript
Im trying to use the following code lines in order to check whether or not the string is larger than 46 characters. If it is longer, it'll break a new line every 46 characters, however, i'm failing to do so.

Can anyone tell me what's wrong?

function ContentFormat(content)
{
    var start = "";
    var end = "";
    var space = "
   ";
    var newcontent = "";
    var toadd = "";
    if (content.length > 46)
    {
        for (var i = 0, len = content.length; i < len; i++) {
            if(i/46 == 0)
            {
                start = content.slice(0, i);
                end = content.slice(i);
                toadd = start.concat(space, end);
            }
            newcontent = toadd;
            toadd = "";
        }
    }
    return newcontent;
}```

答:
Your logic is completely wrong, use below code instead of yours to add the break after 46 characters!

```<code>function ContentFormat(content)
{
    var leftPortion = "";
    var space = "<br/>   ";
    var newcontent = "";
    while (content.length > 46)
    {
        leftPortion = content.slice(0, 45);
        content = content.slice(45);
        newcontent = newcontent + leftPortion + space;
    }
    newcontent = newcontent + content;
    window.alert(newcontent);
}
</code>```

Body:
Your logic is completely wrong, use below code instead of yours to add the break after 46 characters!

function ContentFormat(content)
{
    var leftPortion = "";
    var space = "<br/>&nbsp; &nbsp;";
    var newcontent = "";
    while (content.length > 46)
    {
        leftPortion = content.slice(0, 45);
        content = content.slice(45);
        newcontent = newcontent + leftPortion + space;
    }
    newcontent = newcontent + content;
    window.alert(newcontent);
}


问:
How to mail a birt Report In SpagoBI in CSV format
How to mail a birt report in SpagoBI in Csv Format i have tried to use schedular to schedule a mail by default it is working to generate html(.txt) format,

But how to do that for csv.

答: This can be done by using the csv type in outputType parameter instead of txt.</p>


问:
Difference between two lists in Java
I started learning data structures and algorithms with Java.

I started with list and the first concept which I learnt is difference between array and list.

Now in list I learn how to insert and element in to list and displaying on the screen. I got two pieces of code. The first one I understood very well; where the second one is confusing.

My confusion is what is the Node here? In the beginning we declare Node head;. So basically what is Node here?

Is it predefined datatype or something? Also, how does the second program flow? How is the second program different from the first? And what is the difference?

Also I understood that we are using util here, but still I want to know because how people use it in the industry.

The first method:

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

public class TestCollection7 {
    public static void main(String args[]) {

        LinkedList<String> al = new LinkedList<String>();
        al.add("Ravi");
        al.add("Vijay");
        al.add("Ravi");
        al.add("Ajay");

        Iterator<String> itr = al.iterator();
        while(itr.hasNext()) {
            System.out.println(itr.next());
        }
    }
}
</code>```

Second method:

```<code>package javaapplication3;

public class LIstTEst {
    Node head;

    static class Node {
        int data;
        Node next;
        Node(int d) {
            data = d;
            next = null;
        }
    }

    public void PrintList() {
        Node n = head;
        while(n != null){
            System.out.print(n.data+" ");
            n = n.next;
        }
    }

    public static void main(String args[]) {
        LIstTEst llist = new LIstTEst();
        llist.head = new Node(1);
        Node second = new Node(2);
        Node third = new Node(7);

        llist.head.next = second;
        second.next = third; = third;

        llist.PrintList();
    }
}
</code>```

答:
```<code>public class LIstTEst {
    Node head; // ==> Declaring a Class level variable.

    static class Node { // Create a static class
        int data; // Integer data type variable.
        Node next; // Class refrernce.

        Node(int d) { // Create a constructor.
            data = d; // Holding the current value.
            next = null;
        }
    }

    public void PrintList() {
        Node n = head;
        while (n != null) {
            System.out.print(n.data + " ");
            n = n.next;
        }
    }

    public static void main(String args[]) {
        LIstTEst llist = new LIstTEst(); // Creating a object of the mentioned
                                         // class.

        llist.head = new Node(1);        // Creating the Node class object by Class
                                         // level refrence.

        Node second = new Node(2);       // As this is static class, inside one class,
                                         // so we created directly to object of Node
                                         // class by passing the parameter to the
                                         // constructor.
        Node third = new Node(7);

        llist.head.next = second; // Just transfering the current reference to
                                  // next level reference before that
                                  // constructor is making null for each
                                  // executions.
        llist.head.next = third;

        llist.PrintList(); // Finally for printing purpose it is calling.
    }
}
</code>```

Title: Difference between two lists in Java

Body:
I started learning data structures and algorithms with Java.

I started with list and the first concept which I learnt is difference between array and list.

Now in list I learn how to insert and element in to list and displaying on the screen. I got two pieces of code. The first one I understood very well; where the second one is confusing.

My confusion is what is the Node here? In the beginning we declare Node head;. So basically what is Node here?

Is it predefined datatype or something? Also, how does the second program flow? How is the second program different from the first? And what is the difference?

Also I understood that we are using util here, but still I want to know because how people use it in the industry.

The first method:

import java.util.*;

public class TestCollection7 {
    public static void main(String args[]) {

        LinkedList<String> al = new LinkedList<String>();
        al.add("Ravi");
        al.add("Vijay");
        al.add("Ravi");
        al.add("Ajay");

        Iterator<String> itr = al.iterator();
        while(itr.hasNext()) {
            System.out.println(itr.next());
        }
    }
}

Second method:

package javaapplication3;

public class LIstTEst {
    Node head;

    static class Node {
        int data;
        Node next;
        Node(int d) {
            data = d;
            next = null;
        }
    }

    public void PrintList() {
        Node n = head;
        while(n != null){
            System.out.print(n.data+" ");
            n = n.next;
        }
    }

    public static void main(String args[]) {
        LIstTEst llist = new LIstTEst();
        llist.head = new Node(1);
        Node second = new Node(2);
        Node third = new Node(7);

        llist.head.next = second;
        second.next = third; = third;

        llist.PrintList();
    }
}


问:
How to get child classes which implement a certain base class using reflection in Type Script?
Can we use reflection in Type Script just like C# to get the list of classes which implement a certain base class?

For example, let say Snake and Horse implement the base class Animal. Now I need to get classes which implement Animal. Similar to what we can do in C#:

C# equivalent Code:

```<code>var childTypes = assembly.GetTypes().Where(_ => _.IsSubclassOf(typeof(Animal)));
</code>```

Type Script classes:

```<code>class Animal {
}

class Snake extends Animal {
}

class Horse extends Animal {
}
</code>```

答:
I had the need to deserialize a response from a SOAP web service. I first used an existing SOAP client to get an object from the returned XML and then used a JSON deserializer - the one from http://cloudmark.github.io/Json-Mapping/ - to deserialize this object into the actual types that I want.

Problem was that one of the returned properties was declared as a base type and could actually contain instances of a number of different sub-types.

I solved it by creating a class decorator that I apply to the derived types. This class decorator gets the base class and applies metadata to it, describing the derived class.

To understand the following code, it is important to know that the XML -> JSON parser adds a $type property if the XML from the web service contains a type attribute which indicates that polymorphism is in play.

The actual metadata that is applied to the base type is the type name from the XML and the constructor of the derived type.

Meta data registration and class decorator:

```<code>export interface IJsonPolymorphism {
    name: string;
    clazz: {new(): any};
}

export function RegisterForPolymorphism(name: string) {
    return (target) => {
        let metadata = getJsonPolymorphism(target.__proto__);
        if (!metadata) {
            metadata = [];
        }
        metadata.push({name: name, clazz: target});
        target.__proto__ = Reflect.metadata(jsonPolymorphismMetadataKey, metadata)(target.__proto__);
        return target;
    };
}

export function getJsonPolymorphism(target: any): IJsonPolymorphism[] {
    return Reflect.getMetadata(jsonPolymorphismMetadataKey, target);
}
</code>```

Usage:

```<code>// The base class
export class PropertyBase { /*...*/ }

// The derived classes
//

@RegisterForPolymorphism("b:PicklistProperty")
export class PicklistProperty extends PropertyBase { /*...*/ }
@RegisterForPolymorphism("b:TextProperty")
export class TextProperty extends PropertyBase { /*...*/ }
</code>```

The strings that are passed to the class decorator are the values of the type attribute in the XML response from the web service.

The code of the deserializer makes use of it like this:

```<code>if (jsonObject["$type"]) {
    const polymorphism = getJsonPolymorphism(clazz);
    if (polymorphism && polymorphism.filter) {
        const subclassDefinition = polymorphism.filter(x => x.name === jsonObject["$type"])[0];
        if (subclassDefinition && subclassDefinition.clazz) {
            clazz = subclassDefinition.clazz;
        }
    }
}
</code>```

Basically, clazz is the constructor of the type to deserialize the JSON object to and we replace it with the constructor of the derived type.

This code currently has the restriction that it adds the metadata only to the direct base class, to to the whole hierarchy. But this could easily be solved by adjusting the code inside RegisterForPolymorphism to walk up the tree.

Body:
Can we use reflection in Type Script just like C# to get the list of classes which implement a certain base class?

For example, let say Snake and Horse implement the base class Animal. Now I need to get classes which implement Animal. Similar to what we can do in C#:

C# equivalent Code:

var childTypes = assembly.GetTypes().Where(_ => _.IsSubclassOf(typeof(Animal)));

Type Script classes:

class Animal {
}

class Snake extends Animal {
}

class Horse extends Animal {
}

Body:
I had the need to deserialize a response from a SOAP web service. I first used an existing SOAP client to get an object from the returned XML and then used a JSON deserializer - the one from http://cloudmark.github.io/Json-Mapping/ - to deserialize this object into the actual types that I want.

Problem was that one of the returned properties was declared as a base type and could actually contain instances of a number of different sub-types.

I solved it by creating a class decorator that I apply to the derived types. This class decorator gets the base class and applies metadata to it, describing the derived class.

To understand the following code, it is important to know that the XML -> JSON parser adds a $type property if the XML from the web service contains a type attribute which indicates that polymorphism is in play.

The actual metadata that is applied to the base type is the type name from the XML and the constructor of the derived type.

Meta data registration and class decorator:

export interface IJsonPolymorphism {
    name: string;
    clazz: {new(): any};
}

export function RegisterForPolymorphism(name: string) {
    return (target) => {
        let metadata = getJsonPolymorphism(target.__proto__);
        if (!metadata) {
            metadata = [];
        }
        metadata.push({name: name, clazz: target});
        target.__proto__ = Reflect.metadata(jsonPolymorphismMetadataKey, metadata)(target.__proto__);
        return target;
    };
}

export function getJsonPolymorphism(target: any): IJsonPolymorphism[] {
    return Reflect.getMetadata(jsonPolymorphismMetadataKey, target);
}

Usage:

// The base class
export class PropertyBase { /*...*/ }

// The derived classes
//

@RegisterForPolymorphism("b:PicklistProperty")
export class PicklistProperty extends PropertyBase { /*...*/ }
@RegisterForPolymorphism("b:TextProperty")
export class TextProperty extends PropertyBase { /*...*/ }

The strings that are passed to the class decorator are the values of the type attribute in the XML response from the web service.

The code of the deserializer makes use of it like this:

if (jsonObject["$type"]) {
    const polymorphism = getJsonPolymorphism(clazz);
    if (polymorphism && polymorphism.filter) {
        const subclassDefinition = polymorphism.filter(x => x.name === jsonObject["$type"])[0];
        if (subclassDefinition && subclassDefinition.clazz) {
            clazz = subclassDefinition.clazz;
        }
    }
}

Basically, clazz is the constructor of the type to deserialize the JSON object to and we replace it with the constructor of the derived type.

This code currently has the restriction that it adds the metadata only to the direct base class, to to the whole hierarchy. But this could easily be solved by adjusting the code inside RegisterForPolymorphism to walk up the tree.


问:
IntelliJ doesn't Understand java libraries on Java9-ea
I am using jdk9-ea 149 and created a sample javafx application

IntelliJ doesn't understand the java libraries, It's shows all the import statement in red color and they are all grayed out.even for java.util.List, java.util.ArrayList it has the same issue.

I am able to compile form outside but i am not able to compile the code from IntelliJ 2016.3.2 Ultimate Edition.

It looks like we need to add some libraries to IntelliJ project but with java9 build 149  jigsaw i don't know how to do that.

I am using Experimental features still it doesn't understand the import statements - see intellij setting below

IntelliJ Version : IntelliJ 2016.3.2 Ultimate Edition
Java Version: java 9-ea build: 149

答: The latest version of IntelliJ IDEA, 2017.1, does support jdk 9.</p>


问:
How to correctly initialize $GLOBALS['TSFE']
In my TYPO3 extension, I made a custom controller class that is called from some hook in the TYPO3 backend.

In this controller I would like to get some stuff from $GLOBALS['TSFE'] but when I do var_dump($GLOBALS['TSFE']) I receive null. The question is how can I correctly initialize $GLOBALS['TSFE']?

答:
try something like this:</p>

```<code>$GLOBALS['TSFE'] = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController',$GLOBALS['TYPO3_CONF_VARS'], $id, $type);
</code>```

Body:
try something like this:

$GLOBALS['TSFE'] = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController',$GLOBALS['TYPO3_CONF_VARS'], $id, $type);


问:
Using `QUrl` for file-paths feeds to `std::fstream`
Using QFileDialog, for allowing the user to browses files (for opening), it returns the list of files as QUrl

```<code>QFileDialog dialog;
dialog.setFileMode(QFileDialog::ExistingFile);
dialog.setAcceptMode(QFileDialog::AcceptOpen);
if (!dialog.exec() || dialog.selectedUrls().size()==0) return;

QUrl url = dialog.selectedUrls()[0];
</code>```

After this, the provided url is in the following format:

file:///C:/Users/[...]/test.xml

file:///home/[...]/test.xml

This does not seem to works for std::ifstream so I am trying to (un)normalize the path. For this, I tried the following:

```<code>QUrl nUrl = url.adjusted(QUrl::RemoveScheme | QUrl::RemovePassword | QUrl::RemoveUserInfo |
               QUrl::RemovePort| QUrl::RemoveAuthority | QUrl::RemoveQuery |
               QUrl::RemoveFragment | QUrl::StripTrailingSlash |
               QUrl::NormalizePathSegments);
</code>```

Which return a path in the following format:

/C:/Users/[...]/test.xml

/home/[...]/test.xml

The first slash works on Linux, but not on Windows. And if I remove the first slash, it would works on Windows, but not on Linux.

The quesiton is:

How to convert QUrl reliably to a format which is accepted by std::fstream?

答: Try to use QUrl::toLocalPath instead of QUrl::adjusted</p>

Body:
Using QFileDialog, for allowing the user to browses files (for opening), it returns the list of files as QUrl

QFileDialog dialog;
dialog.setFileMode(QFileDialog::ExistingFile);
dialog.setAcceptMode(QFileDialog::AcceptOpen);
if (!dialog.exec() || dialog.selectedUrls().size()==0) return;

QUrl url = dialog.selectedUrls()[0];

After this, the provided url is in the following format:

file:///C:/Users/[...]/test.xml

file:///home/[...]/test.xml

This does not seem to works for std::ifstream so I am trying to (un)normalize the path. For this, I tried the following:

QUrl nUrl = url.adjusted(QUrl::RemoveScheme | QUrl::RemovePassword | QUrl::RemoveUserInfo |
               QUrl::RemovePort| QUrl::RemoveAuthority | QUrl::RemoveQuery |
               QUrl::RemoveFragment | QUrl::StripTrailingSlash |
               QUrl::NormalizePathSegments);

Which return a path in the following format:

/C:/Users/[...]/test.xml

/home/[...]/test.xml

The first slash works on Linux, but not on Windows. And if I remove the first slash, it would works on Windows, but not on Linux.

The quesiton is:

How to convert QUrl reliably to a format which is accepted by std::fstream?


问:
Move Text Frame Outside Page into Bleed
I need to move the text frame created in the below script to outside the page area to the bleed area. If anyone can help me adjust the below script, that would be wonderful. I have been trying to determine how to use Page Height and Width to do an X, Y adjustment once that is determined. </p>

<p>Please see my code below. Any and all help would be greatly appreciated and thank you in advance. </p>

```<code>myDocument = app.activeDocument;
//The bleed and slug properties belong to the documentPreferences object.
with (myDocument.documentPreferences) {
//Bleed
documentBleedBottomOffset = "2in";
documentBleedTopOffset = "2in";
documentBleedInsideOrLeftOffset = "2in";
documentBleedOutsideOrRightOffset = "2in";
//Slug
slugBottomOffset = "0p";
slugTopOffset = "0p";
slugInsideOrLeftOffset = "0p";
slugRightOrOutsideOffset = "0p";
}
var myDocument = app.documents.item(0);
var myPage = myDocument.pages.item(0);
var myTextFrame = myPage.textFrames.add();
//Set the bounds of the text frame [x1, y1, x2, y2]
//The x1, y1 refers to the upper left coordinate position; the x2, y2 refers to the lower right coordinate
//x2 = Height and y2 = Width
myTextFrame.geometricBounds = [0, 0, .52, 5.5];
//Enter text in the text frame.
//("\r" is a return character.+
myTextFrame.contents = "FName Name//12345-6789//\r WxL//\r XXX-YYYYY//W x L-LtrRD//P_";
myTextFrame.parentStory.insertionPoints.item(-1).contents = SpecialCharacters.autoPageNumber;
//Note that you could also use a properties record to
//create the frame and set its bounds and contents in one line:
//var myTextFrame = myDocument.pages.item(0).textFrames.add({geometricBounds:[72, 72, 288, 288], contents:"This is some example text."});

//Absolute move: based on [X , Y] its important to keep in mind that all units are based on your document units
myTextFrame.move([1, 5.5]);
</code>```

答:
Please add the following lines of snippet that will calculate the x and y coordinate for the move parameter... As it was not mentioned where exactly the frame needs to be shifted hence shifting in the corner in the bleed.. You can use this to adjust accordingly..

```<code>var theBounds = myPage.bounds;
var theXCoord = theBounds[3] + (myDocument.documentPreferences.documentBleedBottomOffset)/2;
var theYCoord = theBounds[2] + (myDocument.documentPreferences.documentBleedBottomOffset)/2;

myTextFrame.move([theXCoord, theYCoord]);
</code>```

Hope this answers your question...

Title: Move Text Frame Outside Page into Bleed

Body:
I need to move the text frame created in the below script to outside the page area to the bleed area. If anyone can help me adjust the below script, that would be wonderful. I have been trying to determine how to use Page Height and Width to do an X, Y adjustment once that is determined.

Please see my code below. Any and all help would be greatly appreciated and thank you in advance.

myDocument = app.activeDocument;
//The bleed and slug properties belong to the documentPreferences object.
with (myDocument.documentPreferences) {
//Bleed
documentBleedBottomOffset = "2in";
documentBleedTopOffset = "2in";
documentBleedInsideOrLeftOffset = "2in";
documentBleedOutsideOrRightOffset = "2in";
//Slug
slugBottomOffset = "0p";
slugTopOffset = "0p";
slugInsideOrLeftOffset = "0p";
slugRightOrOutsideOffset = "0p";
}
var myDocument = app.documents.item(0);
var myPage = myDocument.pages.item(0);
var myTextFrame = myPage.textFrames.add();
//Set the bounds of the text frame [x1, y1, x2, y2]
//The x1, y1 refers to the upper left coordinate position; the x2, y2 refers to the lower right coordinate
//x2 = Height and y2 = Width
myTextFrame.geometricBounds = [0, 0, .52, 5.5];
//Enter text in the text frame.
//("\r" is a return character.+
myTextFrame.contents = "FName Name//12345-6789//\r WxL//\r XXX-YYYYY//W x L-LtrRD//P_";
myTextFrame.parentStory.insertionPoints.item(-1).contents = SpecialCharacters.autoPageNumber;
//Note that you could also use a properties record to
//create the frame and set its bounds and contents in one line:
//var myTextFrame = myDocument.pages.item(0).textFrames.add({geometricBounds:[72, 72, 288, 288], contents:"This is some example text."});

//Absolute move: based on [X , Y] its important to keep in mind that all units are based on your document units
myTextFrame.move([1, 5.5]);

Body:
Please add the following lines of snippet that will calculate the x and y coordinate for the move parameter... As it was not mentioned where exactly the frame needs to be shifted hence shifting in the corner in the bleed.. You can use this to adjust accordingly..

var theBounds = myPage.bounds;
var theXCoord = theBounds[3] + (myDocument.documentPreferences.documentBleedBottomOffset)/2;
var theYCoord = theBounds[2] + (myDocument.documentPreferences.documentBleedBottomOffset)/2;

myTextFrame.move([theXCoord, theYCoord]);

Hope this answers your question...


问:
Apache2 ASP MVC Razor view crashes when referencing PCL enum for dropdown
I am new to using ASP.net on ubuntu with mono, I have several websites working very well indeed using MVC5, though I recently migrated a project over and have found that forms referencing enums from a referenced PCL cause views to crash. Below is my EnumDropDownList call which works fine on a windows host.

```<code><div class="form-group">
@Html.LabelFor(m => m.Type, new { @class = "control-label" })
@Html.EnumDropDownListFor(m => m.Type, new { @class = "form-control" })
</div>
</code>```

When viewing this in the browser on the ubuntu host however I get the following error

```<code>System.InvalidOperationException
The view found at '~/Views/portal/productgroup.cshtml' was not created.
</code>```

Additional the stack trace is

```<code>     at System.Web.Mvc.BuildManagerCompiledView.Render (System.Web.Mvc.ViewContext viewContext, System.IO.TextWriter writer) [0x00061] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.ViewResultBase.ExecuteResult (System.Web.Mvc.ControllerContext context) [0x00080] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.ControllerActionInvoker.InvokeActionResult (System.Web.Mvc.ControllerContext controllerContext, System.Web.Mvc.ActionResult actionResult) [0x00000] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive (System.Collections.Generic.IList`1[T] filters, System.Int32 filterIndex, System.Web.Mvc.ResultExecutingContext preContext, System.Web.Mvc.ControllerContext controllerContext, System.Web.Mvc.ActionResult actionResult) [0x0000b] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive (System.Collections.Generic.IList`1[T] filters, System.Int32 filterIndex, System.Web.Mvc.ResultExecutingContext preContext, System.Web.Mvc.ControllerContext controllerContext, System.Web.Mvc.ActionResult actionResult) [0x0004f] in <cc73190bab9d435c831510ff295c572a>:0
</code>```

Is there a way I need to reference the external assembly in my controller or my razor view? Is this a common issue or could there be something specific going on?

For reference the PCL holds some shared code for use between my site and a mobile app built using Xamarin. The PCL has the profile .NET framework 4.5 in addition to all of the Xamarin ones etc. The code is fully operational on windows and will work if I remove references to the enum stored in the PCL.

Any help would be greatly appreciated.

答:
After much research and testing I have managed to solve my issue, I will explain the process now.

I switched to compiled MVCViews in my project configuration and noticed that they failed to compile due to not referencing System.Runtime in my web.config, I added this reference and then my views compiled, upon testing this locally it worked fine but failed with the same issue on mono.

Next I started to wonder whether mono had a version of System.Runtime so I installed the System.Runtime package from nuget, I noticed that upon building my project this was not added to my bin folder and was also missing from my project references even though nuget listed it as installed in visual studio.

Finally I just copied the System.Runtime.dll into my remote bin folder and this solved my problem. It seems that System.Runtime needs to be present any our bun folder if you rely on it.(Which you probably do!)

I hope this helps someone as I have spent MANY hours trying to find help on this!

Body:
I am new to using ASP.net on ubuntu with mono, I have several websites working very well indeed using MVC5, though I recently migrated a project over and have found that forms referencing enums from a referenced PCL cause views to crash. Below is my EnumDropDownList call which works fine on a windows host.

@Html.LabelFor(m => m.Type, new { @class = "control-label" })
@Html.EnumDropDownListFor(m => m.Type, new { @class = "form-control" })

When viewing this in the browser on the ubuntu host however I get the following error

System.InvalidOperationException
The view found at '~/Views/portal/productgroup.cshtml' was not created.

Additional the stack trace is

     at System.Web.Mvc.BuildManagerCompiledView.Render (System.Web.Mvc.ViewContext viewContext, System.IO.TextWriter writer) [0x00061] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.ViewResultBase.ExecuteResult (System.Web.Mvc.ControllerContext context) [0x00080] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.ControllerActionInvoker.InvokeActionResult (System.Web.Mvc.ControllerContext controllerContext, System.Web.Mvc.ActionResult actionResult) [0x00000] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive (System.Collections.Generic.IList`1[T] filters, System.Int32 filterIndex, System.Web.Mvc.ResultExecutingContext preContext, System.Web.Mvc.ControllerContext controllerContext, System.Web.Mvc.ActionResult actionResult) [0x0000b] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive (System.Collections.Generic.IList`1[T] filters, System.Int32 filterIndex, System.Web.Mvc.ResultExecutingContext preContext, System.Web.Mvc.ControllerContext controllerContext, System.Web.Mvc.ActionResult actionResult) [0x0004f] in <cc73190bab9d435c831510ff295c572a>:0

Is there a way I need to reference the external assembly in my controller or my razor view? Is this a common issue or could there be something specific going on?

For reference the PCL holds some shared code for use between my site and a mobile app built using Xamarin. The PCL has the profile .NET framework 4.5 in addition to all of the Xamarin ones etc. The code is fully operational on windows and will work if I remove references to the enum stored in the PCL.

Any help would be greatly appreciated.


问:
Can http client cancel the reuqest before whole body is received?
For example,
By an user, a client send GET request for a 1GB size of data, then the client is receiving the data.
But the user decides to cancel previous one and download another data.
At this moment, does the client immediately cancel previous HTTP request before 1GB size of whole data and send a new HTTP GET request with reusing socket?
Because I'd like to avoid TCP slow start by new socket connection in this situation.</p>

答: Although Steffen Ullrich is correct and although you cannot stop a response midway (barring an impolite disconnection), you could use the HEAD request to review the metadata (i.e. size of the download) prior to submitting the GET request.</p>


问:
Unable to run app in Simulator : Domain = LaunchServicesError, Code = 0
info.plistI am having trouble launching the simulator, I get the error code that the operation could not be completed.

Here is the error code I received from the console:
I have already noticed that the CFBundleExecutable is missing or invalid, but since I am relatively new to Xcode, I was hoping to get some help and what I have to do to fix this issue.

```<code>Mar  6 17:24:51 Pauls-MBP installd[12084]: 0xb0093000 -[MIInstaller _bundlesAtURL:error:]: Failed to create bundle for file:///Users/Paul/Library/Developer/CoreSimulator/Devices/44B11D45-11C2-4FE3-9ACB-7BE3F82B3FE1/data/Library/Caches/com.apple.mobile.installd.staging/temp.LppSWd/extracted/Davy.app/ : Error Domain=MIInstallerErrorDomain Code=11 "Bundle at path /Users/Paul/Library/Developer/CoreSimulator/Devices/44B11D45-11C2-4FE3-9ACB-7BE3F82B3FE1/data/Library/Caches/com.apple.mobile.installd.staging/temp.LppSWd/extracted/Davy.app has missing or invalid CFBundleExecutable in its Info.plist" UserInfo={LegacyErrorString=MissingBundleExecutable, FunctionName=-[MIExecutableBundle _validateWithError:], NSLocalizedDescription=Bundle at path /Users/Paul/Library/Developer/CoreSimulator/Devices/44B11D45-11C2-4FE3-9ACB-7BE3F82B3FE1/data/Library/Caches/com.apple.mobile.installd.staging/temp.LppSWd/extracted/Davy.app has missing or invalid CFBundleExecutable in its Info.plist, SourceFileLine=68}
Mar  6 17:24:51 Pauls-MBP CoreSimulatorBridge[12099]: 0xb0115000 __MobileInstallationInstallForLaunchServices_block_invoke222: Returned error Error Domain=MIInstallerErrorDomain Code=11 "Bundle at path /Users/Paul/Library/Developer/CoreSimulator/Devices/44B11D45-11C2-4FE3-9ACB-7BE3F82B3FE1/data/Library/Caches/com.apple.mobile.installd.staging/temp.LppSWd/extracted/Davy.app has missing or invalid CFBundleExecutable in its Info.plist" UserInfo={LegacyErrorString=MissingBundleExecutable, FunctionName=-[MIExecutableBundle _validateWithError:], NSLocalizedDescription=Bundle at path /Users/Paul/Library/Developer/CoreSimulator/Devices/44B11D45-11C2-4FE3-9ACB-7BE3F82B3FE1/data/Library/Caches/com.apple.mobile.installd.staging/temp.LppSWd/extracted/Davy.app has missing or invalid CFBundleExecutable in its Info.plist, SourceFileLine=68}
Mar  6 17:24:51 Pauls-MBP CoreSimulatorBridge[12099]: ERROR: MobileInstallationInstallForLaunchServices returned nil
</code>```

答:
you may want to Reset Content & Settings in simulator and also try cleaning your build folder in xCode using cmd+shift+option+k
You may also want to check the bundle identifier.

Body:
info.plistI am having trouble launching the simulator, I get the error code that the operation could not be completed.

Here is the error code I received from the console:
I have already noticed that the CFBundleExecutable is missing or invalid, but since I am relatively new to Xcode, I was hoping to get some help and what I have to do to fix this issue.

Mar  6 17:24:51 Pauls-MBP installd[12084]: 0xb0093000 -[MIInstaller _bundlesAtURL:error:]: Failed to create bundle for file:///Users/Paul/Library/Developer/CoreSimulator/Devices/44B11D45-11C2-4FE3-9ACB-7BE3F82B3FE1/data/Library/Caches/com.apple.mobile.installd.staging/temp.LppSWd/extracted/Davy.app/ : Error Domain=MIInstallerErrorDomain Code=11 "Bundle at path /Users/Paul/Library/Developer/CoreSimulator/Devices/44B11D45-11C2-4FE3-9ACB-7BE3F82B3FE1/data/Library/Caches/com.apple.mobile.installd.staging/temp.LppSWd/extracted/Davy.app has missing or invalid CFBundleExecutable in its Info.plist" UserInfo={LegacyErrorString=MissingBundleExecutable, FunctionName=-[MIExecutableBundle _validateWithError:], NSLocalizedDescription=Bundle at path /Users/Paul/Library/Developer/CoreSimulator/Devices/44B11D45-11C2-4FE3-9ACB-7BE3F82B3FE1/data/Library/Caches/com.apple.mobile.installd.staging/temp.LppSWd/extracted/Davy.app has missing or invalid CFBundleExecutable in its Info.plist, SourceFileLine=68}
Mar  6 17:24:51 Pauls-MBP CoreSimulatorBridge[12099]: 0xb0115000 __MobileInstallationInstallForLaunchServices_block_invoke222: Returned error Error Domain=MIInstallerErrorDomain Code=11 "Bundle at path /Users/Paul/Library/Developer/CoreSimulator/Devices/44B11D45-11C2-4FE3-9ACB-7BE3F82B3FE1/data/Library/Caches/com.apple.mobile.installd.staging/temp.LppSWd/extracted/Davy.app has missing or invalid CFBundleExecutable in its Info.plist" UserInfo={LegacyErrorString=MissingBundleExecutable, FunctionName=-[MIExecutableBundle _validateWithError:], NSLocalizedDescription=Bundle at path /Users/Paul/Library/Developer/CoreSimulator/Devices/44B11D45-11C2-4FE3-9ACB-7BE3F82B3FE1/data/Library/Caches/com.apple.mobile.installd.staging/temp.LppSWd/extracted/Davy.app has missing or invalid CFBundleExecutable in its Info.plist, SourceFileLine=68}
Mar  6 17:24:51 Pauls-MBP CoreSimulatorBridge[12099]: ERROR: MobileInstallationInstallForLaunchServices returned nil


答:
You can also try like:</p>

```<code>DECLARE @StartDate DATETIME='2017-02-04 17:00:00.000',
        @EndDate DATETIME = '2017-02-05 17:00:00.000'
SELECT DateAdd(DAY, nbr - 1, @StartDate) AS date_from,
       DateAdd(DAY, nbr - 1, GetDate()) AS date_to
FROM
  (SELECT ROW_NUMBER() OVER (
                             ORDER BY c.object_id) AS Nbr
   FROM sys.columns c ) nbrs
WHERE nbr - 1 <= DATEDIFF(DAY, @StartDate, @EndDate)
</code>```

Title: Split range of date and time become separate record

Body:
today i have some problem with splitting two date with their time who have range become separate record

in order to do that, for example i have this sample

----------------------------------------------------------------
| Record id | date_from               | date_to                |
----------------------------------------------------------------
|     A     | 2017-02-03 08:00:00.000 | 2017-02-04 17:00:00.000|
----------------------------------------------------------------

then with script or procedure, i want get this result as expected below

----------------------------------------------------------------
| Record id | date_from               | date_to                |
----------------------------------------------------------------
|     A     | 2017-02-03 08:00:00.000 | 2017-02-03 23:59:59.000|
----------------------------------------------------------------
|     A     | 2017-02-04 00:00:00.000 | 2017-02-04 17:00:00.000|
----------------------------------------------------------------

how to get this done by the way? and it's dynamic. thank you very much :)

Body:
You can also try like:

DECLARE @StartDate DATETIME='2017-02-04 17:00:00.000',
        @EndDate DATETIME = '2017-02-05 17:00:00.000'
SELECT DateAdd(DAY, nbr - 1, @StartDate) AS date_from,
       DateAdd(DAY, nbr - 1, GetDate()) AS date_to
FROM
  (SELECT ROW_NUMBER() OVER (
                             ORDER BY c.object_id) AS Nbr
   FROM sys.columns c ) nbrs
WHERE nbr - 1 <= DATEDIFF(DAY, @StartDate, @EndDate)


问:
Scala syntax tree returned from inferImplicitValue is failing to evaluate
I am writing a Scala macro (Scala 2.11) where I'd like to obtain the tree representing an implicit variable inside the macro using inferImplicitValue, evaluate that syntax tree, and use the value.  I have actually done this, but it doesn't seem to work in all circumstances[1].  I constructed a simplified example where it fails.

```<code>// a class for implicit evidence
class DemoEvidence(val value: Int)

// define 'foo' method for invoking the macro
object demoModule {
  def foo: Int = macro DemoMacros.fooImpl
}

class DemoMacros(val c: whitebox.Context) {
  import c.universe._

  def fooImpl: Tree = {
    val vInt = try {
      // get the tree representing the implicit value
      val impl = c.inferImplicitValue(typeOf[DemoEvidence], silent = false)
      // print it out
      println(s"impl= $impl")
      // try to evaluate the tree (this is failing)
      val eval = c.eval(c.Expr[DemoEvidence](c.untypecheck(impl.duplicate)))
      eval.value
    } catch {
      case e: Throwable => {
        // on failure print out the failure message
        println(s"Eval failed with: $e\nStack trace:\n${e.printStackTrace}")
        0
      }
    }
    q"$vInt"  // return tree representing the integer value
  }
}
</code>```

If I compile the above, and then invoke it:

```<code>object demo {
  implicit val demoEvidence: DemoEvidence = new DemoEvidence(42)
  val i: Int = demoModule.foo
}
</code>```

I see the compilation fail in the following way:

```<code>impl= demo.this.demoEvidence
java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at scala.tools.reflect.ToolBoxFactory$ToolBoxImpl$ToolBoxGlobal$$anonfun$compile$1.apply(ToolBoxFactory.scala:275)
...
</code>```

Full output at:
https://gist.github.com/erikerlandson/df48f64329be6ab9de9caef5f5be4a83

So, you can see it is finding the tree for the declared implicit value demo.this.demoEvidence, but evaluation of that tree is failing.  I have seen this basic approach work elsewhere in my project.  Not sure what the difference is, and why it fails here.

[1] UPDATE: If the implicit value is defined in a (sub)project, and compiled, and then used exterior to that project, it works as expected. That was the case where this approach is working for me.

So the question is whether that's just a fundamental constraint I have to live with, or if there is some clever workaround, or if this is a "bug" with inferring implicit values inside macros that might be fixed.

UPDATE: I filed a Scala issue for this: https://github.com/scala/scala-dev/issues/353

答:
From the look of the stack trace, the eval is expecting object demo to exist in classfile form for execution, which makes sense given that the value you're trying to compute depends on val demoEvidence which is a member of object demo.

But the eval is happening during the typechecking of object demo so the classfile doesn't exist yet, hence the error. In the version with the implicit value defined in a subproject I imagine the subproject is compiled first, hence the classfiles required for the eval exist and so evaluation proceeds as you were expecting.

Body:
I am writing a Scala macro (Scala 2.11) where I'd like to obtain the tree representing an implicit variable inside the macro using inferImplicitValue, evaluate that syntax tree, and use the value.  I have actually done this, but it doesn't seem to work in all circumstances[1].  I constructed a simplified example where it fails.

// a class for implicit evidence
class DemoEvidence(val value: Int)

// define 'foo' method for invoking the macro
object demoModule {
  def foo: Int = macro DemoMacros.fooImpl
}

class DemoMacros(val c: whitebox.Context) {
  import c.universe._

  def fooImpl: Tree = {
    val vInt = try {
      // get the tree representing the implicit value
      val impl = c.inferImplicitValue(typeOf[DemoEvidence], silent = false)
      // print it out
      println(s"impl= $impl")
      // try to evaluate the tree (this is failing)
      val eval = c.eval(c.Expr[DemoEvidence](c.untypecheck(impl.duplicate)))
      eval.value
    } catch {
      case e: Throwable => {
        // on failure print out the failure message
        println(s"Eval failed with: $e\nStack trace:\n${e.printStackTrace}")
        0
      }
    }
    q"$vInt"  // return tree representing the integer value
  }
}

If I compile the above, and then invoke it:

object demo {
  implicit val demoEvidence: DemoEvidence = new DemoEvidence(42)
  val i: Int = demoModule.foo
}

I see the compilation fail in the following way:

impl= demo.this.demoEvidence
java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at scala.tools.reflect.ToolBoxFactory$ToolBoxImpl$ToolBoxGlobal$$anonfun$compile$1.apply(ToolBoxFactory.scala:275)
...

Full output at:
https://gist.github.com/erikerlandson/df48f64329be6ab9de9caef5f5be4a83

So, you can see it is finding the tree for the declared implicit value demo.this.demoEvidence, but evaluation of that tree is failing.  I have seen this basic approach work elsewhere in my project.  Not sure what the difference is, and why it fails here.

[1] UPDATE: If the implicit value is defined in a (sub)project, and compiled, and then used exterior to that project, it works as expected. That was the case where this approach is working for me.

So the question is whether that's just a fundamental constraint I have to live with, or if there is some clever workaround, or if this is a "bug" with inferring implicit values inside macros that might be fixed.

UPDATE: I filed a Scala issue for this: https://github.com/scala/scala-dev/issues/353


问:
How to create factory in AngularJS?
I had created a factory in angular but i am  getting the following  error

```<code>Unknown provider:
</code>```

Here is the factory:

```<code>app.factory("getFoo", function($scope){
    return {
       getCommi: function(val,id){
          var array = ["hello","world"];
          return array;
       }
     }
});
</code>```

The controller is:

```<code>app.controller('myCtrl', ['$scope','getFoo',function($scope,getFoo){
   $scope.myArr = getFoo.getCommi(4,1);
}])
</code>```

What can I have to do for  fix this? I just don't see any problem.

答:
Please remove $scope from the factory.

```<code>var app = angular.module('myApp',[]);

app.factory("getFoo", function(){
    return {
       getCommi: function(val,id){
          var array = ["hello","world"];
          return array;
       }
    }
});

app.controller('myCtrl', ['$scope','getFoo',function($scope,getFoo){
   $scope.myArr = getFoo.getCommi(4,1);

}])
</code>```

Title: How to create factory in AngularJS?

Body:
I had created a factory in angular but i am  getting the following  error

Unknown provider:

Here is the factory:

app.factory("getFoo", function($scope){
    return {
       getCommi: function(val,id){
          var array = ["hello","world"];
          return array;
       }
     }
});

The controller is:

app.controller('myCtrl', ['$scope','getFoo',function($scope,getFoo){
   $scope.myArr = getFoo.getCommi(4,1);
}])

What can I have to do for  fix this? I just don't see any problem.

Body:
Please remove $scope from the factory.

var app = angular.module('myApp',[]);

app.factory("getFoo", function(){
    return {
       getCommi: function(val,id){
          var array = ["hello","world"];
          return array;
       }
    }
});

app.controller('myCtrl', ['$scope','getFoo',function($scope,getFoo){
   $scope.myArr = getFoo.getCommi(4,1);

}])