问:
Is the polymer (2.0) is good choice for large scale MVC web application User interface?
I'm thinking to design a Grails web application UI using the Polymer library, as it provides custom templates, data binding and helps to reuse  web components on any page. Also it is pure HTML, so server side processing should be reduced, as compared to JSP or GSP pages.

So, my question is, will it be a good approach for a large application and also performance, browser compatibility and code management etc.?

答:
Everything that means to organize and reuse your code is great for large and complex web apps/projects, and you can achieve that with web components (in this case, with Polymer).

Its performance is good as it provides features like HTML imports, which avoids duplicate requests to the server (and you can also use libraries like Polymer Bundle or Vulcanize to package your assets in production).

Polymer features are supported natively in Google Chrome and Opera, and partially in Firefox, Safari and IE/Edge. You can have a full browser support with polyfills (webcomponents.js).

And code management with Polymer is great as it encapsulates element's styles and templates. In conclusion, Polymer and web components provides great tools and features to work in a large project and they have a great community behind.


来源: stackexchange

问:
How to redirect correctly in a global error handler
I have this global error handler:

```<code>import { ErrorHandler, Injectable, Injector } from '@angular/core';
import { Router } from '@angular/router';

    @Injectable()
    export class GlobalErrorHandler extends ErrorHandler
    {
        constructor(private injector: Injector) {
            super(false);
        }

        handleError(error) {
            super.handleError(error);
            const router = this.injector.get(Router);
                router.navigateByUrl('/error');
        }

    }
</code>```

I put it in app.module:

```<code>  providers: [
    {
      provide: ErrorHandler,
      useClass: GlobalErrorHandler
    }
  ]
</code>```

to test this I throw an error inside a service. For some reason the error component shows up together with the other contents of the page. Something like this:

if I test the error component by going to /error it shows up like this (the error page is a paragraph with a single line):

```<code>Sorry, something went wrong!
</code>```

but when I go to my home page where the error should trigger it shows up like this:

```<code>Sorry, something went wrong!

....
... Original content for /home
....

Sorry, something went wrong!
</code>```

Can someone enlighten me what am I doing wrong?

Update

I've updated to angular-cli 1.5.2 AND also updated to angular 5 and the bug seems fixed there. I can navigate to the error page using the router.

答:
It depends in where you have placed the router-outlet. if you something like this:

```<code><router-outlet></router-outlet>
<!-- Home Component Content -->
</code>```

It will loads just like you say, with the other components content. To avoid this behavior you have to struct your main component like this:

```<code><router-outlet></router-outle>
</code>```

Just that and the things you want in all pages, including the error one.

ContentLicense: CC BY-SA 3.0

Body:
I have this global error handler:

import { ErrorHandler, Injectable, Injector } from '@angular/core';
import { Router } from '@angular/router';

    @Injectable()
    export class GlobalErrorHandler extends ErrorHandler
    {
        constructor(private injector: Injector) {
            super(false);
        }

        handleError(error) {
            super.handleError(error);
            const router = this.injector.get(Router);
                router.navigateByUrl('/error');
        }

    }

I put it in app.module:

  providers: [
    {
      provide: ErrorHandler,
      useClass: GlobalErrorHandler
    }
  ]

to test this I throw an error inside a service. For some reason the error component shows up together with the other contents of the page. Something like this:

if I test the error component by going to /error it shows up like this (the error page is a paragraph with a single line):

Sorry, something went wrong!

but when I go to my home page where the error should trigger it shows up like this:

Sorry, something went wrong!

....
... Original content for /home
....

Sorry, something went wrong!

Can someone enlighten me what am I doing wrong?

Update

I've updated to angular-cli 1.5.2 AND also updated to angular 5 and the bug seems fixed there. I can navigate to the error page using the router.

Body:
It depends in where you have placed the router-outlet. if you something like this:

<router-outlet></router-outlet>
<!-- Home Component Content -->

It will loads just like you say, with the other components content. To avoid this behavior you have to struct your main component like this:

<router-outlet></router-outle>

Just that and the things you want in all pages, including the error one.


问:
Ruby on rails - unable to create comments. NoMethodError
I am creating one of my first RoR applications - a forum. I am try to add comments to the forum, but I am getting some errors. I have Googled for similar issues but none of the seem to solve my issue. Here is my code:

Comments Controller:

```<code>class CommentsController < ApplicationController
  def create
    @forum = Forum.find(params[:forum_id])

    if !@forum.nil?
        puts "Forum object is not nil"
    end

    @comment = @forum.comment.create(comment_params)

    redirect_to forum_path
  end

  private

  def comment_params
    params.require(:comment).permit(:body)
  end
end
</code>```

The Forum controller is auto generated and I haven't changed in. (generated using rails generate scaffold Forum, if you still want to see it, let me know)

```<code>class Comment < ApplicationRecord
  belongs_to :forum
end

class Forum < ApplicationRecord
  has_many :comments
  validates :title, presence: true,
  length: {maximum: 50}
  validates :body, presence: true
end
</code>```

Below is the form for section from the show.html.erb for the forum page

```<code><h2>Comments</h2>

<% @forum.comments.each do |comment| %>
<p>
    <%= comment.body %>
</p>

<% end %>

<h2>Add a comment</h2>

<%= form_for([@forum, @forum.comments.build]) do |f| %>
<p>
    <%= f.label :body %><br/>
    <%= f.text_area :body %>
</p>
<p>
    <%= f.submit %>
</p>
<% end %>
</code>```

And this is the error from rails:

```<code>undefined method `comment' for #<Forum:0x444d518>
</code>```

with the following extract:

```<code>end
 @comment = @forum.comment.create(comment_params) #highlighted
 redirect_to forum_path
end
</code>```

答:
So, the problem lay in the CommentsController.

I changed the comments controller to do this instead:

```<code>def create
        @forum = Forum.find(params[:forum_id])

        @comment = Comment.new(comment_params)
        @comment.forum_id = @forum.id
        @comment.save!

        redirect_to forum_path(@forum)
    end

    private
        def comment_params
            params.require(:comment).permit(:body)
        end
</code>```

Seemed to do the trick.

Thank you to all those who gave an answer.

Body:
I am creating one of my first RoR applications - a forum. I am try to add comments to the forum, but I am getting some errors. I have Googled for similar issues but none of the seem to solve my issue. Here is my code:

Comments Controller:

class CommentsController < ApplicationController
  def create
    @forum = Forum.find(params[:forum_id])

    if !@forum.nil?
        puts "Forum object is not nil"
    end

    @comment = @forum.comment.create(comment_params)

    redirect_to forum_path
  end

  private

  def comment_params
    params.require(:comment).permit(:body)
  end
end

The Forum controller is auto generated and I haven't changed in. (generated using rails generate scaffold Forum, if you still want to see it, let me know)

class Comment < ApplicationRecord
  belongs_to :forum
end

class Forum < ApplicationRecord
  has_many :comments
  validates :title, presence: true,
  length: {maximum: 50}
  validates :body, presence: true
end

Below is the form for section from the show.html.erb for the forum page

Comments

<% @forum.comments.each do |comment| %>

    <%= comment.body %>

<% end %>

Add a comment

<%= form_for([@forum, @forum.comments.build]) do |f| %>

    <%= f.label :body %>

    <%= f.text_area :body %>

    <%= f.submit %>

<% end %>

And this is the error from rails:

undefined method `comment' for #<Forum:0x444d518>

with the following extract:

end
 @comment = @forum.comment.create(comment_params) #highlighted
 redirect_to forum_path
end

Body:
So, the problem lay in the CommentsController.

I changed the comments controller to do this instead:

def create
        @forum = Forum.find(params[:forum_id])

        @comment = Comment.new(comment_params)
        @comment.forum_id = @forum.id
        @comment.save!

        redirect_to forum_path(@forum)
    end

    private
        def comment_params
            params.require(:comment).permit(:body)
        end

Seemed to do the trick.

Thank you to all those who gave an answer.


问:
On Duplicate Key Update is creating a new row instead of updating
I've got a datatable called buildTracker. A php form Posts the data for submission to create new ID/rows. That much works great. A second form pulls up existing rows for edit -

However instead of updating the existing row, it creates a new row and new key (ID)

How can I get the key to update without creating a new row?

```<code>$enteredBy    = $conn->real_escape_string($_POST['enteredBy']);
   $query   = "INSERT into buildtracker (EnteredBy)
    VALUES('" . $enteredBy . "')
    ON DUPLICATE KEY UPDATE EnteredBy='" . $enteredBy . "'";

$success = $conn->query($query);
</code>```

Where am I going wrong with the updating?

Datatable rows include ID (key) and EnteredBy (text)

答: By the looks of it, your table, buildTracker, has a auto-incremented key field on it.  If you do a describe on the table, my guess is that that's what it would show.  The fact you are inserting a date means that the auto-increment will fire and you will never create a duplicate.  If you have EnteredBy as the primary key, it should ALWAYS update where that $enteredBy exists.</p>

Body:
I've got a datatable called buildTracker. A php form Posts the data for submission to create new ID/rows. That much works great. A second form pulls up existing rows for edit -

However instead of updating the existing row, it creates a new row and new key (ID)

How can I get the key to update without creating a new row?

$enteredBy    = $conn->real_escape_string($_POST['enteredBy']);
   $query   = "INSERT into buildtracker (EnteredBy)
    VALUES('" . $enteredBy . "')
    ON DUPLICATE KEY UPDATE EnteredBy='" . $enteredBy . "'";

$success = $conn->query($query);

Where am I going wrong with the updating?

Datatable rows include ID (key) and EnteredBy (text)


问:
Why is multiline string altered on print or write? (Python 3.6 on Windows)
I am using Python 3.6.3 on Windows.
When I try to print a single multiline string to file like this:

```<code>with open('test1.txt', mode='w') as f:
    f.write('test\r\ntest\r\n')
</code>```

Then test1.txt will end up containing test\r\r\ntest\r\r\n instead of test\r\ntest\r\n.

A workaround to get the desired output would look like so:

```<code>with open('test2.txt', mode='w') as f:
    for line in 'test\r\ntest\r\n'.splitlines():
        print(line, file=f)
</code>```

Why is this happening?

答:
Well, turns out properly stating a question often leads to the answer presenting itself:

The reason for this behaviour is to be found with Python's universal newline (quoting from PEP 3116 on TextIOWrapper):

On output, if newline is None, any '\n' characters written are translated to the system default line separator, os.linesep. If newline is '', no translation takes place. If newline is any of the other legal values, any '\n' characters written are translated to the given string. (Note that the rules guiding translation are different for output than for input.)

This means, when opening the file for writing, the newline parameter can be set to '' to achieve the desired output:

```<code>with open('test3.txt', mode='w', newline='') as f:
    f.write('test\r\ntest\r\n')
</code>```

Body:
I am using Python 3.6.3 on Windows.
When I try to print a single multiline string to file like this:

with open('test1.txt', mode='w') as f:
    f.write('test\r\ntest\r\n')

Then test1.txt will end up containing test\r\r\ntest\r\r\n instead of test\r\ntest\r\n.

A workaround to get the desired output would look like so:

with open('test2.txt', mode='w') as f:
    for line in 'test\r\ntest\r\n'.splitlines():
        print(line, file=f)

Why is this happening?

Body:
Well, turns out properly stating a question often leads to the answer presenting itself:

The reason for this behaviour is to be found with Python's universal newline (quoting from PEP 3116 on TextIOWrapper):

On output, if newline is None, any '\n' characters written are translated to the system default line separator, os.linesep. If newline is '', no translation takes place. If newline is any of the other legal values, any '\n' characters written are translated to the given string. (Note that the rules guiding translation are different for output than for input.)

This means, when opening the file for writing, the newline parameter can be set to '' to achieve the desired output:

with open('test3.txt', mode='w', newline='') as f:
    f.write('test\r\ntest\r\n')


问:
Changing image back to original after it is changed on hover?
I am attempting to use jQuery to hover over an image while it changes the other. I have that part done, the part I don't understand is when I hover over the image and then move the mouse off of it, how do I get the original image to come back? Any help would be greatly appreciated.

Here is what I have so far:

```<code>$(document).ready(function(){
     $("#04").hover(function(){
        $("#imgBig").attr("src", "imgLab10/04.jpg");
     });
});
</code>```

答:
.hover() accepts two callbacks, one for hoverIn and one for hoverOut.

So you could do something like

```<code>$(document).ready(function(){
    $("#04").hover(
        function(){
            $("#imgBig").attr("src", "imgLab10/04.jpg");
        },
        function() {
             $("#imgBig").attr("src", "oldImg.jpg");
        }
    );
});
</code>```

Body:
I am attempting to use jQuery to hover over an image while it changes the other. I have that part done, the part I don't understand is when I hover over the image and then move the mouse off of it, how do I get the original image to come back? Any help would be greatly appreciated.

Here is what I have so far:

$(document).ready(function(){
     $("#04").hover(function(){
        $("#imgBig").attr("src", "imgLab10/04.jpg");
     });
});

Body:
.hover() accepts two callbacks, one for hoverIn and one for hoverOut.

So you could do something like

$(document).ready(function(){
    $("#04").hover(
        function(){
            $("#imgBig").attr("src", "imgLab10/04.jpg");
        },
        function() {
             $("#imgBig").attr("src", "oldImg.jpg");
        }
    );
});


问:
Haskell - Couldn't match type `(Int, Integer)' with `Pos'
I am currently learning Haskell and I am currently having an issue.

This is my code:

```<code>data Pos = Pos (Int, Int) deriving (Show, Eq)
allCoordinates :: [Pos]
allCoordinates = concat [(zip (allHelper x) [0..8]) | x<-[0..8]]

allHelper ::Int -> [Int]
allHelper x = [x | y<-[0..8]]
</code>```

I have to use that specific data type and I am having a little issue due to this.

This code works perfectly fine if the code is written like this:

```<code>type Pos = (Int, Int)
allCoordinates :: [(Int, Int)]
allCoordinates = concat [(zip (allHelper x) [0..8]) | x<-[0..8]]
</code>```

but  I need to edit this bit:

```<code>concat [(zip (allHelper x) [0..8]) | x<-[0..8]]
</code>```

so that it works with:

```<code>allCoordinates :: [Pos]
</code>```

It is probably a simple issue and I having a bit of a mental block however can anyone help?

Thank you

答:
type defines a Type alias. That is to say, writing:

```<code>type Pos = (Int, Int)
</code>```

means that whenever you write Pos in your code, the compiler sees (Int, Int). To construct a Pos in this case, you can just write (1, 2), since an (Int, Int) and a Pos are indistinguishable.

However, data defines a new datatype. Your example is:

```<code>data Pos = Pos (Int, Int)
</code>```

Pos is a type constructed by the function Pos :: (Int, Int) -> Pos. These are not equal! To construct a Pos in this case, you would write Pos (1, 2).

To correct your code, write:

```<code>data Pos = Pos (Int, Int)
allCoordinates :: [(Int, Int)]
allCoordinates = concat [zipWith (curry Pos) (allHelper x) [0..8] | x<-[0..8]]
</code>```

Where zipWith :: (a -> b -> c) -> [a] -> [b] -> [c].

However, unless you want different behaviour in typeclasses, using a type alias would be best, otherwise, you should use a newtype.

Body:
I am currently learning Haskell and I am currently having an issue.

This is my code:

data Pos = Pos (Int, Int) deriving (Show, Eq)
allCoordinates :: [Pos]
allCoordinates = concat [(zip (allHelper x) [0..8]) | x<-[0..8]]

allHelper ::Int -> [Int]
allHelper x = [x | y<-[0..8]]

I have to use that specific data type and I am having a little issue due to this.

This code works perfectly fine if the code is written like this:

type Pos = (Int, Int)
allCoordinates :: [(Int, Int)]
allCoordinates = concat [(zip (allHelper x) [0..8]) | x<-[0..8]]

but  I need to edit this bit:

concat [(zip (allHelper x) [0..8]) | x<-[0..8]]

so that it works with:

allCoordinates :: [Pos]

It is probably a simple issue and I having a bit of a mental block however can anyone help?

Thank you

Body:
type defines a Type alias. That is to say, writing:

type Pos = (Int, Int)

means that whenever you write Pos in your code, the compiler sees (Int, Int). To construct a Pos in this case, you can just write (1, 2), since an (Int, Int) and a Pos are indistinguishable.

However, data defines a new datatype. Your example is:

data Pos = Pos (Int, Int)

Pos is a type constructed by the function Pos :: (Int, Int) -> Pos. These are not equal! To construct a Pos in this case, you would write Pos (1, 2).

To correct your code, write:

data Pos = Pos (Int, Int)
allCoordinates :: [(Int, Int)]
allCoordinates = concat [zipWith (curry Pos) (allHelper x) [0..8] | x<-[0..8]]

Where zipWith :: (a -> b -> c) -> [a] -> [b] -> [c].

However, unless you want different behaviour in typeclasses, using a type alias would be best, otherwise, you should use a newtype.


答:
The you have to use it like :

```<code>$( "#04" ).hover(
  function() {
    //When the mouse enter
    $("#imgBig").attr("src", "imgLab10/04.jpg");
  }, function() {
    //When the mouse out
    $("#imgBig").attr("src", "imgLab10/OriginalImage.jpg");
  }
);
</code>```

Hope this helps.

Title: Changing image back to original after it is changed on hover?

Body:
The you have to use it like :

$( "#04" ).hover(
  function() {
    //When the mouse enter
    $("#imgBig").attr("src", "imgLab10/04.jpg");
  }, function() {
    //When the mouse out
    $("#imgBig").attr("src", "imgLab10/OriginalImage.jpg");
  }
);

Hope this helps.


答:
JQuery .hover() method takes two function parameters. One is onMouseover event and the second is onMouseout event.

https://api.jquery.com/hover/

```<code>.hover(handlerIn, handlerOut)

handlerIn
Type: Function( Event eventObject )
A function to execute when the mouse pointer enters the element.

handlerOut
Type: Function( Event eventObject )
A function to execute when the mouse pointer leaves the element.
</code>```

Body:
JQuery .hover() method takes two function parameters. One is onMouseover event and the second is onMouseout event.

https://api.jquery.com/hover/

.hover(handlerIn, handlerOut)

handlerIn
Type: Function( Event eventObject )
A function to execute when the mouse pointer enters the element.

handlerOut
Type: Function( Event eventObject )
A function to execute when the mouse pointer leaves the element.


答:
I recommend you use .prop() instead of .attr() because it will eventually become deprecated.

If you want to change the image back, you need to use .mouseenter() and mouseleave()

```<code>$(document).ready(function() {

  $("#04").mouseenter(function() {
    $("#imgBig").prop("src", "imgLab10/04.jpg");
  });

  $("#04").mouseleave(function() {
    $("#imgBig").prop("src", "orignalPath");
  });
});
</code>```

I think this makes the code easier to understand because you're explicitly coding for both events, but that's just my opinion and .hover() also works well.

Body:
I recommend you use .prop() instead of .attr() because it will eventually become deprecated.

If you want to change the image back, you need to use .mouseenter() and mouseleave()

$(document).ready(function() {

  $("#04").mouseenter(function() {
    $("#imgBig").prop("src", "imgLab10/04.jpg");
  });

  $("#04").mouseleave(function() {
    $("#imgBig").prop("src", "orignalPath");
  });
});

I think this makes the code easier to understand because you're explicitly coding for both events, but that's just my opinion and .hover() also works well.


问:
Replace string that is separated by whitespace or other special character in PHP
I need to find a way to find part of the string in text and to replace it with ***

For example, I have text "Jumping fox jumps around the box"
in normal cases, I would use:

preg_replace('/\b(fox)\b/i', '****', "fox");

but I want to cover cases when we have text "Jumping f.o.x jumps around the box"
or "Jumping f o x jumps around the box"

So basically, I would need regex to support that kind of searches... to cover more special characters is even better

答:
One way would be to add the class of to be ignored chars between each char of the search string. This could  be done with simple php functions

```<code>$string = 'Jumping f.o.x jumps around the box';
$word = 'fox';
$ignore = '[\s\.]*';
$regex = '/\b' . join($ignore, str_split($word)) . '\b/i';
$new_string = preg_replace($regex, '***', $string);
</code>```

If your word contains some regex special chars, you might want to apply preg_quote to each char.

```<code>join($ignore, array_map(function($char) {
    return preg_quote($char, '/');
}, str_split($word)));
</code>```

Body:
One way would be to add the class of to be ignored chars between each char of the search string. This could  be done with simple php functions

$string = 'Jumping f.o.x jumps around the box';
$word = 'fox';
$ignore = '[\s\.]*';
$regex = '/\b' . join($ignore, str_split($word)) . '\b/i';
$new_string = preg_replace($regex, '***', $string);

If your word contains some regex special chars, you might want to apply preg_quote to each char.

join($ignore, array_map(function($char) {
    return preg_quote($char, '/');
}, str_split($word)));


问:
Spring MVC returning 406 to controller test
I have the following project tree:

```<code>├── app
│   ├── build.gradle
│   └── src
│       ├── main
│       │   ├── java
│       │   │   └── child
│       │   │       └── app
│       │   │           └── Application.java
│       │   └── resources
│       │       └── application-default.yaml
│       └── test
│           └── java
│               └── child
│                   └── app
│                       └── ApplicationTest.java
├── build.gradle
└── childA
    ├── build.gradle
    └── src
        ├── main
        │   └── java
        │       └── child
        │           └── a
        │               ├── CoreConfig.java
        │               ├── PingController.java
        │               └── SpringWebMvcInitializer.java
        └── test
            └── java
            │   └── child
            │       └── a
            │           └── PingControllerTest.java
            └── resources
                └── application-core.yml
</code>```

I have the following test class :

```<code>@RunWith(SpringRunner.class)
@ContextConfiguration(classes = { PingController.class, SpringWebMvcInitializer.class }, initializers = ConfigFileApplicationContextInitializer.class)
@WebAppConfiguration
@ActiveProfiles({ "core" })
public class PingControllerTest {

    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext webApplicationContext;

    @Before
    public void setUp() {
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }

    @Test
    public void testPing() throws Exception {
this.mockMvc.perform(get(CoreHttpPathStore.PING)).andDo(print());
this.mockMvc.perform(get(CoreHttpPathStore.PING).accept(MediaType.APPLICATION_JSON_UTF8_VALUE).contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)).andExpect(status().isOk());
    }

}
</code>```

I have the following PingController.java:

```<code>@RestController
public class PingController {

    @RequestMapping(value = CoreHttpPathStore.PING, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity<Map<String, Object>> ping() throws Exception {
        HashMap<String, Object> map = new HashMap<>();
        map.put("message", "Welcome to our API");
        map.put("date", new Date());
        map.put("status", HttpStatus.OK);
        return new ResponseEntity<>(map, HttpStatus.OK);
    }

}
</code>```

I have the following SpringWebMvcInitializer.java:

```<code>@ComponentScan
public class SpringWebMvcInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[]{};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[]{};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{ "/" };
    }

}
</code>```

Expected

I expect test to pass with http code 200.

Result

I get 406 and the following print():

```<code>04:29:47.488 [main] DEBUG org.springframework.test.web.servlet.TestDispatcherServlet - Successfully completed request

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /ping
       Parameters = {}
          Headers = {}

Handler:
             Type = com.kopaxgroup.api.core.controller.PingController

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = org.springframework.web.HttpMediaTypeNotAcceptableException

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 406
    Error message = null
          Headers = {}
     Content type = null
             Body =
    Forwarded URL = null
   Redirected URL = null
          Cookies = []
</code>```

Question

So here are my questions :

I have done some googling and most of the answers says that the context needs to be loaded with @ContextConfiguration("/test-context.xml"), I use JAVA configuration and I have no XML. Is my SpringWebMvcInitializer.java replacing that file and is it replacing it correctly ?

Why do I get 406 error ?

答:
Try doing below steps:

```<code>@Configuration
    @EnableWebMvc
    public static class PingControllerTestConfiguration {

        @Bean
        public PingController myController() {
            return new PingController();
        }
    }
</code>```

and

changing below

```<code>@ContextConfiguration(classes = { PingController.class, SpringWebMvcInitializer.class }, initializers = ConfigFileApplicationContextInitializer.class)
</code>```

to @ContextConfiguration

Body:
I have the following project tree:

├── app
│   ├── build.gradle
│   └── src
│       ├── main
│       │   ├── java
│       │   │   └── child
│       │   │       └── app
│       │   │           └── Application.java
│       │   └── resources
│       │       └── application-default.yaml
│       └── test
│           └── java
│               └── child
│                   └── app
│                       └── ApplicationTest.java
├── build.gradle
└── childA
    ├── build.gradle
    └── src
        ├── main
        │   └── java
        │       └── child
        │           └── a
        │               ├── CoreConfig.java
        │               ├── PingController.java
        │               └── SpringWebMvcInitializer.java
        └── test
            └── java
            │   └── child
            │       └── a
            │           └── PingControllerTest.java
            └── resources
                └── application-core.yml

I have the following test class :

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = { PingController.class, SpringWebMvcInitializer.class }, initializers = ConfigFileApplicationContextInitializer.class)
@WebAppConfiguration
@ActiveProfiles({ "core" })
public class PingControllerTest {

    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext webApplicationContext;

    @Before
    public void setUp() {
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }

    @Test
    public void testPing() throws Exception {
this.mockMvc.perform(get(CoreHttpPathStore.PING)).andDo(print());
this.mockMvc.perform(get(CoreHttpPathStore.PING).accept(MediaType.APPLICATION_JSON_UTF8_VALUE).contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)).andExpect(status().isOk());
    }

}

I have the following PingController.java:

@RestController
public class PingController {

    @RequestMapping(value = CoreHttpPathStore.PING, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity<Map<String, Object>> ping() throws Exception {
        HashMap<String, Object> map = new HashMap<>();
        map.put("message", "Welcome to our API");
        map.put("date", new Date());
        map.put("status", HttpStatus.OK);
        return new ResponseEntity<>(map, HttpStatus.OK);
    }

}

I have the following SpringWebMvcInitializer.java:

@ComponentScan
public class SpringWebMvcInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[]{};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[]{};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{ "/" };
    }

}

Expected

I expect test to pass with http code 200.

Result

I get 406 and the following print():

04:29:47.488 [main] DEBUG org.springframework.test.web.servlet.TestDispatcherServlet - Successfully completed request

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /ping
       Parameters = {}
          Headers = {}

Handler:
             Type = com.kopaxgroup.api.core.controller.PingController

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = org.springframework.web.HttpMediaTypeNotAcceptableException

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 406
    Error message = null
          Headers = {}
     Content type = null
             Body =
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

Question

So here are my questions :

I have done some googling and most of the answers says that the context needs to be loaded with @ContextConfiguration("/test-context.xml"), I use JAVA configuration and I have no XML. Is my SpringWebMvcInitializer.java replacing that file and is it replacing it correctly ?

Why do I get 406 error ?

Body:
Try doing below steps:

@Configuration
    @EnableWebMvc
    public static class PingControllerTestConfiguration {

        @Bean
        public PingController myController() {
            return new PingController();
        }
    }

and

changing below

@ContextConfiguration(classes = { PingController.class, SpringWebMvcInitializer.class }, initializers = ConfigFileApplicationContextInitializer.class)

to @ContextConfiguration


问:
SQL Server Create table to autoconvert int -> decimal
I'm not sure if this is possible but here goes.

I have financial data stored in a csv format. The data unfortunately lacks any decimal points in the dollar fields. so $100.00 is stored as '00000010000'. Its also stored as a string. In my current setup I upload the csv file into a staging table with all columns set to varchar(x).

I know that if I try to insert this value into an integer column it will automatically convert it to 10000 of type integer, but that means I am missing my decimal place.

Is there anyway I can create a table such that inserting an integer stored as a string or integer automatically converts it to an decimal with 2 places behind the decimal????

EX: '000010000' -> 100.00

I know I can cast the column to a decimal and divide the existing value by 100.... but this table has 100+ columns with 60+ of them needing to be recast. This is also only table 1 of 6. I want to avoid creating commands to individually changing the relevant columns. Not all columns containing a number need the decimal treatment.

答:
Just a little helper stored procedure, to convert imported table to required format.

You specify imported table name, converted table name, which will be created and comma separated list of columns which are not required to be converted.

SQL Fiddle

MS SQL Server 2014 Schema Setup:

```<code>create table source (
  id int not null identity(1,1),
  c1 varchar(100) not null,
  c2 varchar(100) not null,
  c3 varchar(100) not null,
  c4 varchar(100) not null,
  c5 varchar(100) not null,
  c6 varchar(100) not null
);

insert source (c1, c2, c3, c4, c5, c6) values
  ('a', '000001000', '000001000', '000001000', '000001000', 'b'),
  ('c', '000002001', '000002002', '000002003', '200020002', 'd'),
  ('e', '000003002', '000003002', '000003003', '300030003', 'f'),
  ('g', '000004003', '000004002', '000004003', '400040004', 'h'),
  ('i', '000005004', '000005002', '000005003', '500050005', 'j')
;

create procedure convert_table
  @source varchar(max),
  @dest varchar(max),
  @exclude_cols varchar(max)
as
begin
  declare
    @sql varchar(max) = 'select ',
    @col_name varchar(max)

  if @exclude_cols not like ',%' set @exclude_cols = ',' + @exclude_cols
  if @exclude_cols not like '%,' set @exclude_cols = @exclude_cols + ','

  declare c cursor for
  select column_name
  from information_schema.columns
  where table_name = @source

  open c
  fetch next from c into @col_name
  while @@fetch_status = 0
  begin
    if @exclude_cols like '%,' + @col_name + ',%'
      set @sql = @sql + @col_name + ','
    else
      set @sql = @sql + 'convert(numeric(11, 2), ' + @col_name + ') / 100 as ' + @col_name + ','

    fetch next from c into @col_name
  end
  close c
  deallocate c

  set @sql = substring(@sql, 1, len(@sql) -1)
  set @sql = @sql + ' into ' + @dest + ' from ' + @source

  --print(@sql)
  exec(@sql)
end
;

exec convert_table @source = 'source', @dest = 'dest', @exclude_cols = 'id,c1,c6'
</code>```

Query 1:

```<code>select * from dest
</code>```

Results:

```<code>| id | c1 |    c2 |    c3 |    c4 |         c5 | c6 |
|----|----|-------|-------|-------|------------|----|
|  1 |  a |    10 |    10 |    10 |         10 |  b |
|  2 |  c | 20.01 | 20.02 | 20.03 | 2000200.02 |  d |
|  3 |  e | 30.02 | 30.02 | 30.03 | 3000300.03 |  f |
|  4 |  g | 40.03 | 40.02 | 40.03 | 4000400.04 |  h |
|  5 |  i | 50.04 | 50.02 | 50.03 | 5000500.05 |  j |
</code>```

Body:
Just a little helper stored procedure, to convert imported table to required format.

You specify imported table name, converted table name, which will be created and comma separated list of columns which are not required to be converted.

SQL Fiddle

MS SQL Server 2014 Schema Setup:

create table source (
  id int not null identity(1,1),
  c1 varchar(100) not null,
  c2 varchar(100) not null,
  c3 varchar(100) not null,
  c4 varchar(100) not null,
  c5 varchar(100) not null,
  c6 varchar(100) not null
);

insert source (c1, c2, c3, c4, c5, c6) values
  ('a', '000001000', '000001000', '000001000', '000001000', 'b'),
  ('c', '000002001', '000002002', '000002003', '200020002', 'd'),
  ('e', '000003002', '000003002', '000003003', '300030003', 'f'),
  ('g', '000004003', '000004002', '000004003', '400040004', 'h'),
  ('i', '000005004', '000005002', '000005003', '500050005', 'j')
;

create procedure convert_table
  @source varchar(max),
  @dest varchar(max),
  @exclude_cols varchar(max)
as
begin
  declare
    @sql varchar(max) = 'select ',
    @col_name varchar(max)

  if @exclude_cols not like ',%' set @exclude_cols = ',' + @exclude_cols
  if @exclude_cols not like '%,' set @exclude_cols = @exclude_cols + ','

  declare c cursor for
  select column_name
  from information_schema.columns
  where table_name = @source

  open c
  fetch next from c into @col_name
  while @@fetch_status = 0
  begin
    if @exclude_cols like '%,' + @col_name + ',%'
      set @sql = @sql + @col_name + ','
    else
      set @sql = @sql + 'convert(numeric(11, 2), ' + @col_name + ') / 100 as ' + @col_name + ','

    fetch next from c into @col_name
  end
  close c
  deallocate c

  set @sql = substring(@sql, 1, len(@sql) -1)
  set @sql = @sql + ' into ' + @dest + ' from ' + @source

  --print(@sql)
  exec(@sql)
end
;

exec convert_table @source = 'source', @dest = 'dest', @exclude_cols = 'id,c1,c6'

Query 1:

select * from dest

Results:

| id | c1 |    c2 |    c3 |    c4 |         c5 | c6 |
|----|----|-------|-------|-------|------------|----|
|  1 |  a |    10 |    10 |    10 |         10 |  b |
|  2 |  c | 20.01 | 20.02 | 20.03 | 2000200.02 |  d |
|  3 |  e | 30.02 | 30.02 | 30.03 | 3000300.03 |  f |
|  4 |  g | 40.03 | 40.02 | 40.03 | 4000400.04 |  h |
|  5 |  i | 50.04 | 50.02 | 50.03 | 5000500.05 |  j |


问:
Clojure def giving UnsupportedOperationException
I am trying to ping fleetdb from a clojure client.  When I ping the server, I get back the response "pong", but when I try to save it to a variable using def, I get  "UnsupportedOperationException applyTo".

```<code>(use 'fleetdb.client)

(def client (connect {:host "127.0.0.1", :port 3400}))

(client ["ping"]) ; get back "pong" as response

(type  (client ["ping"]))   ;java.lang.String

(print (client ["ping"]))   ; get back "pong" as response

(def isalive (client ["ping"]))

; UnsupportedOperationException applyTo  fleetdb.client.proxy$java.lang.Object$IFn

; $ILookup$Closeable$9aed515e.applyTo (:-1)
</code>```

Tried with clojure 1.2 and 1.3.0-alpha4

What is wrong?

答:
Seems the client proxy does not define the applyTo method which is part of IFn interface:

https://github.com/mmcgrana/fleetdb-client/blob/master/src/fleetdb/client.clj#L54

This will work:

```<code>user> (def x (.invoke client ["ping"]))
#'user/x
</code>```

Need to check out, why applyTo is used instead of invoke

ContentLicense: CC BY-SA 2.5

Body:
I am trying to ping fleetdb from a clojure client.  When I ping the server, I get back the response "pong", but when I try to save it to a variable using def, I get  "UnsupportedOperationException applyTo".

(use 'fleetdb.client)

(def client (connect {:host "127.0.0.1", :port 3400}))

(client ["ping"]) ; get back "pong" as response

(type  (client ["ping"]))   ;java.lang.String

(print (client ["ping"]))   ; get back "pong" as response

(def isalive (client ["ping"]))

; UnsupportedOperationException applyTo  fleetdb.client.proxy$java.lang.Object$IFn

; $ILookup$Closeable$9aed515e.applyTo (:-1)

Tried with clojure 1.2 and 1.3.0-alpha4

What is wrong?

Body:
Seems the client proxy does not define the applyTo method which is part of IFn interface:

https://github.com/mmcgrana/fleetdb-client/blob/master/src/fleetdb/client.clj#L54

This will work:

user> (def x (.invoke client ["ping"]))
#'user/x

Need to check out, why applyTo is used instead of invoke


问:
Minesweeper algorithm for finding neighbours?
Im programming in c the minesweeper game.
im pretty at the end.
I have only problem with the last part.

in the game (see picture) when I click on the upper left field, the fields where no mine is are turned around and at the border there are numbers.

how is the algorithm for finding this field and turn them around or to show them .... I mean algorithm for the field in the green circle?

答:
I am doing a design from scratch, I hope it helps you.

If my game arena is nxn matrix of integers,

```<code>0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
</code>```

I can model placing a bomb in that matrix by applying such a 3x3 matrix:

```<code>1 1 1
1 9 1
1 1 1
</code>```

Here 9 denotes a bomb, you probably need to use a bigger integer. And when I say apply, I pick the location and increment it by the numbers in that 3x3 matrix. So let's place 1 bomb:

```<code>0 1 1 1 0
0 1 9 1 0
0 1 1 1 0
0 0 0 0 0
0 0 0 0 0
</code>```

Let's place another bomb, just next to the first one. And let's be a bit clever and not increment the location when the initial value in a cell is 9.

```<code>0 1 2 2 1
0 1 9 9 1
0 1 2 2 1
0 0 0 0 0
0 0 0 0 0
</code>```

Let's place another one this time somewhere below.

```<code>0 1 2 2 1
0 1 9 9 1
0 1 3 3 2
0 0 1 9 1
0 0 1 1 1
</code>```

So if I try to start revealing numbers from bottom right. What should be my algorithm? Here is my take:

```<code>function revealCell(location)
{
   if(cellValueIsRevealed(location)) {
       return;
   }
   var value = revealValueOfCell(location);
   if(value > 0)
   {
       return;
   }

   foreach(neighbor in neighbors)
   {
       revealCell(neighbor);
   }
}
</code>```

To implement cellValueIsRevealed method, one way would be to implement a matrix of booleans.

Body:
I am doing a design from scratch, I hope it helps you.

If my game arena is nxn matrix of integers,

0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0

I can model placing a bomb in that matrix by applying such a 3x3 matrix:

1 1 1
1 9 1
1 1 1

Here 9 denotes a bomb, you probably need to use a bigger integer. And when I say apply, I pick the location and increment it by the numbers in that 3x3 matrix. So let's place 1 bomb:

0 1 1 1 0
0 1 9 1 0
0 1 1 1 0
0 0 0 0 0
0 0 0 0 0

Let's place another bomb, just next to the first one. And let's be a bit clever and not increment the location when the initial value in a cell is 9.

0 1 2 2 1
0 1 9 9 1
0 1 2 2 1
0 0 0 0 0
0 0 0 0 0

Let's place another one this time somewhere below.

0 1 2 2 1
0 1 9 9 1
0 1 3 3 2
0 0 1 9 1
0 0 1 1 1

So if I try to start revealing numbers from bottom right. What should be my algorithm? Here is my take:

function revealCell(location)
{
   if(cellValueIsRevealed(location)) {
       return;
   }
   var value = revealValueOfCell(location);
   if(value > 0)
   {
       return;
   }

   foreach(neighbor in neighbors)
   {
       revealCell(neighbor);
   }
}

To implement cellValueIsRevealed method, one way would be to implement a matrix of booleans.


问:
How to use Entity DataSource with subquery in Code Behind
I am using RadGrid in Telerik and I am trying to use entity DataSource in code behind.  Initially, the RadGrid loads fine when the page loads but I am having an issue when i try to filter the RadGrid values based on the TextBox input value. I am getting this error

"PART_NUMBER' could not be resolved in the current scope or context.
  Make sure that all referenced variables are in scope, that required
  schemas are loaded, and that namespaces are referenced correctly."

Here is my code:

```<code>protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        EntityDataSource1.CommandText = "DetailData";
    }
}

 protected void FilterBtn_Click(object sender, Telerik.Web.UI.ImageButtonClickEventArgs e)
 {
     string partNumber = PartNumberTB.Text;
     EntityDataSource1.CommandText = @"SELECT value p FROM DetailData as p
 where REFERENCE_NUM in (select distinct REFERENCE_NUM from DetailData
  where (DetailData.PART_NUMBER like  '" + partNumber + "%' or PART_NUMBER = ''))";
 }
</code>```

答:
Try using aliases in your query and see if that helps.

SELECT value p FROM DetailData as p
WHERE p.REFERENCE_NUM in (select distinct s.REFERENCE_NUM from DetailData as s
WHERE (p.PART_NUMBER like  '" + partNumber + "%' or s.PART_NUMBER = ''))
```

<p>Here is a reference to Subqueries with Aliases</p>

<p><strong>Edit:</strong></p>

<p>You can test the query on w3schools - SQL Statement with the following code:</p>

<pre class="lang-sql prettyprint-override"><code>SELECT p.* FROM OrderDetails AS p
WHERE p.OrderID IN (SELECT DISTINCT s.OrderID FROM OrderDetails AS s
WHERE (p.OrderDetailID LIKE '2%' OR s.OrderDetailID = 20))
</code>```

Body:
I am using RadGrid in Telerik and I am trying to use entity DataSource in code behind.  Initially, the RadGrid loads fine when the page loads but I am having an issue when i try to filter the RadGrid values based on the TextBox input value. I am getting this error

"PART_NUMBER' could not be resolved in the current scope or context.
  Make sure that all referenced variables are in scope, that required
  schemas are loaded, and that namespaces are referenced correctly."

Here is my code:

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        EntityDataSource1.CommandText = "DetailData";
    }
}

 protected void FilterBtn_Click(object sender, Telerik.Web.UI.ImageButtonClickEventArgs e)
 {
     string partNumber = PartNumberTB.Text;
     EntityDataSource1.CommandText = @"SELECT value p FROM DetailData as p
 where REFERENCE_NUM in (select distinct REFERENCE_NUM from DetailData
  where (DetailData.PART_NUMBER like  '" + partNumber + "%' or PART_NUMBER = ''))";
 }

Body:
Try using aliases in your query and see if that helps.

SELECT value p FROM DetailData as p
WHERE p.REFERENCE_NUM in (select distinct s.REFERENCE_NUM from DetailData as s
WHERE (p.PART_NUMBER like  '" + partNumber + "%' or s.PART_NUMBER = ''))

Here is a reference to Subqueries with Aliases

Edit:

You can test the query on w3schools - SQL Statement with the following code:

SELECT p.* FROM OrderDetails AS p
WHERE p.OrderID IN (SELECT DISTINCT s.OrderID FROM OrderDetails AS s
WHERE (p.OrderDetailID LIKE '2%' OR s.OrderDetailID = 20))


问:
How to store different method pointers in one container in delphi?
I have the following method pointers

```<code>type
  TMethod1 = procedure(aValue: TType1) of object;
  TMethod2 = procedure(aValue: TType2) of object;
  .
  .
  TMethodN = procedure(aValue: TTypeN) of object;
</code>```

I want to store them in one container.

I found this answer, where a pointer to TMethod1 is used to store one method and then call it. However, I would rather not use it for the following reasons:

It allocates new block of memory and then later I should decide when to free it(never made it out of that area in one piece).

It assumes all methods have the same definition, which is not my case.

It is for one method. I have an array of them, and I do not see how I'm going to maintain such storage.

And there is an example in the documentation which uses a TMethod approach, but in a different way where the second assumption above is no longer needed.  In the last step to call the method, I have to do an unsafe typecast, which again is something I would like to stay away from.

How do I accomplish this?

Clarification on how I'm going to use these methods:

I have a

```<code>procedure DoWork(aData: TType1; method: TMethod1);
begin
  store aData in a field;
  store method in my container;
end;
</code>```

Then later, process aData and call method.

答:
Whatever you store in your container must be the same type.  You can use TMethod for that.  It is a special record type provided by the RTL to represents any of object method pointer.

The hard part is going to be calling the methods that are stored in your container.  You can't just call TMethod directly, you have to know the exact method type that it is pointing at, then type-cast it to that type.  For example:

```<code>var
  Field: TObject; // assuming TType... are class types
  Container: TList<TMethod>;

procedure DoWork<T>(aData: T; method: procedure(aValue: T) of object);
var
  M: TMethod;
begin
  M := TMethod(method);
  Field := aData;
  Container.Add(M);
end;

procedure CallFieldMethod;
var
  M: TMethod;
begin
  M := Container[Index];
  if Field.ClassType = TType1 then
  begin
    TMethod1(M)(TType1(Field));
  end
  else if Field.ClassType = TType2 then
  begin
    TMethod2(M)(TType2(Field));
  end
  ...
end;

...

procedure TSomeClass.MethodForType1(aValue: TType1);
begin
  // use aValue as needed...
end;

DoWork<TType1>(Type1Obj, MethodForType1);

...

procedure TSomeClass.MethodForType2(aValue: TType2);
begin
  // use aValue as needed...
end;

DoWork<TType2>(Type2Obj, MethodForType2);

...
</code>```

Another solution is to not rely on specific types at all, and just define 1 method type for the container.  Let the caller of DoWork() decide what to do:

```<code>type
  TMyMethod = procedure(aValue: Pointer) of object;

var
  Field: Pointer;
  Container: TList<TMyMethod>;

procedure DoWork(aData: Pointer; method: TMyMethod);
begin
  Field := aData;
  Container.Add(method);
end;

procedure CallFieldMethod;
begin
  Container[Index](Field);
end;

...

procedure TSomeClass.MethodForType1(aValue: Pointer);
begin
  // use TType1(aValue) as needed...
end;

DoWork(Type1Obj, MethodForType1);

...

procedure TSomeClass.MethodForType2(aValue: Pointer);
begin
  // use TType2(aValue) as needed...
end;

DoWork(Type2Obj, MethodForType2);

...
</code>```

Body:
I have the following method pointers

type
  TMethod1 = procedure(aValue: TType1) of object;
  TMethod2 = procedure(aValue: TType2) of object;
  .
  .
  TMethodN = procedure(aValue: TTypeN) of object;

I want to store them in one container.

I found this answer, where a pointer to TMethod1 is used to store one method and then call it. However, I would rather not use it for the following reasons:

It allocates new block of memory and then later I should decide when to free it(never made it out of that area in one piece).

It assumes all methods have the same definition, which is not my case.

It is for one method. I have an array of them, and I do not see how I'm going to maintain such storage.

And there is an example in the documentation which uses a TMethod approach, but in a different way where the second assumption above is no longer needed.  In the last step to call the method, I have to do an unsafe typecast, which again is something I would like to stay away from.

How do I accomplish this?

Clarification on how I'm going to use these methods:

I have a

procedure DoWork(aData: TType1; method: TMethod1);
begin
  store aData in a field;
  store method in my container;
end;

Then later, process aData and call method.

Body:
Whatever you store in your container must be the same type.  You can use TMethod for that.  It is a special record type provided by the RTL to represents any of object method pointer.

The hard part is going to be calling the methods that are stored in your container.  You can't just call TMethod directly, you have to know the exact method type that it is pointing at, then type-cast it to that type.  For example:

var
  Field: TObject; // assuming TType... are class types
  Container: TList<TMethod>;

procedure DoWork<T>(aData: T; method: procedure(aValue: T) of object);
var
  M: TMethod;
begin
  M := TMethod(method);
  Field := aData;
  Container.Add(M);
end;

procedure CallFieldMethod;
var
  M: TMethod;
begin
  M := Container[Index];
  if Field.ClassType = TType1 then
  begin
    TMethod1(M)(TType1(Field));
  end
  else if Field.ClassType = TType2 then
  begin
    TMethod2(M)(TType2(Field));
  end
  ...
end;

...

procedure TSomeClass.MethodForType1(aValue: TType1);
begin
  // use aValue as needed...
end;

DoWork<TType1>(Type1Obj, MethodForType1);

...

procedure TSomeClass.MethodForType2(aValue: TType2);
begin
  // use aValue as needed...
end;

DoWork<TType2>(Type2Obj, MethodForType2);

...

Another solution is to not rely on specific types at all, and just define 1 method type for the container.  Let the caller of DoWork() decide what to do:

type
  TMyMethod = procedure(aValue: Pointer) of object;

var
  Field: Pointer;
  Container: TList<TMyMethod>;

procedure DoWork(aData: Pointer; method: TMyMethod);
begin
  Field := aData;
  Container.Add(method);
end;

procedure CallFieldMethod;
begin
  Container[Index](Field);
end;

...

procedure TSomeClass.MethodForType1(aValue: Pointer);
begin
  // use TType1(aValue) as needed...
end;

DoWork(Type1Obj, MethodForType1);

...

procedure TSomeClass.MethodForType2(aValue: Pointer);
begin
  // use TType2(aValue) as needed...
end;

DoWork(Type2Obj, MethodForType2);

...


问:
How to extract a representative subset of triples from a triple store
We have an OpenLink Virtuoso-based triple (or rather quad-) store with about ~6bn triples in it. Our collaborators are asking us to give them a small subset of the data so they can test some of their queries and algorithms. Naturally, if we extract a random subset of graph-subject-predicate-object quads from the entire set, most of their SPARQL queries against the subset will find no solutions, because a small random subset of quads will represent an almost entirely disconnected graph. Is there a technique (possibly Virtuoso-specific) that would allow the extraction of a subset of quads s from the entire set S such that, for a given “select” or “construct” SPARQL query Q, Q executed against s would return the same solution as Q executed against the entire set S? If this could be done, it would be possible to run all sample queries that the collaborators want to be able to run against our dataset, extract that smallest possible subset and send it to them (as an n-quads file) so they can load it into their triple store.</p>

答:
This doesn't have a pre-built Virtuoso-specific solution. (ObDisclaimer: OpenLink Software produces Virtuoso, and employs me.)

As noted in the comments above, it's actually a rather complex question.  From many perspectives, the simple answer to "what is the minimal set to deliver the same result to the same query" is "all of it," and this might well work out to be the final answer, due to the effort needed to arrive at any satisfactory smaller subset.

The following are more along the lines of experimental exploration, than concrete advice.

It sounds like your collaborators want to run some known query, so I'd start by running that query against your full dataset, and then do a DESCRIBE over each ?s and ?p and ?o that appears the in the result, load all that output as your subset, and test the original query against that.

If known, explicitly including all the ontological data from the large set in the small may help.

If this sequence doesn't deliver the expected result set, you might try a second, third, or more rounds of the DESCRIBE, this time targeting every new ?s and ?p and ?o that appeared in the previous round.

The idea of exposing your existing endpoint, with the full data set, to your collaborators is worth considering.  You could grant them only READ permissions and/or adjust server configuration to limit the processing time, result set size, and other aspects of their activity.

A sideways approach to this that may help in thinking about it might be to consider that in the SQL Relational Table world, a useful subset of a single table is easy -- it can be just a few rows, that include at least the one(s) that you want your query to return (and often at least a few that you want your query to not return).

With a SQL Relational Schema involving multiple Tables, the useful subset extends to include the rows of each table which are relationally connected to the (un)desired row(s) in any of the others.

Now, in the RDF Relational Graph world, each "row" of those SQL Relational Tables might be thought of as having been decomposed, with the primary key of each table becoming a ?s, and each column/field becoming a ?p, and each value becoming a ?o.

The reality is (obviously?) more complex (you might look at the W3C RDF2RDF work, and the Direct Mapping and R2RML results of that work, for more detail), but this gives a conceptual starting point for considering how to find the quads (or triples) from an RDF dataset that comprise the minimum sub-dataset that will satisfy a given query against both dataset and subdataset.


问:
could not deserialize] with root cause java.io.EOFException: null
I have seen some questions on this subject but I have not got any valid solution for my case

I'm having an exception with jason serialization I have the following classes

when I do a GET Pacientes I have an exception of the serialization privilege type

```<code>2017-11-14 08:54:35.039  INFO 8724 --- [nio-8080-exec-1] o.h.e.internal.DefaultLoadEventListener  : HHH000327: Error performing load command : org.hibernate.type.SerializationException: could not deserialize
2017-11-14 08:54:35.047 ERROR 8724 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException: could not deserialize; nested exception is org.hibernate.type.SerializationException: could not deserialize] with root cause

    java.io.EOFException: null
        at java.io.ObjectInputStream$PeekInputStream.readFully(Unknown Source) ~[na:1.8.0_144]
        at java.io.ObjectInputStream$BlockDataInputStream.readShort(Unknown Source) ~[na:1.8.0_144]
        at java.io.ObjectInputStream.readStreamHeader(Unknown Source) ~[na:1.8.0_144]
        at java.io.ObjectInputStream.<init>(Unknown Source) ~[na:1.8.0_144]
        at org.hibernate.internal.util.SerializationHelper$CustomObjectInputStream.<init>(SerializationHelper.java:309) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
        at org.hibernate.internal.util.SerializationHelper$CustomObjectInputStream.<init>(SerializationHelper.java:299) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
        at org.hibernate.internal.util.SerializationHelper.doDeserialize(SerializationHelper.java:218) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
</code>```

I'm using framwork Spring boot with spring data jpa

class Paciente

```<code>import java.io.Serializable;
import java.math.BigInteger;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import digifred.model.global.Entidades;
import digifred.model.global.IdentidadesGenero;
import digifred.model.global.OrientacoesSexuais;
import digifred.model.global.Pessoas;

@Entity
@Table(name = "pacientes", schema = "sau")
public class Pacientes implements Serializable  {

    private static final long serialVersionUID = 5776384003601026304L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "idPaciente")
    private Long idPaciente;

    @JoinColumn(name="id_entidade")
    @ManyToOne(cascade = CascadeType.ALL)
    private Entidades entidade;

    @Basic(optional = false)
    @JoinColumn(name="idPessoa")
    @ManyToOne(cascade = CascadeType.ALL)
    private Pessoas pessoa;

    @Column(name = "idResponsavel_familiar")
    private BigInteger responsavelFamiliar;

    @Column(name = "nomeResponsavel")
    private String nomeResponsavel;

    @Column(name = "cpfResponsavel")
    private String cpfResponsavel;

    @Column(name = "cnsResponsavel")
    private String cnsResponsavel;

    @Column(name = "flagAlergico")
    private Integer flagAlergico;

    @Column(name = "observacoesAlergias")
    private String observacoesAlergias;

    @Column(name = "microarea")
    private String microarea;

    @Column(name = "idDomicilio")
    private Long idDomicilio;

    @JoinColumn(name="idOrientacaoSexual")
    @ManyToOne
    private OrientacoesSexuais orientacaoSexual;

    @JoinColumn(name="idIdentidadeGenero", insertable=false, updatable=false)
    @ManyToOne
    private IdentidadesGenero identidadeGenero;

    @Basic(optional = false)
    @Column(name = "flag_ativo")
    private int flagAtivo;

    @JoinColumn(name="idArea")
    @ManyToOne
    private Areas area;

    @JoinColumn(name="idFamilia")
    @ManyToOne
    private Familias familia;

    public Pacientes() {
    }

 getters and setters
}
</code>```

答: Looks like you're trying to deserialize an empty stream.</p>

Body:
I have seen some questions on this subject but I have not got any valid solution for my case

I'm having an exception with jason serialization I have the following classes

when I do a GET Pacientes I have an exception of the serialization privilege type

2017-11-14 08:54:35.039  INFO 8724 --- [nio-8080-exec-1] o.h.e.internal.DefaultLoadEventListener  : HHH000327: Error performing load command : org.hibernate.type.SerializationException: could not deserialize
2017-11-14 08:54:35.047 ERROR 8724 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException: could not deserialize; nested exception is org.hibernate.type.SerializationException: could not deserialize] with root cause

    java.io.EOFException: null
        at java.io.ObjectInputStream$PeekInputStream.readFully(Unknown Source) ~[na:1.8.0_144]
        at java.io.ObjectInputStream$BlockDataInputStream.readShort(Unknown Source) ~[na:1.8.0_144]
        at java.io.ObjectInputStream.readStreamHeader(Unknown Source) ~[na:1.8.0_144]
        at java.io.ObjectInputStream.<init>(Unknown Source) ~[na:1.8.0_144]
        at org.hibernate.internal.util.SerializationHelper$CustomObjectInputStream.<init>(SerializationHelper.java:309) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
        at org.hibernate.internal.util.SerializationHelper$CustomObjectInputStream.<init>(SerializationHelper.java:299) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
        at org.hibernate.internal.util.SerializationHelper.doDeserialize(SerializationHelper.java:218) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]

I'm using framwork Spring boot with spring data jpa

class Paciente

import java.io.Serializable;
import java.math.BigInteger;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import digifred.model.global.Entidades;
import digifred.model.global.IdentidadesGenero;
import digifred.model.global.OrientacoesSexuais;
import digifred.model.global.Pessoas;

@Entity
@Table(name = "pacientes", schema = "sau")
public class Pacientes implements Serializable  {

    private static final long serialVersionUID = 5776384003601026304L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "idPaciente")
    private Long idPaciente;

    @JoinColumn(name="id_entidade")
    @ManyToOne(cascade = CascadeType.ALL)
    private Entidades entidade;

    @Basic(optional = false)
    @JoinColumn(name="idPessoa")
    @ManyToOne(cascade = CascadeType.ALL)
    private Pessoas pessoa;

    @Column(name = "idResponsavel_familiar")
    private BigInteger responsavelFamiliar;

    @Column(name = "nomeResponsavel")
    private String nomeResponsavel;

    @Column(name = "cpfResponsavel")
    private String cpfResponsavel;

    @Column(name = "cnsResponsavel")
    private String cnsResponsavel;

    @Column(name = "flagAlergico")
    private Integer flagAlergico;

    @Column(name = "observacoesAlergias")
    private String observacoesAlergias;

    @Column(name = "microarea")
    private String microarea;

    @Column(name = "idDomicilio")
    private Long idDomicilio;

    @JoinColumn(name="idOrientacaoSexual")
    @ManyToOne
    private OrientacoesSexuais orientacaoSexual;

    @JoinColumn(name="idIdentidadeGenero", insertable=false, updatable=false)
    @ManyToOne
    private IdentidadesGenero identidadeGenero;

    @Basic(optional = false)
    @Column(name = "flag_ativo")
    private int flagAtivo;

    @JoinColumn(name="idArea")
    @ManyToOne
    private Areas area;

    @JoinColumn(name="idFamilia")
    @ManyToOne
    private Familias familia;

    public Pacientes() {
    }

 getters and setters
}


问:
Tomcat & Eclipse integration
I'm developing on a Ubuntu 8.04 machine using Eclipse Ganymede. I installed Tomcat 5.5 using sudo apt-get install tomcat5.5 tomcat5.5-admin and using an Ant script I deploy my WAR file by copying it to $CATALINA_HOME/webapps.

I then created an Eclipse project and I have it output compiled source in a similar but separate directory structure under $PROJECT_ROOT/target/. I still deploy the WAR file by right clicking on the build.xml and choosing my deploy-war task.

As Tomcat is running as a deamon, automatically started up on booting, I'm not instructing it when to start or exit.

My problems with this setup are:

Using this approach I do not get any output to the Eclipse console, as Tomcat is running under the tomcat55 user and I have a different login and no access to Stdout of tomcat55.

The logging which occurs is also directed to Stdout at the moment, which I find pretty nice during development. But it's not nice when I can't see it. :-)

I don't have any servers under the Server tab and no Run configurations. This makes it impossible for me to use the Debug mode of Eclipse, which otherwise is quite convenient.

What do you think I should do to integrate them and in turn make my development environment much better?

答: Add Tomcat to the list of Eclipse servers and run your web-app on the server. If you need more details click here.</p>

Title: Tomcat & Eclipse integration

OwnerDisplayName: Boris Pavlović


问:
convert png to pdf using ghostscript
as the title says I am trying to convert png to pdf.
I could not find well described example anywhere about this.

I used this command

```<code>gs sDEVICE=pdfwrite -dNOPAUSE -dBATCH -dSAFER -sOutputFile=test.pdf test.png
</code>```

but all I get is

```<code>Error: /syntaxerror in (binary token, type=137)
Operand stack:

Execution stack:
   %interp_exit   .runexec2   --nostringval--   --nostringval--   --nostringval--   2   %stopped_push   --nostringval--   --nostringval--   --nostringval--   false   1   %stopped_push   1894   1   3   %oparray_pop   1893   1   3   %oparray_pop   1877   1   3   %oparray_pop   1771   1   3   %oparray_pop   --nostringval--   %errorexec_pop   .runexec2   --nostringval--   --nostringval--   --nostringval--   2   %stopped_push
Dictionary stack:
   --dict:1161/1684(ro)(G)--   --dict:0/20(G)--   --dict:77/200(L)--
Current allocation mode is local
GPL Ghostscript 9.07: Unrecoverable error, exit code 1
</code>```

this error message. And now I started wodering if such feature is possible in ghostscript. Should I use other software?
** I'm runing the latest 9.07 version

答:
Yes, image magick can do this no problem - here's the cmd line for looping through all the pngs in a folder and converting to pdf:

cd to the folder with the pngs

mogrify -format pdf -density 300 -units PixelsPerInch *png

Title: convert png to pdf using ghostscript

Body:
as the title says I am trying to convert png to pdf.
I could not find well described example anywhere about this.

I used this command

gs sDEVICE=pdfwrite -dNOPAUSE -dBATCH -dSAFER -sOutputFile=test.pdf test.png

but all I get is

Error: /syntaxerror in (binary token, type=137)
Operand stack:

Execution stack:
   %interp_exit   .runexec2   --nostringval--   --nostringval--   --nostringval--   2   %stopped_push   --nostringval--   --nostringval--   --nostringval--   false   1   %stopped_push   1894   1   3   %oparray_pop   1893   1   3   %oparray_pop   1877   1   3   %oparray_pop   1771   1   3   %oparray_pop   --nostringval--   %errorexec_pop   .runexec2   --nostringval--   --nostringval--   --nostringval--   2   %stopped_push
Dictionary stack:
   --dict:1161/1684(ro)(G)--   --dict:0/20(G)--   --dict:77/200(L)--
Current allocation mode is local
GPL Ghostscript 9.07: Unrecoverable error, exit code 1

this error message. And now I started wodering if such feature is possible in ghostscript. Should I use other software?
** I'm runing the latest 9.07 version


问:
Bash on Ubuntu on Windows can't use `sudo apt-get install <packagename>`
I was excited to use bash on windows but quickly ran into an issue. I am trying to install build-essential, but I get a dependency issue. Upon trying to resolve with sudo apt-get install -f, I run into another error that doesn't make much sense. I've tried update and upgrade, but that didn't work either. F

```<code>barzevp@UK-LT-8356:~$ sudo apt-get install build-essential
Reading package lists... Done
Building dependency tree
Reading state information... Done
build-essential is already the newest version.
You might want to run 'apt-get -f install' to correct these:
The following packages have unmet dependencies.
 libc6-dev : Depends: linux-libc-dev but it is not going to be installed
E: Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution).
barzevp@UK-LT-8356:~$ sudo apt-get -f install
Reading package lists... Done
Building dependency tree
Reading state information... Done
Correcting dependencies... Done
The following packages were automatically installed and are no longer required:
  libfreetype6 os-prober
Use 'apt-get autoremove' to remove them.
The following extra packages will be installed:
  linux-libc-dev
The following NEW packages will be installed
  linux-libc-dev
0 to upgrade, 1 to newly install, 0 to remove and 43 not to upgrade.
5 not fully installed or removed.
Need to get 0 B/767 kB of archives.
After this operation, 3,946 kB of additional disk space will be used.
Do you want to continue? [Y/n] y
(Reading database ... 28660 files and directories currently installed.)
Preparing to unpack .../linux-libc-dev_3.13.0-123.172_amd64.deb ...
Unpacking linux-libc-dev:amd64 (3.13.0-123.172) ...
dpkg: error processing archive /var/cache/apt/archives/linux-libc-dev_3.13.0-123.172_amd64.deb (--unpack):
 unable to install new version of /usr/include/linux/netfilter_ipv6/ip6t_hl.h': File exists
E: Sub-process /usr/bin/dpkg returned an error code (1)
</code>```

Full log of what led to the error in Bash on Ubuntu on Windows terminal is here:
https://pastebin.com/dq2D2Gtz

答:
I don't have a solution, but I see the root of the problem.  It seems to have to do with case sensitivity on the filesystem.  The package for linux-libc-dev puts two copies of a file in /usr/include/linux/netfilter_ipv6 with only a difference in case; ip6t_HL.h, and ip6t_hl.h.  After placing ip6t_HL.h, it attempts to rename ip6t_hl.h.dpkg-new to ip6t_hl.h.  The system call to rename the file fails, claiming that ip6t_hl.h already exists

On a "real" linux system, ip6t_HL.h and ip6t_hl.h would clearly be different files.  Under WSL they probably had some strange incompatibilities to work out between NTFS's default case insensitive FS and unix's default case sensitivity.

You can duplicate the problem by hand e.g., with

```<code>echo hi > foo.H
echo hi > foo.h-new
mv foo.h-new foo.h
</code>```

mv: cannot move 'foo.h-new' to 'foo.h': File exists

strace output:

```<code>rename("/usr/include/linux/netfilter_ipv6/ip6t_HL.h.dpkg-new", "/usr/include/linux/netfilter_ipv6/ip6t_HL.h") = 0
open("/usr/include/linux/netfilter_ipv6/ip6t_hl.h.dpkg-new", O_WRONLY) = 10
fsync(10)                               = 0
close(10)                               = 0
rename("/usr/include/linux/netfilter_ipv6/ip6t_hl.h.dpkg-new", "/usr/include/linux/netfilter_ipv6/ip6t_hl.h") = -1 EEXIST (File exists)
write(2, "dpkg: error processing archive /"..., 199dpkg: error processing archive /var/cache/apt/archives/linux-libc-dev_4.4.0-98.121_amd64.deb (--install):
 unable to install new version of '/usr/include/linux/netfilter_ipv6/ip6t_hl.h': File exists
) = 199
</code>```

Body:
I was excited to use bash on windows but quickly ran into an issue. I am trying to install build-essential, but I get a dependency issue. Upon trying to resolve with sudo apt-get install -f, I run into another error that doesn't make much sense. I've tried update and upgrade, but that didn't work either. F

barzevp@UK-LT-8356:~$ sudo apt-get install build-essential
Reading package lists... Done
Building dependency tree
Reading state information... Done
build-essential is already the newest version.
You might want to run 'apt-get -f install' to correct these:
The following packages have unmet dependencies.
 libc6-dev : Depends: linux-libc-dev but it is not going to be installed
E: Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution).
barzevp@UK-LT-8356:~$ sudo apt-get -f install
Reading package lists... Done
Building dependency tree
Reading state information... Done
Correcting dependencies... Done
The following packages were automatically installed and are no longer required:
  libfreetype6 os-prober
Use 'apt-get autoremove' to remove them.
The following extra packages will be installed:
  linux-libc-dev
The following NEW packages will be installed
  linux-libc-dev
0 to upgrade, 1 to newly install, 0 to remove and 43 not to upgrade.
5 not fully installed or removed.
Need to get 0 B/767 kB of archives.
After this operation, 3,946 kB of additional disk space will be used.
Do you want to continue? [Y/n] y
(Reading database ... 28660 files and directories currently installed.)
Preparing to unpack .../linux-libc-dev_3.13.0-123.172_amd64.deb ...
Unpacking linux-libc-dev:amd64 (3.13.0-123.172) ...
dpkg: error processing archive /var/cache/apt/archives/linux-libc-dev_3.13.0-123.172_amd64.deb (--unpack):
 unable to install new version of /usr/include/linux/netfilter_ipv6/ip6t_hl.h': File exists
E: Sub-process /usr/bin/dpkg returned an error code (1)

Full log of what led to the error in Bash on Ubuntu on Windows terminal is here:
https://pastebin.com/dq2D2Gtz

Body:
I don't have a solution, but I see the root of the problem.  It seems to have to do with case sensitivity on the filesystem.  The package for linux-libc-dev puts two copies of a file in /usr/include/linux/netfilter_ipv6 with only a difference in case; ip6t_HL.h, and ip6t_hl.h.  After placing ip6t_HL.h, it attempts to rename ip6t_hl.h.dpkg-new to ip6t_hl.h.  The system call to rename the file fails, claiming that ip6t_hl.h already exists

On a "real" linux system, ip6t_HL.h and ip6t_hl.h would clearly be different files.  Under WSL they probably had some strange incompatibilities to work out between NTFS's default case insensitive FS and unix's default case sensitivity.

You can duplicate the problem by hand e.g., with

echo hi > foo.H
echo hi > foo.h-new
mv foo.h-new foo.h

mv: cannot move 'foo.h-new' to 'foo.h': File exists

strace output:

rename("/usr/include/linux/netfilter_ipv6/ip6t_HL.h.dpkg-new", "/usr/include/linux/netfilter_ipv6/ip6t_HL.h") = 0
open("/usr/include/linux/netfilter_ipv6/ip6t_hl.h.dpkg-new", O_WRONLY) = 10
fsync(10)                               = 0
close(10)                               = 0
rename("/usr/include/linux/netfilter_ipv6/ip6t_hl.h.dpkg-new", "/usr/include/linux/netfilter_ipv6/ip6t_hl.h") = -1 EEXIST (File exists)
write(2, "dpkg: error processing archive /"..., 199dpkg: error processing archive /var/cache/apt/archives/linux-libc-dev_4.4.0-98.121_amd64.deb (--install):
 unable to install new version of '/usr/include/linux/netfilter_ipv6/ip6t_hl.h': File exists
) = 199


问:
python3: does multiprocessing.Lock() also lock at the thread level?
I have recently switched from threading to multiprocessing in my python3 program. This seems to work fine, and the multiprocessing.Lock() call seems to indeed successfully work as it's supposed to within multiple threads of execution that I spawn from within my program.

However, my program itself is invoked from another, higher-order module which runs separate instances of my program via normal Python threads. I have no ability to rewrite the code of that module.

I previously was using threading.Lock() and threading.RLock() to manage shared code in this environment, and I'm wondering if multiprocessing.Lock() will do the same as threading.Lock() or threading.RLock() when it is invoked within separate threads of the same process.

Or will I have to implement some sort of hybrid locking mechanism to make sure my shared resources are all safe within my combinationmultiprocessing-and-threading environment?

If a hybrid is needed, would the following be sufficient? ...

```<code>with multiprocessing.Lock():
    with threading.Lock():  # threading.RLock() in some cases
        # code that I want to protect
</code>```

... or would I have to implement something more sophisticated, perhaps via a new locking context manager that I would have to write?

Thank you in advance.

答:
I finally found the answer to my question:
Safe to call multiprocessing from a thread in Python?

I now see that calling multiprocessing.Lock() from within a threaded environment will not work. I had previously posted some code here that created a hybrid multiprocessing/threading lock object, but I have now deleted that code, because it is incorrect.

Body:
I have recently switched from threading to multiprocessing in my python3 program. This seems to work fine, and the multiprocessing.Lock() call seems to indeed successfully work as it's supposed to within multiple threads of execution that I spawn from within my program.

However, my program itself is invoked from another, higher-order module which runs separate instances of my program via normal Python threads. I have no ability to rewrite the code of that module.

I previously was using threading.Lock() and threading.RLock() to manage shared code in this environment, and I'm wondering if multiprocessing.Lock() will do the same as threading.Lock() or threading.RLock() when it is invoked within separate threads of the same process.

Or will I have to implement some sort of hybrid locking mechanism to make sure my shared resources are all safe within my combinationmultiprocessing-and-threading environment?

If a hybrid is needed, would the following be sufficient? ...

with multiprocessing.Lock():
    with threading.Lock():  # threading.RLock() in some cases
        # code that I want to protect

... or would I have to implement something more sophisticated, perhaps via a new locking context manager that I would have to write?

Thank you in advance.


答:
So i didn't find the overly simple answer i was hoping for but i did find another way to accomplish my goal. If i set all columns that should have a decimal place to a decimal type I can then use the system tables and (Tsql?) to modify all columns of type decimal to equal itself/100.0. </p>

```<code>DECLARE @tableName varchar(10)
SET @tableName = 'test21'

DECLARE @sql VARCHAR(MAX)
SET @sql = ''

SELECT @sql = @sql + 'UPDATE ' + @tableName + ' SET ' + c.name + ' = ' + c.name + '/100.0 ;'
FROM sys.columns c
INNER JOIN sys.tables t ON c.object_id = t.object_id
INNER JOIN sys.types y ON c.system_type_id = y.system_type_id
WHERE t.name = @tableName AND y.name IN ('decimal')

exec(@sql)
</code>```

<p>I have to dynamically construct the command within SQL based on information within the system tables and then execute it. . </p>

Title: SQL Server Create table to autoconvert int -> decimal

Body:
I'm not sure if this is possible but here goes.

I have financial data stored in a csv format. The data unfortunately lacks any decimal points in the dollar fields. so $100.00 is stored as '00000010000'. Its also stored as a string. In my current setup I upload the csv file into a staging table with all columns set to varchar(x).

I know that if I try to insert this value into an integer column it will automatically convert it to 10000 of type integer, but that means I am missing my decimal place.

Is there anyway I can create a table such that inserting an integer stored as a string or integer automatically converts it to an decimal with 2 places behind the decimal????

EX: '000010000' -> 100.00

I know I can cast the column to a decimal and divide the existing value by 100.... but this table has 100+ columns with 60+ of them needing to be recast. This is also only table 1 of 6. I want to avoid creating commands to individually changing the relevant columns. Not all columns containing a number need the decimal treatment.

Body:
So i didn't find the overly simple answer i was hoping for but i did find another way to accomplish my goal. If i set all columns that should have a decimal place to a decimal type I can then use the system tables and (Tsql?) to modify all columns of type decimal to equal itself/100.0.

DECLARE @tableName varchar(10)
SET @tableName = 'test21'

DECLARE @sql VARCHAR(MAX)
SET @sql = ''

SELECT @sql = @sql + 'UPDATE ' + @tableName + ' SET ' + c.name + ' = ' + c.name + '/100.0 ;'
FROM sys.columns c
INNER JOIN sys.tables t ON c.object_id = t.object_id
INNER JOIN sys.types y ON c.system_type_id = y.system_type_id
WHERE t.name = @tableName AND y.name IN ('decimal')

exec(@sql)

I have to dynamically construct the command within SQL based on information within the system tables and then execute it. .


问:
validate a dropdownlist in asp.net mvc
```<code>//in controller
ViewBag.Categories = categoryRepository.GetAllCategories().ToList();

//in view
 @Html.DropDownList("Cat", new SelectList(ViewBag.Categories,"ID", "CategoryName"))
</code>```

How can I make it so that by default it says "-Select Category-"

And validate to check something is selected (client and on the model)

Thanks

答:
There is an overload with 3 arguments. Html.DropdownList(name, selectList, optionLabel)
Update: there was a typo in the below code snippet.

```<code>@Html.DropDownList("Cat", new SelectList(ViewBag.Categories,"ID", "CategoryName"), "-Select Category-")
</code>```

For the validator use

```<code>@Html.ValidationMessage("Cat")
</code>```

Title: validate a dropdownlist in asp.net mvc

Body:
//in controller
ViewBag.Categories = categoryRepository.GetAllCategories().ToList();

//in view
 @Html.DropDownList("Cat", new SelectList(ViewBag.Categories,"ID", "CategoryName"))

How can I make it so that by default it says "-Select Category-"

And validate to check something is selected (client and on the model)

Thanks

Body:
There is an overload with 3 arguments. Html.DropdownList(name, selectList, optionLabel)
Update: there was a typo in the below code snippet.

@Html.DropDownList("Cat", new SelectList(ViewBag.Categories,"ID", "CategoryName"), "-Select Category-")

For the validator use

@Html.ValidationMessage("Cat")


问:
Node.js serving over https
I'm testing Node.js application over https connection where I created certificates for localhost,

Certificate creation,

```<code>$ openssl genrsa -out localhost.key 2048
$ openssl req -new -x509 -key localhost.key -out localhost.cert -days 3650 -subj /CN=localhost
</code>```

Use this in server,

```<code>var options = {
  key: fs.readFileSync('./localhost.key'),
  cert: fs.readFileSync('./localhost.cert'),
};
var http2 = require('http2');
var app = express();
const server = http2.createSecureServer( options, app);
server.listen({ host: app_host, port: port});
</code>```

Start the node.js server as,

```<code>$ node server.js

Tested using simple curl command as,
$ curl -k https://localhost:9000/getcpuinfo
 {"hw": ...}
</code>```

"-k" option is to ignote certificate validation step.

But if I try to use pythons 'requests' module as shown below the request fails,
    $ python
    import requests

requests.get("https://localhost:9000/getcpuinfo")
            requests.exceptions.SSLError: ("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')],)",)

So I used 'verify' option to make the request, it still fails.

requests.get("https://localhost:9000/getcpuinfo", verify=False)
          requests.exceptions.SSLError: ("bad handshake: SysCallError(-1, 'Unexpected EOF')",)

What am I doing wrong? How do I workaround this issue using 'requests' module'? Shouldn't 'verify' prevent the check?

答: You cant generate https certificates over localhost.</p>

Title: Node.js serving over https

Body:
I'm testing Node.js application over https connection where I created certificates for localhost,

Certificate creation,

$ openssl genrsa -out localhost.key 2048
$ openssl req -new -x509 -key localhost.key -out localhost.cert -days 3650 -subj /CN=localhost

Use this in server,

var options = {
  key: fs.readFileSync('./localhost.key'),
  cert: fs.readFileSync('./localhost.cert'),
};
var http2 = require('http2');
var app = express();
const server = http2.createSecureServer( options, app);
server.listen({ host: app_host, port: port});

Start the node.js server as,

$ node server.js

Tested using simple curl command as,
$ curl -k https://localhost:9000/getcpuinfo
 {"hw": ...}

"-k" option is to ignote certificate validation step.

But if I try to use pythons 'requests' module as shown below the request fails,
    $ python
    import requests

requests.get("https://localhost:9000/getcpuinfo")
            requests.exceptions.SSLError: ("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')],)",)

So I used 'verify' option to make the request, it still fails.

requests.get("https://localhost:9000/getcpuinfo", verify=False)
          requests.exceptions.SSLError: ("bad handshake: SysCallError(-1, 'Unexpected EOF')",)

What am I doing wrong? How do I workaround this issue using 'requests' module'? Shouldn't 'verify' prevent the check?


问:
What does .trigger('custom') mean if there is no second parameter?
I am looking at a piece of jQuery code:

```<code>    $(document)
        .trigger('someText')
        .on('click keyup', someMethod);
</code>```

I am unclear as to what .trigger('someText') triggers?  What is someText referring to?  I can't seem to find it in the code base at all.

The documentation states that for `.trigger('custom') to be useful, you need a second parameter, but there is none.

答:
All of the posters are correct, that action triggers a custom event; see http://api.jquery.com/trigger/

An example:

```<code>var btn = $('#button');
var box = $('$box');

btn.on('click', function() {
    box.trigger('hideBox');
});

box.on('hideBox', function() {
    box.hide();
});
</code>```

Body:
I am looking at a piece of jQuery code:

    $(document)
        .trigger('someText')
        .on('click keyup', someMethod);

I am unclear as to what .trigger('someText') triggers?  What is someText referring to?  I can't seem to find it in the code base at all.

The documentation states that for `.trigger('custom') to be useful, you need a second parameter, but there is none.

Body:
All of the posters are correct, that action triggers a custom event; see http://api.jquery.com/trigger/

An example:

var btn = $('#button');
var box = $('$box');

btn.on('click', function() {
    box.trigger('hideBox');
});

box.on('hideBox', function() {
    box.hide();
});


问:
Python Reading a text file
I wrote an applescript to generate a text file of all unwatched movies in my itunes library.  Here is the code of that script:

```<code>tell application "iTunes"
    set watchedEpisodes to tracks of playlist "TV Shows" whose unplayed is false and played count > 0
    set unwatchedEpisodes to tracks of playlist "TV Shows" whose unplayed is true
    if (count unwatchedEpisodes) > 0 then
        set trackNames to {}
        repeat with anEpisode in unwatchedEpisodes
            set tmp to location of anEpisode as text
            set posixtmp to POSIX path of tmp
            set end of trackNames to (posixtmp as text)
        end repeat

        set {TID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, return}

        set unwatchedTVShows to trackNames as text
        do shell script "echo " & quoted form of unwatchedTVShows & " > /Volumes/Data/Media/Kodi/unwatchedTVShows.txt"
        #display dialog trackNames as text
        set AppleScript's text item delimiters to TID
    end if

    set watchedEpisodes to tracks of playlist "Movies" whose unplayed is false and played count > 0
    set unwatchedEpisodes to tracks of playlist "Movies" whose unplayed is true
    if (count unwatchedEpisodes) > 0 then
        set trackNames to {}
        repeat with anEpisode in unwatchedEpisodes
            set tmp to location of anEpisode as text
            set posixtmp to POSIX path of tmp
            set end of trackNames to (posixtmp as text)

        end repeat

        set {TID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, return}

        set unwatchedMovies to trackNames as text
        do shell script "echo " & quoted form of unwatchedMovies & " > /Volumes/Data/Media/Kodi/unwatchedMovies.txt"
        #display dialog trackNames as text
        set AppleScript's text item delimiters to TID
    end if
end tell
</code>```

Here is my output file:

```<code>/Volumes/Data/Media/Movies/Thanks For Sharing.m4v
/Volumes/Data/Media/Movies/Thats My Boy.m4v
/Volumes/Data/Media/Movies/Think Like a Man.m4v
/Volumes/Data/Media/Movies/Think Like a Man Too.m4v
/Volumes/Data/Media/Movies/This Means War.m4v
/Volumes/Data/Media/Movies/Top Five.m4v
/Volumes/Data/Media/Movies/Trail of Blood.m4v
</code>```

My problem is reading this file.  I need to open it, and put it in a string so that I can search it wholeistically (ie, if I search for "Think Like a Man" I don't want a false positive on "Think Like a Man Too".

Anyway, here is my current python code (or at least a snippet of that code):

```<code>KODIFOLDER="/Volumes/Data/Media/Kodi"
with open(KODIFOLDER + "/unwatchedMovies.txt", 'r') as umovies:
    for line in umovies:
        line = line.strip()
        print line
</code>```

Here is the output:

```<code>/Volumes/Data/Media/Movies/Trail of Blood.m4voo.m4v
</code>```

Clearly, it's opening and reading the file, but I'm not understanding why the snippet isn't providing a full "list" of what's in the text file.  Any thoughts as to what I'm doing wrong?

Here is the final answer.  Not sure exactly what's different than what I had before (mixing tabs and spaces maybe??).  Anyway, for future reference, this code:

```<code>with open(KODIFOLDER + "/unwatchedMovies.txt", 'r') as uwmovies:
    for line in uwmovies:
        line = line.replace("\n","")
        unwatchedmovies = line.split('\r')
        print unwatchedmovies
</code>```

Gave the output of this list:

```<code>['/Volumes/Data/Media/Movies/Table 19.m4v', '/Volumes/Data/Media/Movies/Term Life.m4v', '/Volumes/Data/Media/Movies/Thanks For Sharing.m4v', '/Volumes/Data/Media/Movies/Thats My Boy.m4v', '/Volumes/Data/Media/Movies/Think Like a Man.m4v', '/Volumes/Data/Media/Movies/Think Like a Man Too.m4v', '/Volumes/Data/Media/Movies/This Means War.m4v', '/Volumes/Data/Media/Movies/Top Five.m4v', '/Volumes/Data/Media/Movies/Trail of Blood.m4v']
</code>```

which was exactly what I needed.  I list with no "\r" or "\n"'s.  Thanks for the help!

答:
Try This ( Pythonic Way, UPDATED ) :

```<code>import sys

read_lines = [sys.stdout.write(line.rstrip('\n') + "\n") for line in open('1.txt')]
</code>```

Python 2x

```<code>from __future__ import print_function
read_lines = [print(line.rstrip('\n')) for line in open('1.txt')]
</code>```

Title: Python Reading a text file

Body:
I wrote an applescript to generate a text file of all unwatched movies in my itunes library.  Here is the code of that script:

tell application "iTunes"
    set watchedEpisodes to tracks of playlist "TV Shows" whose unplayed is false and played count > 0
    set unwatchedEpisodes to tracks of playlist "TV Shows" whose unplayed is true
    if (count unwatchedEpisodes) > 0 then
        set trackNames to {}
        repeat with anEpisode in unwatchedEpisodes
            set tmp to location of anEpisode as text
            set posixtmp to POSIX path of tmp
            set end of trackNames to (posixtmp as text)
        end repeat

        set {TID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, return}

        set unwatchedTVShows to trackNames as text
        do shell script "echo " & quoted form of unwatchedTVShows & " > /Volumes/Data/Media/Kodi/unwatchedTVShows.txt"
        #display dialog trackNames as text
        set AppleScript's text item delimiters to TID
    end if

    set watchedEpisodes to tracks of playlist "Movies" whose unplayed is false and played count > 0
    set unwatchedEpisodes to tracks of playlist "Movies" whose unplayed is true
    if (count unwatchedEpisodes) > 0 then
        set trackNames to {}
        repeat with anEpisode in unwatchedEpisodes
            set tmp to location of anEpisode as text
            set posixtmp to POSIX path of tmp
            set end of trackNames to (posixtmp as text)

        end repeat

        set {TID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, return}

        set unwatchedMovies to trackNames as text
        do shell script "echo " & quoted form of unwatchedMovies & " > /Volumes/Data/Media/Kodi/unwatchedMovies.txt"
        #display dialog trackNames as text
        set AppleScript's text item delimiters to TID
    end if
end tell

Here is my output file:

/Volumes/Data/Media/Movies/Thanks For Sharing.m4v
/Volumes/Data/Media/Movies/Thats My Boy.m4v
/Volumes/Data/Media/Movies/Think Like a Man.m4v
/Volumes/Data/Media/Movies/Think Like a Man Too.m4v
/Volumes/Data/Media/Movies/This Means War.m4v
/Volumes/Data/Media/Movies/Top Five.m4v
/Volumes/Data/Media/Movies/Trail of Blood.m4v

My problem is reading this file.  I need to open it, and put it in a string so that I can search it wholeistically (ie, if I search for "Think Like a Man" I don't want a false positive on "Think Like a Man Too".

Anyway, here is my current python code (or at least a snippet of that code):

KODIFOLDER="/Volumes/Data/Media/Kodi"
with open(KODIFOLDER + "/unwatchedMovies.txt", 'r') as umovies:
    for line in umovies:
        line = line.strip()
        print line

Here is the output:

/Volumes/Data/Media/Movies/Trail of Blood.m4voo.m4v

Clearly, it's opening and reading the file, but I'm not understanding why the snippet isn't providing a full "list" of what's in the text file.  Any thoughts as to what I'm doing wrong?

Here is the final answer.  Not sure exactly what's different than what I had before (mixing tabs and spaces maybe??).  Anyway, for future reference, this code:

with open(KODIFOLDER + "/unwatchedMovies.txt", 'r') as uwmovies:
    for line in uwmovies:
        line = line.replace("\n","")
        unwatchedmovies = line.split('\r')
        print unwatchedmovies

Gave the output of this list:

['/Volumes/Data/Media/Movies/Table 19.m4v', '/Volumes/Data/Media/Movies/Term Life.m4v', '/Volumes/Data/Media/Movies/Thanks For Sharing.m4v', '/Volumes/Data/Media/Movies/Thats My Boy.m4v', '/Volumes/Data/Media/Movies/Think Like a Man.m4v', '/Volumes/Data/Media/Movies/Think Like a Man Too.m4v', '/Volumes/Data/Media/Movies/This Means War.m4v', '/Volumes/Data/Media/Movies/Top Five.m4v', '/Volumes/Data/Media/Movies/Trail of Blood.m4v']

which was exactly what I needed.  I list with no "\r" or "\n"'s.  Thanks for the help!

Body:
Try This ( Pythonic Way, UPDATED ) :

import sys

read_lines = [sys.stdout.write(line.rstrip('\n') + "\n") for line in open('1.txt')]

Python 2x

from __future__ import print_function
read_lines = [print(line.rstrip('\n')) for line in open('1.txt')]