问:
How to get JIRA ticket status using jQuery
I tried

```<code>var ajaxUrl = 'https://mydomain.atlassian.net/rest/api/2/issue/TICKET-207?fields=status';
        jQuery.ajax({
            url:ajaxUrl,
            dataType: 'jsonp',
            type : "GET",
            success: function(data){
                alert('Sucess data: ' + data);
                var resultdata = JSON.stringify(data);
                console.log('resultdata22: ' + resultdata);
                alert('resultdata: ' + resultdata);

            },
            error: function(data){
                alert('alert error');
            }
       });
</code>```

but failed

Refused to execute script from 'https://domain.atlassian.net/rest/api/2/issue/TICKET-207?fields=status&callback=jQuery31104841491505141431_1496758817313&_=1496758817314' because its MIME type ('application/json') is not executable, and strict MIME type checking is enabled.

Kindly suggest some way.
Thanks in adavance

答:
It does not work because you are missing authentification to use the jira rest api properly. There are 3 methods you can use to authenticate yourself to jira before making any rest queries: basic, cookie-based and OAuth.

You can find all the crunchy details on how to implement authentication correctly for json in the jira api documentation located here https://developer.atlassian.com/jiradev/jira-apis/jira-rest-apis/jira-rest-api-tutorials/jira-rest-api-example-basic-authentication

On my side i use c# + json to perform my queries.
A basic authentication operation needs this header information for all my request to work properly.

```<code>string authToken = "username:password";

request.Headers[HttpRequestHeader.Authorization] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(authToken));
</code>```

in your case it would probably look a little bit like this to be test tested over https only ( security reasons)

here is a curl example

```<code>curl -D- -u yourusername:yourpassword -X GET -H "Content-Type: application/json" https://mydomain.atlassian.net/rest/api/2/issue/TICKET-207?fields=status
</code>```

here is your javascript with added header

```<code>var ajaxUrl = 'https://mydomain.atlassian.net/rest/api/2/issue/TICKET-207?fields=status';
        jQuery.ajax({
            url:ajaxUrl,
            dataType: 'jsonp',
            type : "GET",
            beforeSend: function (xhr){
               xhr.setRequestHeader ("Authorization", "Basic " + btoa(username + ":" + password));
            success: function(data){
                alert('Sucess data: ' + data);
                var resultdata = JSON.stringify(data);
                console.log('resultdata22: ' + resultdata);
                alert('resultdata: ' + resultdata);

            },
            error: function(data){
                alert('alert error');
            }
       });

},
</code>```

Body:
I tried

var ajaxUrl = 'https://mydomain.atlassian.net/rest/api/2/issue/TICKET-207?fields=status';
        jQuery.ajax({
            url:ajaxUrl,
            dataType: 'jsonp',
            type : "GET",
            success: function(data){
                alert('Sucess data: ' + data);
                var resultdata = JSON.stringify(data);
                console.log('resultdata22: ' + resultdata);
                alert('resultdata: ' + resultdata);

            },
            error: function(data){
                alert('alert error');
            }
       });

but failed

Refused to execute script from 'https://domain.atlassian.net/rest/api/2/issue/TICKET-207?fields=status&callback=jQuery31104841491505141431_1496758817313&_=1496758817314' because its MIME type ('application/json') is not executable, and strict MIME type checking is enabled.

Kindly suggest some way.
Thanks in adavance

Body:
It does not work because you are missing authentification to use the jira rest api properly. There are 3 methods you can use to authenticate yourself to jira before making any rest queries: basic, cookie-based and OAuth.

You can find all the crunchy details on how to implement authentication correctly for json in the jira api documentation located here https://developer.atlassian.com/jiradev/jira-apis/jira-rest-apis/jira-rest-api-tutorials/jira-rest-api-example-basic-authentication

On my side i use c# + json to perform my queries.
A basic authentication operation needs this header information for all my request to work properly.

string authToken = "username:password";

request.Headers[HttpRequestHeader.Authorization] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(authToken));

in your case it would probably look a little bit like this to be test tested over https only ( security reasons)

here is a curl example

curl -D- -u yourusername:yourpassword -X GET -H "Content-Type: application/json" https://mydomain.atlassian.net/rest/api/2/issue/TICKET-207?fields=status

here is your javascript with added header

var ajaxUrl = 'https://mydomain.atlassian.net/rest/api/2/issue/TICKET-207?fields=status';
        jQuery.ajax({
            url:ajaxUrl,
            dataType: 'jsonp',
            type : "GET",
            beforeSend: function (xhr){
               xhr.setRequestHeader ("Authorization", "Basic " + btoa(username + ":" + password));
            success: function(data){
                alert('Sucess data: ' + data);
                var resultdata = JSON.stringify(data);
                console.log('resultdata22: ' + resultdata);
                alert('resultdata: ' + resultdata);

            },
            error: function(data){
                alert('alert error');
            }
       });

},


来源: stackexchange

问:
Force orientation on view controller
in my app i have a navigation controller that shows a view controller forced to portrait orientation. On tap on a button on screen a push is performed and a view controller is shown, and it doesn't have restrictions about orientation, it support all orientations. The problem is that when i tap on back button and i am in landscape, the first view controller is shown in landscape, and not in portrait has expected.
I've implemented all method for orientation, such as supportedInterfaceOrientation for each view controller, but i don't found a way to force the first view controller to portrait.</p>

答:
I was able to force orientation for a particular view by calling the following in the viewWillAppear event:

```<code>// LOCK SCREEN ORIENTATION TO LANDSCAPE
AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
[appDelegate setLockLandscape:YES];

// CHECK CURRNET ORIENTATION
if([[UIDevice currentDevice] orientation] != UIInterfaceOrientationLandscapeRight){

    // TRANSITION ORIENTATION TO LANDSCAPE
    NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeRight];
    [[UIDevice currentDevice] setValue:value forKey:@"orientation"];

}else{

    // SET ORIENTATION TO PORTRAIT
    NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
    [[UIDevice currentDevice] setValue:value forKey:@"orientation"];

    // TRANSITION ORIENTATION TO LANDSCAPE
    value = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeRight];
    [[UIDevice currentDevice] setValue:value forKey:@"orientation"];

}
</code>```

Transition The View

This will animate the view to a particular orientation, however the orientation will not be locked necessarily:

```<code>// TRANSITION ORIENTATION TO LANDSCAPE
NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeRight];
[[UIDevice currentDevice] setValue:value forKey:@"orientation"];
</code>```

Lock The Orientation

This will lock the view:

```<code>AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
[appDelegate setLockLandscape:YES];
</code>```

I was able to call [appDelegate setLockLandscape:YES]; from the property lockLandscape I created in my appDelegates as well as the following function:

@property (assign, nonatomic) BOOL lockLandscape;

```<code>//////////////////////////////////////////
// DELAGATE FUNCTION - LOCK ORIENTATION
-(UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window{

   // CHECK LOCK LANDSCAPE
   if (self.lockLandscape){

       // LOCK LANDSCAPE
       return UIInterfaceOrientationMaskLandscape;

   }else{

       // LOCK PORTRAIT
       return UIInterfaceOrientationMaskPortrait;

   }

} // END - FUNCTION DELAGATE
</code>```

The other code was to fix a bug that occurred when transition from another type of landscape than what I was forcing.

ContentLicense: CC BY-SA 3.0

Title: Force orientation on view controller

Body:
I was able to force orientation for a particular view by calling the following in the viewWillAppear event:

// LOCK SCREEN ORIENTATION TO LANDSCAPE
AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
[appDelegate setLockLandscape:YES];

// CHECK CURRNET ORIENTATION
if([[UIDevice currentDevice] orientation] != UIInterfaceOrientationLandscapeRight){

    // TRANSITION ORIENTATION TO LANDSCAPE
    NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeRight];
    [[UIDevice currentDevice] setValue:value forKey:@"orientation"];

}else{

    // SET ORIENTATION TO PORTRAIT
    NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
    [[UIDevice currentDevice] setValue:value forKey:@"orientation"];

    // TRANSITION ORIENTATION TO LANDSCAPE
    value = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeRight];
    [[UIDevice currentDevice] setValue:value forKey:@"orientation"];

}

Transition The View

This will animate the view to a particular orientation, however the orientation will not be locked necessarily:

// TRANSITION ORIENTATION TO LANDSCAPE
NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeRight];
[[UIDevice currentDevice] setValue:value forKey:@"orientation"];

Lock The Orientation

This will lock the view:

AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
[appDelegate setLockLandscape:YES];

I was able to call [appDelegate setLockLandscape:YES]; from the property lockLandscape I created in my appDelegates as well as the following function:

@property (assign, nonatomic) BOOL lockLandscape;

//////////////////////////////////////////
// DELAGATE FUNCTION - LOCK ORIENTATION
-(UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window{

   // CHECK LOCK LANDSCAPE
   if (self.lockLandscape){

       // LOCK LANDSCAPE
       return UIInterfaceOrientationMaskLandscape;

   }else{

       // LOCK PORTRAIT
       return UIInterfaceOrientationMaskPortrait;

   }

} // END - FUNCTION DELAGATE

The other code was to fix a bug that occurred when transition from another type of landscape than what I was forcing.


问:
How to remove draggability from an element with Ext JS?
I have a div that I want to make draggable or not, depending on the state of some other stuff on my page.  I seem to be able to easily make it draggable, but I can't seem to figure out how to best remove the draggability from the div.

I am making it draggable with:

```<code>var dd = Ext.create('Ext.dd.DDProxy', mydiv, 'myDDGroup', { isTarget: false });
</code>```

And I've tried to then remove the draggability by removing the only group it's a member of

```<code>dd.removeFromGroup('myDDGroup');
</code>```

and just destroying the dd object with

```<code>delete dd;
</code>```

Neither of these seem to actually keep me from starting a drag on the element. I suspect I should be able to use the b4Drag override in some way to simply cancel a drag of my div before it even begins, rather than toggling the draggable state of the div at all, but I can't seem to find docs on how I might cancel the drag during the b4Drag call.

So, how can I make a div undraggable after I have already made it draggable?

答:
When looking at something specific that needs to be dragged, you might consider that allowing dragging is something users expect, for general ease of use you might try the ondragstart="return, this could be appended to your images, or links like so:

link.

Body:
I have a div that I want to make draggable or not, depending on the state of some other stuff on my page.  I seem to be able to easily make it draggable, but I can't seem to figure out how to best remove the draggability from the div.

I am making it draggable with:

var dd = Ext.create('Ext.dd.DDProxy', mydiv, 'myDDGroup', { isTarget: false });

And I've tried to then remove the draggability by removing the only group it's a member of

dd.removeFromGroup('myDDGroup');

and just destroying the dd object with

delete dd;

Neither of these seem to actually keep me from starting a drag on the element. I suspect I should be able to use the b4Drag override in some way to simply cancel a drag of my div before it even begins, rather than toggling the draggable state of the div at all, but I can't seem to find docs on how I might cancel the drag during the b4Drag call.

So, how can I make a div undraggable after I have already made it draggable?

Body:
When looking at something specific that needs to be dragged, you might consider that allowing dragging is something users expect, for general ease of use you might try the ondragstart="return, this could be appended to your images, or links like so:

<a ondragstart="return false" href="#link">link</a>.


问:
Java on Debian: Probable fatal error: No fonts found
I want to run Tomcat on Debian 5 Minimal. So I don't need a gui for my OS, it's just a pure Tomcat-Server.

Which packages do I need for my JVM to use Fonts in my applications? Im drawing texts in Graphics2D and am creating PDF-Files in my Java-Project.

答:
Graphics2D and anything in the java.awt.* or java.swing.* packages require a GUI to do its drawing.

This is a problem on most headless servers.  You have two options, and try them in this order:

Use the system property "java.awt.headless" and set that to "true"
java -Djava.awt.headless=true or System.setProperty("java.awt.headless", "true");

Install the XWindows Virtual Frame Buffer (xvfb) on your server.  This keeps the server headless, but provides the XWindows primitives needed to draw on a virtual screen.  It is far from optimized (no graphics acceleration), but it will allow your system to work again.

The java.awt.headless option was introduced with Java 1.4.  See: http://java.sun.com/developer/technicalArticles/J2SE/Desktop/headless/

In the event that does not work, install the XVFB package and configure it to create a virtual frame buffer large enough to do your drawing.

ContentLicense: CC BY-SA 2.5


问:
Curl POST command to pass json data to spring-boot app not working
Have looked at other related posts but nothing seemed to work.

Basically I'm trying to figure out how to pass data to my restful spring-boot app.

Here is the curl command I'm using:

```<code>$ curl -iX POST -H 'Content-Type: application/json' -d @args.json http://localhost:8080/myapp/dummyApi
</code>```

With args.json contains:

file: args.json:

```<code>{
  "arg1": "hello",
  "arg2": 10,
  "arg3": {
    "a": "1",
    "b": "2"
  }
}
</code>```

The api is defined in MyController.java as such:

file: MyController.java

```<code>@RestController
@RequestMapping("/myapp")
public class MyController {

//...

static class DummyRet {
    private String foo;
    public DummyRet(String f) {
        foo = f;
    }
    public String getFoo() {
        return foo;
    }
    public void setFoo(String foo) {
        this.foo = foo;
    }
}

@RequestMapping(value="/dummyApi", method=RequestMethod.POST)
public DummyRet dummyApi(@RequestParam(value = "arg1", required = false, defaultValue = "") String arg1,
                               @RequestParam(value = "arg2", required = false, defaultValue = "") Long arg2,
                               @RequestParam(value = "arg3", required = false) Map<String, String> arg3) {
    LOGGER.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
    LOGGER.info("Arguments received:");
    LOGGER.info("arg1: " + arg1);
    LOGGER.info("arg2: " + arg2);
    LOGGER.info("arg3: " + arg3);
    LOGGER.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
    return new DummyRet("foo");
}

//...
}
</code>```

The return of the curl command is 200 success (since non of the arguments is required) but the values of args are not reaching over to dummyApi method

```<code>$ curl -iX POST -H 'Content-Type: application/json' -d @args.json http://localhost:8080/myapp/dummyApi
HTTP/1.1 200
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Sun, 04 Jun 2017 15:37:42 GMT

{"foo":"foo"}
</code>```

The server console looks like this:

```<code>2017-06-04 18:17:56.818 DEBUG 32258 --- [nio-8080-exec-7] o.s.web.servlet.DispatcherServlet        : DispatcherServlet with name 'dispatcherServlet' processing POST request for [/myapp/dummyApi]
2017-06-04 18:17:56.818 DEBUG 32258 --- [nio-8080-exec-7] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /myapp/dummyApi
2017-06-04 18:17:56.818 DEBUG 32258 --- [nio-8080-exec-7] s.w.s.m.m.a.RequestMappingHandlerMapping : Returning handler method [public com.xx.controllers.MyController$DummyRet com.xx.controllers.MyController.dummyApi(java.lang.String,java.lang.Long,java.util.Map<java.lang.String, java.lang.String>)]
2017-06-04 18:17:56.819  INFO 32258 --- [nio-8080-exec-7] c.p.controllers.MyController       : >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
2017-06-04 18:17:56.819  INFO 32258 --- [nio-8080-exec-7] c.p.controllers.MyController       : Arguments received:
2017-06-04 18:17:56.819  INFO 32258 --- [nio-8080-exec-7] c.p.controllers.MyController       : arg1:
2017-06-04 18:17:56.819  INFO 32258 --- [nio-8080-exec-7] c.p.controllers.MyController       : arg2: null
2017-06-04 18:17:56.819  INFO 32258 --- [nio-8080-exec-7] c.p.controllers.MyController       : arg3: null
2017-06-04 18:17:56.819  INFO 32258 --- [nio-8080-exec-7] c.p.controllers.MyController       : >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
2017-06-04 18:17:56.819 DEBUG 32258 --- [nio-8080-exec-7] m.m.a.RequestResponseBodyMethodProcessor : Written [com.xx.controllers.MyController$DummyRet@c35d46f] as "application/json" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@301ec38b]
2017-06-04 18:17:56.819 DEBUG 32258 --- [nio-8080-exec-7] o.s.web.servlet.DispatcherServlet        : Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
2017-06-04 18:17:56.819 DEBUG 32258 --- [nio-8080-exec-7] o.s.web.servlet.DispatcherServlet        : Successfully completed request
</code>```

I hope I haven't left out any of the important details, but please let me know if anything is missing.

答:
This worked:

I had two issues in my spring-boot java method,

I'm specifying @RrequestParam for the arguments, where I should be using @RequestBody instead

I have multiple of such method params where in POST it should be a single (see footnote) @RequestBody

But since I need to pass multiple arguments over to the method the solution was to wrap these arguments in a backing object, as such:

```<code>public static class Args {
    // members
    private String arg1;
    private Long arg2;
    private Map<String, String> arg3;
    // accessors
    public String getArg1() {return arg1;}
    public void setArg1(String arg1) {this.arg1 = arg1;}
    public Long getArg2() {return arg2;}
    public void setArg2(Long arg2) {this.arg2 = arg2;}
    public Map<String, String> getArg3() {return arg3;}
    public void setArg3(Map<String, String> arg3) {this.arg3 = arg3;}
}
</code>```

The receiver method would then be:

```<code>@RequestMapping(value="/dummyApi", method=RequestMethod.POST)
public DummyRet dummyApi(@RequestBody Args args) {
  LOGGER.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
  LOGGER.info("Arguments received:");
  LOGGER.info("arg1: " + args.getArg1().toString());
  LOGGER.info("arg2: " + args.getArg2().toString());
  LOGGER.info("arg3: " + args.getArg3().toString());
  LOGGER.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
  return new DummyRet("foo");
}
</code>```

Footnote: In fact it is possible to pass multiple params through custom implementation as described in this SO response. Haven't tried it

Body:
Have looked at other related posts but nothing seemed to work.

Basically I'm trying to figure out how to pass data to my restful spring-boot app.

Here is the curl command I'm using:

$ curl -iX POST -H 'Content-Type: application/json' -d @args.json http://localhost:8080/myapp/dummyApi

With args.json contains:

file: args.json:

{
  "arg1": "hello",
  "arg2": 10,
  "arg3": {
    "a": "1",
    "b": "2"
  }
}

The api is defined in MyController.java as such:

file: MyController.java

@RestController
@RequestMapping("/myapp")
public class MyController {

//...

static class DummyRet {
    private String foo;
    public DummyRet(String f) {
        foo = f;
    }
    public String getFoo() {
        return foo;
    }
    public void setFoo(String foo) {
        this.foo = foo;
    }
}

@RequestMapping(value="/dummyApi", method=RequestMethod.POST)
public DummyRet dummyApi(@RequestParam(value = "arg1", required = false, defaultValue = "") String arg1,
                               @RequestParam(value = "arg2", required = false, defaultValue = "") Long arg2,
                               @RequestParam(value = "arg3", required = false) Map<String, String> arg3) {
    LOGGER.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
    LOGGER.info("Arguments received:");
    LOGGER.info("arg1: " + arg1);
    LOGGER.info("arg2: " + arg2);
    LOGGER.info("arg3: " + arg3);
    LOGGER.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
    return new DummyRet("foo");
}

//...
}

The return of the curl command is 200 success (since non of the arguments is required) but the values of args are not reaching over to dummyApi method

$ curl -iX POST -H 'Content-Type: application/json' -d @args.json http://localhost:8080/myapp/dummyApi
HTTP/1.1 200
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Sun, 04 Jun 2017 15:37:42 GMT

{"foo":"foo"}

The server console looks like this:

2017-06-04 18:17:56.818 DEBUG 32258 --- [nio-8080-exec-7] o.s.web.servlet.DispatcherServlet        : DispatcherServlet with name 'dispatcherServlet' processing POST request for [/myapp/dummyApi]
2017-06-04 18:17:56.818 DEBUG 32258 --- [nio-8080-exec-7] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /myapp/dummyApi
2017-06-04 18:17:56.818 DEBUG 32258 --- [nio-8080-exec-7] s.w.s.m.m.a.RequestMappingHandlerMapping : Returning handler method [public com.xx.controllers.MyController$DummyRet com.xx.controllers.MyController.dummyApi(java.lang.String,java.lang.Long,java.util.Map<java.lang.String, java.lang.String>)]
2017-06-04 18:17:56.819  INFO 32258 --- [nio-8080-exec-7] c.p.controllers.MyController       : >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
2017-06-04 18:17:56.819  INFO 32258 --- [nio-8080-exec-7] c.p.controllers.MyController       : Arguments received:
2017-06-04 18:17:56.819  INFO 32258 --- [nio-8080-exec-7] c.p.controllers.MyController       : arg1:
2017-06-04 18:17:56.819  INFO 32258 --- [nio-8080-exec-7] c.p.controllers.MyController       : arg2: null
2017-06-04 18:17:56.819  INFO 32258 --- [nio-8080-exec-7] c.p.controllers.MyController       : arg3: null
2017-06-04 18:17:56.819  INFO 32258 --- [nio-8080-exec-7] c.p.controllers.MyController       : >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
2017-06-04 18:17:56.819 DEBUG 32258 --- [nio-8080-exec-7] m.m.a.RequestResponseBodyMethodProcessor : Written [com.xx.controllers.MyController$DummyRet@c35d46f] as "application/json" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@301ec38b]
2017-06-04 18:17:56.819 DEBUG 32258 --- [nio-8080-exec-7] o.s.web.servlet.DispatcherServlet        : Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
2017-06-04 18:17:56.819 DEBUG 32258 --- [nio-8080-exec-7] o.s.web.servlet.DispatcherServlet        : Successfully completed request

I hope I haven't left out any of the important details, but please let me know if anything is missing.

Body:
This worked:

I had two issues in my spring-boot java method,

I'm specifying @RrequestParam for the arguments, where I should be using @RequestBody instead

I have multiple of such method params where in POST it should be a single (see footnote) @RequestBody

But since I need to pass multiple arguments over to the method the solution was to wrap these arguments in a backing object, as such:

public static class Args {
    // members
    private String arg1;
    private Long arg2;
    private Map<String, String> arg3;
    // accessors
    public String getArg1() {return arg1;}
    public void setArg1(String arg1) {this.arg1 = arg1;}
    public Long getArg2() {return arg2;}
    public void setArg2(Long arg2) {this.arg2 = arg2;}
    public Map<String, String> getArg3() {return arg3;}
    public void setArg3(Map<String, String> arg3) {this.arg3 = arg3;}
}

The receiver method would then be:

@RequestMapping(value="/dummyApi", method=RequestMethod.POST)
public DummyRet dummyApi(@RequestBody Args args) {
  LOGGER.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
  LOGGER.info("Arguments received:");
  LOGGER.info("arg1: " + args.getArg1().toString());
  LOGGER.info("arg2: " + args.getArg2().toString());
  LOGGER.info("arg3: " + args.getArg3().toString());
  LOGGER.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
  return new DummyRet("foo");
}

Footnote: In fact it is possible to pass multiple params through custom implementation as described in this SO response. Haven't tried it


问:
Is there a way to mock an $? return using Pester?
I'm writing tests for a PowerShell application, using Pester.

I have been able to create mocks for most functions, but I haven't been able to mock a function returning the $? variable. I'm currently using it to evaluate the returns from AWS CLI commands.

This is, for example, to mock a failing AWS CLI command return.

Any thoughts?

答:
You should be able to do:</p>

```<code>Mock AWC-CLI { $ = $true } -Verifiable
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You should be able to do:

Mock AWC-CLI { $ = $true } -Verifiable


问:
Executing R file from bash script
I need to run the same R script over and over with different parameters for each run. I've written the R portion and it works. I'm trying to integrate this process with some other Java tools I've written that will need to use on the files changed by the R script. I'm therefore trying to run my R file from Java. I've tried to run it using the command line prompt: RScript TestR.R (this command works in terminal), but that didn't work. I am therefore in the process of trying to run my R script from a bash file. I am using the same command as above and my bash file can execute other commands but for some reason nothing happens when I try to run the R file. The java command I'm using is

```<code>Process proc = Runtime.getRuntime().exec("absolute-path/testbash.sh");
</code>```

I'm not sure what format of output to look for. Currently, this runs without any runtime errors.

UPDATE: when I checked the ErrorStream, it said "Rscript: command not found"

UPDATE: I figured it out by using "/usr/local/bin/RScript" as the command

答:
You can do it the following way:</p>

```<code>new ProcessBuilder("<absolute-path-to-script>/testbash.sh").start();
</code>```

Title: Executing R file from bash script

Body:
I need to run the same R script over and over with different parameters for each run. I've written the R portion and it works. I'm trying to integrate this process with some other Java tools I've written that will need to use on the files changed by the R script. I'm therefore trying to run my R file from Java. I've tried to run it using the command line prompt: RScript TestR.R (this command works in terminal), but that didn't work. I am therefore in the process of trying to run my R script from a bash file. I am using the same command as above and my bash file can execute other commands but for some reason nothing happens when I try to run the R file. The java command I'm using is

Process proc = Runtime.getRuntime().exec("absolute-path/testbash.sh");

I'm not sure what format of output to look for. Currently, this runs without any runtime errors.

UPDATE: when I checked the ErrorStream, it said "Rscript: command not found"

UPDATE: I figured it out by using "/usr/local/bin/RScript" as the command

Body:
You can do it the following way:

new ProcessBuilder("<absolute-path-to-script>/testbash.sh").start();


问:
Change the textview's text using button click in Android
I want to change the text on a textView on button click. There can be multiple buttons in activity. The main purpose is to change the name of fruit on button click either any one button is clicked.
For example: Button 1 is clicked change the name, Button 2 is clicked next name, Button 3 is clicked next name and so on. I am trying as given below but the names are not changing.

Main Activity

```<code>import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private TextView sentence_etx;
    private Button btn_1,btn_2;
    private String[] names = { "Apple","Mango","Cherry","Banana","Extra"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sentence_etx = (TextView) findViewById(R.id.etx_sentence);
        btn_1 = (Button) findViewById(R.id.btn_1);
        btn_2 = (Button) findViewById(R.id.btn_2);

        for (int i=0;i<=names.length;i++) {
            work(i);
        }
    }

    private void work(final int i) {
            btn_1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    sentence_etx.setText(names[i]);
                }
            });

            btn_2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    sentence_etx.setText(names[i]);
                }
            });
    }
}
</code>```

XML

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.awais.test2.MainActivity">

    <LinearLayout
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:orientation="vertical">

        <TextView
            android:layout_marginTop="50dp"
            android:layout_marginRight="30dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/etx_sentence"
            android:text="Names......" />

        <LinearLayout
            android:gravity="center"
            android:layout_marginTop="100dp"
            android:layout_height="wrap_content"
            android:layout_width="match_parent">

        <Button
            android:layout_height="50dp"
            android:layout_width="50dp"
            android:id="@+id/btn_1"
            android:text="1"/>

        <Button
            android:layout_height="50dp"
            android:layout_width="50dp"
            android:id="@+id/btn_2"
            android:text="2"/>

        <Button
            android:layout_height="50dp"
            android:layout_width="50dp"
            android:id="@+id/btn_3"
            android:text="3"/>

        </LinearLayout>

    </LinearLayout>

</RelativeLayout>
</code>```

答:
You're reseting the OnClickListener of your buttons every time you call work. If you want them to show different names, you can't assign them the same OnClickListener (which is that you do right now).

What you could do is change the signature of work to receive the Button as a parameter and set the listener on that button. Then, in the onCreate method, you decide which name goes with which button

Body:
I want to change the text on a textView on button click. There can be multiple buttons in activity. The main purpose is to change the name of fruit on button click either any one button is clicked.
For example: Button 1 is clicked change the name, Button 2 is clicked next name, Button 3 is clicked next name and so on. I am trying as given below but the names are not changing.

Main Activity

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private TextView sentence_etx;
    private Button btn_1,btn_2;
    private String[] names = { "Apple","Mango","Cherry","Banana","Extra"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sentence_etx = (TextView) findViewById(R.id.etx_sentence);
        btn_1 = (Button) findViewById(R.id.btn_1);
        btn_2 = (Button) findViewById(R.id.btn_2);

        for (int i=0;i<=names.length;i++) {
            work(i);
        }
    }

    private void work(final int i) {
            btn_1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    sentence_etx.setText(names[i]);
                }
            });

            btn_2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    sentence_etx.setText(names[i]);
                }
            });
    }
}

XML

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.awais.test2.MainActivity">

    <LinearLayout
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:orientation="vertical">

        <TextView
            android:layout_marginTop="50dp"
            android:layout_marginRight="30dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/etx_sentence"
            android:text="Names......" />

        <LinearLayout
            android:gravity="center"
            android:layout_marginTop="100dp"
            android:layout_height="wrap_content"
            android:layout_width="match_parent">

        <Button
            android:layout_height="50dp"
            android:layout_width="50dp"
            android:id="@+id/btn_1"
            android:text="1"/>

        <Button
            android:layout_height="50dp"
            android:layout_width="50dp"
            android:id="@+id/btn_2"
            android:text="2"/>

        <Button
            android:layout_height="50dp"
            android:layout_width="50dp"
            android:id="@+id/btn_3"
            android:text="3"/>

        </LinearLayout>

    </LinearLayout>

</RelativeLayout>


问:
change print text when tap in GMSPoligon. Swift
I have some GMSPoligon:

```<code>    let españa = GMSMutablePath()
    españa.add(CLLocationCoordinate2D(latitude: 42.11, longitude: -9.37))
    españa.add(CLLocationCoordinate2D(latitude: 43.94, longitude: -9.55))
    españa.add(CLLocationCoordinate2D(latitude: 43.60, longitude: -1.89))
    españa.add(CLLocationCoordinate2D(latitude: 42.02, longitude: 3.72))
    españa.add(CLLocationCoordinate2D(latitude: 36.16, longitude: -2.65))
    españa.add(CLLocationCoordinate2D(latitude: 37.10, longitude: -7.28))
    españa.add(CLLocationCoordinate2D(latitude: 42.08, longitude: -6.61))

    let polygonEspaña = GMSPolygon(path: españa)
    polygonEspaña.fillColor = UIColor(red : CGFloat(fillColorRed), green: CGFloat(fillColorGreen), blue: CGFloat(fillColorBlue), alpha: CGFloat(fillColorAlpha));
    polygonEspaña.strokeColor = strokeColor
    polygonEspaña.strokeWidth = strokeWidth
    polygonEspaña.map = mapView
    polygonEspaña.isTappable = true
</code>```

I implemented some delegates:

import UIKit
import GoogleMaps

class MapViewController: UIViewController, GMSMapViewDelegate, CLLocationManagerDelegate {

and some functions

// ###### Click Country

```<code>func mapView(_ mapView: GMSMapView, didTap overlay: GMSOverlay) {
    print("User Tapped Layer: \(overlay)")
</code>```

// FUNCTION THAT IS NOT WORKING:    print("has clicado en : (GMSPoligon)")

```<code>}

// #### Find location in console.

func mapView(_ mapView: GMSMapView, didTapAt coordinate: CLLocationCoordinate2D) {
    print("You tapped at \(coordinate.latitude), \(coordinate.longitude)")
}
</code>```

GMSPolygon works and they are visible on the map, but when i click them. i recieve this text on my console:

LOCATION TAP : You tapped at 52.8075964305343, 16.8773408979177
GMSPoigonTap: User Tapped Layer:  (null) size 7 color UIExtendedSRGBColorSpace 0.25 0 0 0.05

I want to change this text and recive, the county. if i tap in spain: YOU CLICKED ON SPAIN. if i click on Germany : YOU CLICKED ON GERMANY.

How can i do that?

Thanks at all buddies.

答:
Finally i added this property to my GMSPolygon

```<code>        polygonEspaña.title = "España"
</code>```

And this function.

```<code>  func mapView(_ mapView: GMSMapView, didTap overlay: GMSOverlay) {

    print("\(overlay.title)"

Now i receive in my console : Optional("España"
</code>```

Body:
I have some GMSPoligon:

    let españa = GMSMutablePath()
    españa.add(CLLocationCoordinate2D(latitude: 42.11, longitude: -9.37))
    españa.add(CLLocationCoordinate2D(latitude: 43.94, longitude: -9.55))
    españa.add(CLLocationCoordinate2D(latitude: 43.60, longitude: -1.89))
    españa.add(CLLocationCoordinate2D(latitude: 42.02, longitude: 3.72))
    españa.add(CLLocationCoordinate2D(latitude: 36.16, longitude: -2.65))
    españa.add(CLLocationCoordinate2D(latitude: 37.10, longitude: -7.28))
    españa.add(CLLocationCoordinate2D(latitude: 42.08, longitude: -6.61))

    let polygonEspaña = GMSPolygon(path: españa)
    polygonEspaña.fillColor = UIColor(red : CGFloat(fillColorRed), green: CGFloat(fillColorGreen), blue: CGFloat(fillColorBlue), alpha: CGFloat(fillColorAlpha));
    polygonEspaña.strokeColor = strokeColor
    polygonEspaña.strokeWidth = strokeWidth
    polygonEspaña.map = mapView
    polygonEspaña.isTappable = true

I implemented some delegates:

import UIKit
import GoogleMaps

class MapViewController: UIViewController, GMSMapViewDelegate, CLLocationManagerDelegate {

and some functions

// ###### Click Country

func mapView(_ mapView: GMSMapView, didTap overlay: GMSOverlay) {
    print("User Tapped Layer: \(overlay)")

// FUNCTION THAT IS NOT WORKING:    print("has clicado en : (GMSPoligon)")

}

// #### Find location in console.

func mapView(_ mapView: GMSMapView, didTapAt coordinate: CLLocationCoordinate2D) {
    print("You tapped at \(coordinate.latitude), \(coordinate.longitude)")
}

GMSPolygon works and they are visible on the map, but when i click them. i recieve this text on my console:

LOCATION TAP : You tapped at 52.8075964305343, 16.8773408979177
GMSPoigonTap: User Tapped Layer:  (null) size 7 color UIExtendedSRGBColorSpace 0.25 0 0 0.05

I want to change this text and recive, the county. if i tap in spain: YOU CLICKED ON SPAIN. if i click on Germany : YOU CLICKED ON GERMANY.

How can i do that?

Thanks at all buddies.

Body:
Finally i added this property to my GMSPolygon

        polygonEspaña.title = "España"

And this function.

  func mapView(_ mapView: GMSMapView, didTap overlay: GMSOverlay) {

    print("\(overlay.title)"

Now i receive in my console : Optional("España"


问:
PHP: Get current locale using timezone
I am using timezone to get exact time of a user according to his timezone. I have a drop down list to select timezone for users and showing their current time as they selected their timezone. The code i am using is:

```<code>$timezone = 'America/New_York';
date_default_timezone_set($timezone);
echo date('H:i:s A');
</code>```

It is working fine. I want to get locale of that user using timezone in the same way I am getting current time for that timezone.

How can I achieve the current locale using timezone? Does PHP have any kind of solution to get current locale using timezone?

答:
Locale and time zone are orthogonal.  You cannot determine one from the other.

America/New_York means that the user's local time is aligned to New York City, which happens to be called "Eastern Time" in the United States, which is 5 hours behind UTC during standard time and 4 hours behind UTC when daylight saving time is in effect.

en-US (or en_US) means that the user speaks English, with cultural dialects (word choice, numbers, dates, etc.) of the United States.  For example, en-US uses MM/DD/YYYY date format, and en-GB uses DD/MM/YYYY date format, but we both call our first month "January", while es-MX calls their first month "enero".

I could very well be an English speaking American visiting Japan, thus my time zone would be Asia/Tokyo even though my local would still be en-US.

Aside: A hyphen (-) is the correct character to split language and country codes in a locale identifier.  Though some implementations have substituted an underscore (_), this is not correct by the IETF language tag specification.

Title: PHP: Get current locale using timezone

Body:
I am using timezone to get exact time of a user according to his timezone. I have a drop down list to select timezone for users and showing their current time as they selected their timezone. The code i am using is:

$timezone = 'America/New_York';
date_default_timezone_set($timezone);
echo date('H:i:s A');

It is working fine. I want to get locale of that user using timezone in the same way I am getting current time for that timezone.

How can I achieve the current locale using timezone? Does PHP have any kind of solution to get current locale using timezone?


问:
Error uploading analysis to SonarQube
I have a Sonarcloud account and I'm trying to analyze a Visual Studio solution using SonarQube.Scanner.MSBuild.exe.  I've created a token and am passing that on as the sonar.login property in the SonarQube.Analysis.xml file.
I'm using https://sonarcloud.io as sonar.host.url, but I've also tried https://sonarqube.com.

Here is the relevant snippet of the configuration:

```<code><Property Name="sonar.host.url">https://sonarcloud.io</Property>
<Property Name="sonar.login">***my*token****</Property>
<Property Name="sonar.password"></Property>
<Property Name="sonar.organization">MyOrganization</Property>
</code>```

The analysis seems to run fine, but in the end when it tries to upload the analysis to Sonarcloud, I'm getting this error:

```<code>ERROR: Error during SonarQube Scanner execution
ERROR: You're only authorized to execute a local (preview) SonarQube analysis without pushing the results to the SonarQube server. Please contact your SonarQube administrator.
</code>```

I've tried connecting to a local Sonarqube server and that works fine. Does anybody have any idea what's going wrong here?

答: You're likely missing the sonar.organization analysis property. You should be able to get the value from the Organization Key field on your project home page. If your project doesn't exist on the server yet, you can get it by logging in then: My Account > Organizations

Title: Error uploading analysis to SonarQube

Body:
I have a Sonarcloud account and I'm trying to analyze a Visual Studio solution using SonarQube.Scanner.MSBuild.exe.  I've created a token and am passing that on as the sonar.login property in the SonarQube.Analysis.xml file.
I'm using https://sonarcloud.io as sonar.host.url, but I've also tried https://sonarqube.com.

Here is the relevant snippet of the configuration:

<Property Name="sonar.host.url">https://sonarcloud.io</Property>
<Property Name="sonar.login">***my*token****</Property>
<Property Name="sonar.password"></Property>
<Property Name="sonar.organization">MyOrganization</Property>

The analysis seems to run fine, but in the end when it tries to upload the analysis to Sonarcloud, I'm getting this error:

ERROR: Error during SonarQube Scanner execution
ERROR: You're only authorized to execute a local (preview) SonarQube analysis without pushing the results to the SonarQube server. Please contact your SonarQube administrator.

I've tried connecting to a local Sonarqube server and that works fine. Does anybody have any idea what's going wrong here?


Title: filter df based on index condition

Body:
I have a df with lots of rows:

13790226       0.320  0.001976
9895d5dis    182.600  0.040450
105066007     18.890  0.006432
109067019     52.500  0.034011
111845014     16.400  0.023974
11668574e      7.180  0.070714
113307021      4.110  0.017514
113679I37      8.180  0.010837

I would like to filter this df in order to obtain the rows where the index last char is not a digit

Desired df:

9895d5dis    182.600  0.040450
11668574e      7.180  0.070714

How can I do it?

Body:
Here's a concise way without creating a new temp column:

df
                b         c
a
9895d5dis  182.60  0.040450
105066007   18.89  0.006432
109067019   52.50  0.034011
111845014   16.40  0.023974
11668574e    7.18  0.070714
113307021    4.11  0.017514
113679I37    8.18  0.010837

df[~df.index.str[-1].str.isnumeric()]
                b         c
a
9895d5dis  182.60  0.040450
11668574e    7.18  0.070714


问:
A Tkinter Frame is instantiated with super(). Why can I not make a Label widget its child?
This concerns Python and Tkinter.

I wish to have a Label widget display the word "Meow".

The Label widget should be the child of a Frame in a Tk window.

This seems simple, yet the code below does not work - nothing appears:

```<code>import tkinter as tk

class Options(tk.Frame):

    def __init__(self, gui_parent):

        super().__init__()
        tk.Label(self, text="Meow").pack()

class Gui(tk.Tk):

    def __init__(self):

        super().__init__()
        Options(self)

gui = Gui()
gui.mainloop()
</code>```

I then experimented: if I change the Label widget to tk.Label(gui_parent, text="Meow").pack(), the content of the window then appears. (However this is not the 'correct' behaviour, since I wish for the Label widget to be a direct child of the Frame widget, not of the Tk parent window.)

To my understanding, super().__init__() should have instantiated a Frame. The Label widget should then be able to access the Frame via self. This is not so.

Where have I gone wrong?

答:
You do not pack your Options widget. Try with:

```<code>Options(self).pack()
</code>```

Also, I would explicitly state that Options is the child of Gui, so you should pass gui_parent to the __init__ function of Options objects:

```<code>def __init__(self, gui_parent):
    super().__init__(gui_parent)
    tk.Label(self, text="Meow").pack()
</code>```

Body:
This concerns Python and Tkinter.

I wish to have a Label widget display the word "Meow".

The Label widget should be the child of a Frame in a Tk window.

This seems simple, yet the code below does not work - nothing appears:

import tkinter as tk

class Options(tk.Frame):

    def __init__(self, gui_parent):

        super().__init__()
        tk.Label(self, text="Meow").pack()

class Gui(tk.Tk):

    def __init__(self):

        super().__init__()
        Options(self)

gui = Gui()
gui.mainloop()

I then experimented: if I change the Label widget to tk.Label(gui_parent, text="Meow").pack(), the content of the window then appears. (However this is not the 'correct' behaviour, since I wish for the Label widget to be a direct child of the Frame widget, not of the Tk parent window.)

To my understanding, super().__init__() should have instantiated a Frame. The Label widget should then be able to access the Frame via self. This is not so.

Where have I gone wrong?

Body:
You do not pack your Options widget. Try with:

Options(self).pack()

Also, I would explicitly state that Options is the child of Gui, so you should pass gui_parent to the __init__ function of Options objects:

def __init__(self, gui_parent):
    super().__init__(gui_parent)
    tk.Label(self, text="Meow").pack()


问:
Ionic Share feature not working
I've been using Ionic for a while, including the "ionic share" command from the CLI.

However, recently, that command fails with:

```<code>$ ionic share

Invalid command (CLI v2.2.2)

Your system information:

Cordova CLI: 6.4.0
Ionic CLI Version: 2.2.2
Ionic App Lib Version: 2.2.1
ios-deploy version: 1.9.0
ios-sim version: 5.0.13
OS: macOS Sierra
Node Version: v6.9.3
Xcode version: Xcode 8.3 Build version 8E16
</code>```

Has anyone run into this issue?

Thanks,
Wayne

答:
As of now the Ionic CLI doesn't recognize the ionic share command, though their documentation hasn't updated this information.

However, you can now share your app from your ionic.io account:

Dashboard > Settings icon next to the app you want to share > Share

Then you'll be able to enter email addresses to share your preview with. Just had to go through that drudgery myself.

Title: Ionic Share feature not working

Body:
I've been using Ionic for a while, including the "ionic share" command from the CLI.

However, recently, that command fails with:

$ ionic share

Invalid command (CLI v2.2.2)

Your system information:

Cordova CLI: 6.4.0
Ionic CLI Version: 2.2.2
Ionic App Lib Version: 2.2.1
ios-deploy version: 1.9.0
ios-sim version: 5.0.13
OS: macOS Sierra
Node Version: v6.9.3
Xcode version: Xcode 8.3 Build version 8E16

Has anyone run into this issue?

Thanks,
Wayne


问:
Combining two MS Access queries
I have this query:

```<code>SELECT "I1" & "," & "I2" AS Item_set, Round(Sum([T1].Fuzzy_Value)/Count(*),15) AS Support
    FROM (SELECT *
    FROM Prune AS t
    WHERE t.Trans_ID IN

        (SELECT t1.Trans_ID FROM (

         SELECT *FROM Prune WHERE [Nama]="I1")  AS t1
         INNER JOIN (SELECT * FROM Prune WHERE [Nama]="I2")  AS t2 ON t1.Trans_ID = t2.Trans_ID)

    AND t.Nama IN ("I1","I2"))  AS T1;
</code>```

And ttrans query

```<code>SELECT Count([Trans_ID].[Trans_ID]) AS Expr1
FROM Trans_ID;
</code>```

I need to change Count (*) from :

```<code> SELECT "I1" & "," & "I2" AS Item_set, Round(Sum([T1].Fuzzy_Value)/Count(*),15)
</code>```

into ttrans query.

I've tried using

```<code>SELECT "I1" & "," & "I2" AS Item_set, Round(Sum([T1].Fuzzy_Value)/ttrans.Expr1,15) AS Support
FROM (SELECT *
FROM Prune AS t
WHERE t.Trans_ID IN

    (SELECT t1.Trans_ID FROM (

     SELECT *FROM Prune WHERE [Nama]="I1")  AS t1
     INNER JOIN (SELECT * FROM Prune WHERE [Nama]="I2")  AS t2 ON t1.Trans_ID = t2.Trans_ID)

AND t.Nama IN ("I1","I2"))  AS T1, ttrans;
</code>```

But I got error like this :

```<code>You tried to execute a query that does not include the specified expression
'Round(sum([T1].Fuzzy_Value/ttrans.Expr1,15)' as part of an aggregate function
</code>```

any idea how to fix it?

Note : I'm trying to find 2 combination of all item in transaction database and get a result like this

```<code>ITEM       Support
I1, I2     0.xxxxxxxxx
</code>```

where support is (total transaction containing item I1 and I2 / total transaction) -> note that I'm using ttrans query to get total transaction value

note2: I'm using MS Access
note3:

Ttrans table will look like this

```<code>Expr1
270200
</code>```

答:
Try:</p>

```<code>SELECT "I1" & "," & "I2" AS Item_set, Round(Sum([T1].Fuzzy_Value)/ttrans.Expr1,15) AS Support
FROM (SELECT *
FROM Prune AS t
WHERE t.Trans_ID IN

    (SELECT t1.Trans_ID FROM (

     SELECT *FROM Prune WHERE [Nama]="I1")  AS t1
     INNER JOIN (SELECT * FROM Prune WHERE [Nama]="I2")  AS t2 ON t1.Trans_ID = t2.Trans_ID)

AND t.Nama IN ("I1","I2"))  AS T1, ttrans
GROUP BY "I1" & "," & "I2"
</code>```

Title: Combining two MS Access queries

Body:
I have this query:

SELECT "I1" & "," & "I2" AS Item_set, Round(Sum([T1].Fuzzy_Value)/Count(*),15) AS Support
    FROM (SELECT *
    FROM Prune AS t
    WHERE t.Trans_ID IN

        (SELECT t1.Trans_ID FROM (

         SELECT *FROM Prune WHERE [Nama]="I1")  AS t1
         INNER JOIN (SELECT * FROM Prune WHERE [Nama]="I2")  AS t2 ON t1.Trans_ID = t2.Trans_ID)

    AND t.Nama IN ("I1","I2"))  AS T1;

And ttrans query

SELECT Count([Trans_ID].[Trans_ID]) AS Expr1
FROM Trans_ID;

I need to change Count (*) from :

 SELECT "I1" & "," & "I2" AS Item_set, Round(Sum([T1].Fuzzy_Value)/Count(*),15)

into ttrans query.

I've tried using

SELECT "I1" & "," & "I2" AS Item_set, Round(Sum([T1].Fuzzy_Value)/ttrans.Expr1,15) AS Support
FROM (SELECT *
FROM Prune AS t
WHERE t.Trans_ID IN

    (SELECT t1.Trans_ID FROM (

     SELECT *FROM Prune WHERE [Nama]="I1")  AS t1
     INNER JOIN (SELECT * FROM Prune WHERE [Nama]="I2")  AS t2 ON t1.Trans_ID = t2.Trans_ID)

AND t.Nama IN ("I1","I2"))  AS T1, ttrans;

But I got error like this :

You tried to execute a query that does not include the specified expression
'Round(sum([T1].Fuzzy_Value/ttrans.Expr1,15)' as part of an aggregate function

any idea how to fix it?

Note : I'm trying to find 2 combination of all item in transaction database and get a result like this

ITEM       Support
I1, I2     0.xxxxxxxxx

where support is (total transaction containing item I1 and I2 / total transaction) -> note that I'm using ttrans query to get total transaction value

note2: I'm using MS Access
note3:

Ttrans table will look like this

Expr1
270200

Body:
Try:

SELECT "I1" & "," & "I2" AS Item_set, Round(Sum([T1].Fuzzy_Value)/ttrans.Expr1,15) AS Support
FROM (SELECT *
FROM Prune AS t
WHERE t.Trans_ID IN

    (SELECT t1.Trans_ID FROM (

     SELECT *FROM Prune WHERE [Nama]="I1")  AS t1
     INNER JOIN (SELECT * FROM Prune WHERE [Nama]="I2")  AS t2 ON t1.Trans_ID = t2.Trans_ID)

AND t.Nama IN ("I1","I2"))  AS T1, ttrans
GROUP BY "I1" & "," & "I2"


问:
How can i apply left outer join conditions on four tables?
i was trying to apply joins on 4 tables. but i could not find proper result for that.
i have 4 tables like 1.students,2.college,3.locations,4.departments. so i have same column sid in all tables which can be used to join conditions.
i want all matched rows from four tables as mentioned columns in select statement below and unmatched rows in left table which is left outer join work.

i have tried this syntax.

```<code>select
  students.sname,
  college.cname,
  locations.loc,
  department.dept
from students, college, locaions, departments
where student.sid=college.sid(+)
and college.sid=locations.sid(+)
and locations.sid=department.sid(+);
</code>```

is this right ?

答:
This is an old-fashioned way of outer-joining in an Oracle database. For Oracle this statement is correct; in other DBMS it is invalid.

Anyway, nowadays (as of Oracle 9i; in other DBMS much longer) you should use standard SQL joins instead.

```<code>select
  s.sname,
  c.cname,
  l.loc,
  d.dept
from students s
left outer join college c on c.sid = s.sid
left outer join locations l on l.sid = c.sid
left outer join departments d on d.sid = l.sid;
</code>```

Body:
i was trying to apply joins on 4 tables. but i could not find proper result for that.
i have 4 tables like 1.students,2.college,3.locations,4.departments. so i have same column sid in all tables which can be used to join conditions.
i want all matched rows from four tables as mentioned columns in select statement below and unmatched rows in left table which is left outer join work.

i have tried this syntax.

select
  students.sname,
  college.cname,
  locations.loc,
  department.dept
from students, college, locaions, departments
where student.sid=college.sid(+)
and college.sid=locations.sid(+)
and locations.sid=department.sid(+);

is this right ?

Body:
This is an old-fashioned way of outer-joining in an Oracle database. For Oracle this statement is correct; in other DBMS it is invalid.

Anyway, nowadays (as of Oracle 9i; in other DBMS much longer) you should use standard SQL joins instead.

select
  s.sname,
  c.cname,
  l.loc,
  d.dept
from students s
left outer join college c on c.sid = s.sid
left outer join locations l on l.sid = c.sid
left outer join departments d on d.sid = l.sid;


问:
Multiple child elements in XSL for each
Am using for each tag in XSL:

Scenario

Input xml

```<code><root>
  <parent>
     <Child 1>
         <Child2>
              data1
              data2
              data3
                ....
                ...
         </child2>
        <Child2>
              data1
              data2
              data3
                ....
                ...
         </child2>
         <Child2>
              data1
              data2
              data3
                ....
                ...
         </child2>
</child1>
</parent>
</code>```

When I am using for each on parent tag, in transformation file it is taking only the first occurence of child 2 repeatedly .

My requirement is, it need to take all the child two elements of child one.

答:
Pretty sure from the comments that you've not got well-formed input XML. You can't have 2 R3 (root) elements at the top level of the document. This could be a push in the right direction.

Which data are you actually hoping to return, and in what format?

You've also hamstrung yourself by not having a repeating group inside Adress.

If you have the option, I'd reform your XML document into something more useful, because currently it's close to unworkable.

Recommend:

```<code><?xml version="1.0" encoding="UTF-8"?>
<AddressBook owner="" date="">
    <Address>
        <addr firstName="" secondName="">
        </addr>
        <addr firstName="" secondName="">
        </addr>
        <addr firstName="" secondName="">
        </addr>
    </Address>
    <Address>
        <addr firstName="" secondName="">
        </addr>
        <addr firstName="" secondName="">
        </addr>
        <addr firstName="" secondName="">
        </addr>
    </Address>
</AddressBook>
</code>```

This way, you can iterate through the elements which are named the same.

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">
    <xsl:template match="/AddressBook">
        <xsl:for-each select="Address">
            <xsl:for-each select="addr">
                <xsl:value-of select="concat(@firstName, ', ', @secondName)"/>
            </xsl:for-each>
        </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>
</code>```

Alternately, if you need to add address lines, make a repeating group inside your addr elements, and give them id's to sort by, to make sure they're in order.

Hope this points you in the right direction.

Title: Multiple child elements in XSL for each

Body:
Am using for each tag in XSL:

Scenario

Input xml

<root>
  <parent>
     <Child 1>
         <Child2>
              data1
              data2
              data3
                ....
                ...
         </child2>
        <Child2>
              data1
              data2
              data3
                ....
                ...
         </child2>
         <Child2>
              data1
              data2
              data3
                ....
                ...
         </child2>
</child1>
</parent>

When I am using for each on parent tag, in transformation file it is taking only the first occurence of child 2 repeatedly .

My requirement is, it need to take all the child two elements of child one.

Body:
Pretty sure from the comments that you've not got well-formed input XML. You can't have 2 R3 (root) elements at the top level of the document. This could be a push in the right direction.

Which data are you actually hoping to return, and in what format?

You've also hamstrung yourself by not having a repeating group inside Adress.

If you have the option, I'd reform your XML document into something more useful, because currently it's close to unworkable.

Recommend:

<?xml version="1.0" encoding="UTF-8"?>
<AddressBook owner="" date="">
    <Address>
        <addr firstName="" secondName="">
        </addr>
        <addr firstName="" secondName="">
        </addr>
        <addr firstName="" secondName="">
        </addr>
    </Address>
    <Address>
        <addr firstName="" secondName="">
        </addr>
        <addr firstName="" secondName="">
        </addr>
        <addr firstName="" secondName="">
        </addr>
    </Address>
</AddressBook>

This way, you can iterate through the elements which are named the same.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">
    <xsl:template match="/AddressBook">
        <xsl:for-each select="Address">
            <xsl:for-each select="addr">
                <xsl:value-of select="concat(@firstName, ', ', @secondName)"/>
            </xsl:for-each>
        </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>

Alternately, if you need to add address lines, make a repeating group inside your addr elements, and give them id's to sort by, to make sure they're in order.

Hope this points you in the right direction.


问:
strings returned by wcf wrapped with extra quotes
I'm stuck with this problem for the last 2 days:

I have server running WCF JSON service that returns type: string.

The client that consumes this service is Android application.

The problem:

The string returned by the WCF service seems to be fine (for example: "result_1"), but the value in the Android application looks like this: ""result_1"" (note the problematic extra quotes...).

What should i do in order to fix this?
Thanks.

答:
I have had this problem with iPhone developers in my workplace. The workaround I used was returning a custom class object instead of String like following:

```<code>public class StringContainer
{
    public String Value { get; set; }
}
</code>```

Body:
I have had this problem with iPhone developers in my workplace. The workaround I used was returning a custom class object instead of String like following:

public class StringContainer
{
    public String Value { get; set; }
}


问:
Golang: How to construct a struct for Elasticsearch pipeline attachment
I'm constructing a struct to send a put message to Elasticsearch for pipeline attachment.

This is the json that I'm supposed to send it to ES:

```<code>PUT _ingest/pipeline/attachment
{
    "description": "Process documents",
    "processors": [
        {
            "attachment": {
                "field": "thedata",
                "indexed_chars": -1
            }
        },
        {
            "set": {
                "field": "attachment.title",
                "value": "{{ title }}"
            }
        },
        {
            "set": {
                "field": "attachment.author",
                "value": "{{ author }}"
            }
        },
        {
            "set": {
                "field": "attachment.url",
                "value": "{{ url }}"
            }
        },
        {
            "set": {
                "field": "attachment.cover",
                "value": "{{ cover }}"
            }
        },
        {
            "set": {
                "field": "attachment.page",
                "value": "{{ page }}"
            }
        }
    ]
}
</code>```

Do I really need to make a struct and marshal it in order to put the message? (I'm coming from Python). Setting up pipeline is a single time process.

I'm constructing structs like this in Go:

```<code>type AS struct {
    Description string

}

type ASP struct {
    Processors
}

type ASPA struct {
    Attachment []ASPAF `json:"attachment"`
}

type ASPAF struct {
    Field string `json:"field"`
    IndexedChars uint64 `json:"indexed_chars"`
}

type ASPS struct {
    Set []ASPSF `json:"set"`
}

type ASPSF struct {
    Field string `json:"field"`
    Value string `json:"value"`
}
</code>```

If you can see the code, I'm stuck at ASP struct and AS struct for processors and rounding up as attachment struct with description.

Could someone guide me? I'm not even sure if I'm right with the above structs.

Thanks!

答: you can use logrus package which has elastic search hook and is simple enough.</p>

Body:
I'm constructing a struct to send a put message to Elasticsearch for pipeline attachment.

This is the json that I'm supposed to send it to ES:

PUT _ingest/pipeline/attachment
{
    "description": "Process documents",
    "processors": [
        {
            "attachment": {
                "field": "thedata",
                "indexed_chars": -1
            }
        },
        {
            "set": {
                "field": "attachment.title",
                "value": "{{ title }}"
            }
        },
        {
            "set": {
                "field": "attachment.author",
                "value": "{{ author }}"
            }
        },
        {
            "set": {
                "field": "attachment.url",
                "value": "{{ url }}"
            }
        },
        {
            "set": {
                "field": "attachment.cover",
                "value": "{{ cover }}"
            }
        },
        {
            "set": {
                "field": "attachment.page",
                "value": "{{ page }}"
            }
        }
    ]
}

Do I really need to make a struct and marshal it in order to put the message? (I'm coming from Python). Setting up pipeline is a single time process.

I'm constructing structs like this in Go:

type AS struct {
    Description string

}

type ASP struct {
    Processors
}

type ASPA struct {
    Attachment []ASPAF `json:"attachment"`
}

type ASPAF struct {
    Field string `json:"field"`
    IndexedChars uint64 `json:"indexed_chars"`
}

type ASPS struct {
    Set []ASPSF `json:"set"`
}

type ASPSF struct {
    Field string `json:"field"`
    Value string `json:"value"`
}

If you can see the code, I'm stuck at ASP struct and AS struct for processors and rounding up as attachment struct with description.

Could someone guide me? I'm not even sure if I'm right with the above structs.

Thanks!


问:
batch file bcp command
Stuck with a simple batch file that runs a bcp command.
I need this batch file to loop thru a txt file that contains the tables names.

Here is what I have so far

```<code>set hour=%time:~0,2%
if "%hour:~0,1%" == " " set hour=0%hour:~1,1%
echo hour=%hour%
set min=%time:~3,2%
if "%min:~0,1%" == " " set min=0%min:~1,1%
echo min=%min%
set secs=%time:~6,2%
if "%secs:~0,1%" == " " set secs=0%secs:~1,1%
echo secs=%secs%

set year=%date:~-4%
echo year=%year%

set dt=%date:~-4,4%%date:~-10,2%%date:~-7,2%_%hour%%min%%secs%
set filename=%1
bcp TABLE.dbo.%1 OUT C:\temp\%filename%_%dt%.dat -n -T
</code>```

I like the %1 come from input.txt file that might have 50 table names.

Thank you for your help

答:
I'd use the for command to loop through a text file.  See for /? for help.

Let's say that the filename is input.txt, with one table name on each line.  You call it with myscript.cmd input.txt:

```<code>set hour=%time:~0,2%
if "%hour:~0,1%" == " " set hour=0%hour:~1,1%
echo hour=%hour%
set min=%time:~3,2%
if "%min:~0,1%" == " " set min=0%min:~1,1%
echo min=%min%
set secs=%time:~6,2%
if "%secs:~0,1%" == " " set secs=0%secs:~1,1%
echo secs=%secs%

set year=%date:~-4%
echo year=%year%

set dt=%date:~-4,4%%date:~-10,2%%date:~-7,2%_%hour%%min%%secs%

for /f %%i in (%1) do (
    bcp TABLE.dbo.%%i OUT C:\temp\%%i_%dt%.dat -n -T
)
</code>```

Title: batch file bcp command

Body:
Stuck with a simple batch file that runs a bcp command.
I need this batch file to loop thru a txt file that contains the tables names.

Here is what I have so far

set hour=%time:~0,2%
if "%hour:~0,1%" == " " set hour=0%hour:~1,1%
echo hour=%hour%
set min=%time:~3,2%
if "%min:~0,1%" == " " set min=0%min:~1,1%
echo min=%min%
set secs=%time:~6,2%
if "%secs:~0,1%" == " " set secs=0%secs:~1,1%
echo secs=%secs%

set year=%date:~-4%
echo year=%year%

set dt=%date:~-4,4%%date:~-10,2%%date:~-7,2%_%hour%%min%%secs%
set filename=%1
bcp TABLE.dbo.%1 OUT C:\temp\%filename%_%dt%.dat -n -T

I like the %1 come from input.txt file that might have 50 table names.

Thank you for your help

Body:
I'd use the for command to loop through a text file.  See for /? for help.

Let's say that the filename is input.txt, with one table name on each line.  You call it with myscript.cmd input.txt:

set hour=%time:~0,2%
if "%hour:~0,1%" == " " set hour=0%hour:~1,1%
echo hour=%hour%
set min=%time:~3,2%
if "%min:~0,1%" == " " set min=0%min:~1,1%
echo min=%min%
set secs=%time:~6,2%
if "%secs:~0,1%" == " " set secs=0%secs:~1,1%
echo secs=%secs%

set year=%date:~-4%
echo year=%year%

set dt=%date:~-4,4%%date:~-10,2%%date:~-7,2%_%hour%%min%%secs%

for /f %%i in (%1) do (
    bcp TABLE.dbo.%%i OUT C:\temp\%%i_%dt%.dat -n -T
)


问:
How to clear all SpellBox controls in WinForm
I have a WinForm project which utilises SpellBoxes from WPF. I am now creating a function to clear all of my fields, and TextBoxes in the class. The textBoxes are actually SpellBoxes intergrated into the project which is why I think I am getting this problem. From my understanding this will be best achieved by looping through all of my controls with something similar to this:

```<code>public void ClearControls()
        {
            foreach (Control control in panel1.Controls)
            {
                if (control is SpellBox)
                {
                    SpellBox txt = (SpellBox)control;
                    txt.Text = "";
                }

            }
        }
</code>```

And then called on  a click event, ClearControls();

However due to me using SpellBoxes I cannot seem to even iterate through, it’s as if they’re not even recognised. The above function works with TextBox’s, but not with spellBox’s.  If anyone could give me some indication as to why this is happening, I would be grateful. Thanks in advance

答:
Quick example of a recursive search:

```<code>public void ClearControls(Control cntr)
{
    foreach (Control control in cntr.Controls)
    {
        if (control is SpellBox)
        {
            control.Text = "";
        }
        else if(control.HasChildren)
        {
            ClearControls(control);
        }
    }
}
</code>```

You start it off by passing in the Form itself via this:

```<code>ClearControls(this);
</code>```

Body:
I have a WinForm project which utilises SpellBoxes from WPF. I am now creating a function to clear all of my fields, and TextBoxes in the class. The textBoxes are actually SpellBoxes intergrated into the project which is why I think I am getting this problem. From my understanding this will be best achieved by looping through all of my controls with something similar to this:

public void ClearControls()
        {
            foreach (Control control in panel1.Controls)
            {
                if (control is SpellBox)
                {
                    SpellBox txt = (SpellBox)control;
                    txt.Text = "";
                }

            }
        }

And then called on  a click event, ClearControls();

However due to me using SpellBoxes I cannot seem to even iterate through, it’s as if they’re not even recognised. The above function works with TextBox’s, but not with spellBox’s.  If anyone could give me some indication as to why this is happening, I would be grateful. Thanks in advance

Body:
Quick example of a recursive search:

public void ClearControls(Control cntr)
{
    foreach (Control control in cntr.Controls)
    {
        if (control is SpellBox)
        {
            control.Text = "";
        }
        else if(control.HasChildren)
        {
            ClearControls(control);
        }
    }
}

You start it off by passing in the Form itself via this:

ClearControls(this);


答:
Is the column on which you are filtering index or a column? If its a column

```<code>df1 = df[df[0].str.contains('[A-Za-z]')]
</code>```

Returns

```<code>    0           1       2
1   9895d5dis   182.60  0.040450
5   11668574e   7.18    0.070714
7   113679I37   8.18    0.010837 #looks like read_clipboard is reading 1 in 113679137 as I
</code>```

If its index, first do

```<code>df = df.reset_index()
</code>```

Title: filter df based on index condition

Body:
I have a df with lots of rows:

13790226       0.320  0.001976
9895d5dis    182.600  0.040450
105066007     18.890  0.006432
109067019     52.500  0.034011
111845014     16.400  0.023974
11668574e      7.180  0.070714
113307021      4.110  0.017514
113679I37      8.180  0.010837

I would like to filter this df in order to obtain the rows where the index last char is not a digit

Desired df:

9895d5dis    182.600  0.040450
11668574e      7.180  0.070714

How can I do it?

Body:
Is the column on which you are filtering index or a column? If its a column

df1 = df[df[0].str.contains('[A-Za-z]')]

Returns

    0           1       2
1   9895d5dis   182.60  0.040450
5   11668574e   7.18    0.070714
7   113679I37   8.18    0.010837 #looks like read_clipboard is reading 1 in 113679137 as I

If its index, first do

df = df.reset_index()


问:
How to retain the entered data in an html form after clicking submit
I have a form in an html page that ends up being cleared after i click the submit button. I wanted to know how I to make the data stay in the form after clicking submit in case the user needs to fix any errors. Any help would be appreciated!

Here is the html code:

```<code><form id = "contactform" action = "">
<label> Name:
<input name = "firstname" type = "text" id = "firstname" maxlength = "50"/>
</label>
<label> Last Name:
<input name = "lastname" type = "text" id = "lastname" maxlength = "150" />
</label>
<label> Address:
<input name = "address" type = "text" id = "address" maxlength = "200"/>
</label>
<label> Postcode:
<input name = "postcode" type = "text" id = "postcode" maxlength = "50" />
</label>
<input type = "submit" value = "Submit" onclick = "validate()" />
<input type = "reset" value = "Clear" />
</p>
</form>
</code>```

and here is the javascript code:

```<code>function validate() {

var firstname = document.getElementById('firstname');
var lastname = document.getElementById('lastname');
var address = document.getElementById('address');
var postcode = document.getElementById('postcode');

if(firstname.value == "") {
    alert("Make sure the first name field is filled");
    return false;
    }

if(lastname.value == "") {
        alert("Make sure the last name field is filled");
        return false;
        }
if(address.value == "") {
        alert("Make sure the address field is filled");
        return false;
        }
if(postcode.value == "") {
        alert("Make sure the post code field is filled");
        return false;
        }
</code>```

答:
First, add a submit handler to your form:

```<code><form id="contactform" action = "" onsubmit="handleSubmit()">
  ...
</form>
</code>```

Then in your handler validate the input. If its not valid you need to preventDefault() to stop the form from submitting. Note: You'll have to return true at the end of validate() if nothing is wrong. I don't see that in the question.

```<code>function handleSubmit(event) {
  if(!validate()) {
    event.preventDefault();
  }
  return;
}
</code>```

Body:
I have a form in an html page that ends up being cleared after i click the submit button. I wanted to know how I to make the data stay in the form after clicking submit in case the user needs to fix any errors. Any help would be appreciated!

Here is the html code:

<form id = "contactform" action = "">
 Name:
<input name = "firstname" type = "text" id = "firstname" maxlength = "50"/>

 Last Name:
<input name = "lastname" type = "text" id = "lastname" maxlength = "150" />

 Address:
<input name = "address" type = "text" id = "address" maxlength = "200"/>

 Postcode:
<input name = "postcode" type = "text" id = "postcode" maxlength = "50" />

<input type = "submit" value = "Submit" onclick = "validate()" />
<input type = "reset" value = "Clear" />

</form>

and here is the javascript code:

function validate() {

var firstname = document.getElementById('firstname');
var lastname = document.getElementById('lastname');
var address = document.getElementById('address');
var postcode = document.getElementById('postcode');

if(firstname.value == "") {
    alert("Make sure the first name field is filled");
    return false;
    }

if(lastname.value == "") {
        alert("Make sure the last name field is filled");
        return false;
        }
if(address.value == "") {
        alert("Make sure the address field is filled");
        return false;
        }
if(postcode.value == "") {
        alert("Make sure the post code field is filled");
        return false;
        }

Body:
First, add a submit handler to your form:

<form id="contactform" action = "" onsubmit="handleSubmit()">
  ...
</form>

Then in your handler validate the input. If its not valid you need to preventDefault() to stop the form from submitting. Note: You'll have to return true at the end of validate() if nothing is wrong. I don't see that in the question.

function handleSubmit(event) {
  if(!validate()) {
    event.preventDefault();
  }
  return;
}


问:
Creating Date Partitioned Tables programmatically
Is there a way to create a date partitioned table using Apache Beam BigQueryIO, in other words, is there a way to use partition decorator for a table which is not created yet?

I know that I can create a table at first and then I can use partition decorator within my code but since I dynamically determine the TableDestination from fields of rows, I cannot create these tables in advance.

My code is like this:

```<code>rows.apply("Write rows",
    BigQueryIO.writeTableRows()
      .to(new SerializableFunction<ValueInSingleWindow<TableRow>, TableDestination>() {
          @Override
          public TableDestination apply(ValueInSingleWindow<TableRow> value) {
            TableRow t = value.getValue();

            String tableName = ... // get from the fields of table row
            String partition = ... // get the date part that will be used for decorator

            TableDestination td = new TableDestination(
                      "project-id:dataset-id." + tableName + "$" + partition, "");
              return td;
          }
      }).withSchema(someSchema)
      .withWriteDisposition(BigQueryIO.Write.WriteDisposition.WRITE_APPEND)
    .withCreateDisposition(BigQueryIO.Write.CreateDisposition.CREATE_IF_NEEDED));
</code>```

With this, it tries to create a table of project-id:dataset-id.tableName$partition and it complains that $ cannot be used inside a table name.

答: Table id format: The ID of the table. The ID must contain only letters (a-z, A-Z), numbers (0-9), or underscores (_). The maximum length is 1,024 characters. check the BigQuery doc.

Body:
Is there a way to create a date partitioned table using Apache Beam BigQueryIO, in other words, is there a way to use partition decorator for a table which is not created yet?

I know that I can create a table at first and then I can use partition decorator within my code but since I dynamically determine the TableDestination from fields of rows, I cannot create these tables in advance.

My code is like this:

rows.apply("Write rows",
    BigQueryIO.writeTableRows()
      .to(new SerializableFunction<ValueInSingleWindow<TableRow>, TableDestination>() {
          @Override
          public TableDestination apply(ValueInSingleWindow<TableRow> value) {
            TableRow t = value.getValue();

            String tableName = ... // get from the fields of table row
            String partition = ... // get the date part that will be used for decorator

            TableDestination td = new TableDestination(
                      "project-id:dataset-id." + tableName + "$" + partition, "");
              return td;
          }
      }).withSchema(someSchema)
      .withWriteDisposition(BigQueryIO.Write.WriteDisposition.WRITE_APPEND)
    .withCreateDisposition(BigQueryIO.Write.CreateDisposition.CREATE_IF_NEEDED));

With this, it tries to create a table of project-id:dataset-id.tableName$partition and it complains that $ cannot be used inside a table name.


问:
How would I tell a browser to render a string, not display it
I have this extension method I created and it returns a string of all the categories in my database as hyperlinks. Great!

```<code>@Html.MyMenu()
</code>```

The problem is that the links are being displayed as text and not rendered as hyperlinks.

When viewing the source code I see:

```<code><div id="menucontainer">

                <a href="/Anuncio/Electronics">Electronics</a><a href="/Anuncio/Clothes">Clothes</a><a href="/Anuncio/Domestic">Domestic</a><a href="/Anuncio/Garden">Garden</a>

            </div>
</code>```

I think I may be wrong but I remember that in MVC2 (using the default view engine) you had:

```<code><%: this is rendered, right? %>
</code>```

Or am I mistaken? Anyways, I'm using MVC3 and the Razor engine. Thanks a lot for your help guys. I'm really enjoying learning as much as I can about this.

答: well your extension method should be returning an MvcHtmlString in order to properly display on your page using the <%: %> If it returns a string, all angle brackets and other html special characters will be html-encoded.

OwnerDisplayName: delete

Body:
I have this extension method I created and it returns a string of all the categories in my database as hyperlinks. Great!

@Html.MyMenu()

The problem is that the links are being displayed as text and not rendered as hyperlinks.

When viewing the source code I see:

                ElectronicsClothesDomesticGarden

I think I may be wrong but I remember that in MVC2 (using the default view engine) you had:

<%: this is rendered, right? %>

Or am I mistaken? Anyways, I'm using MVC3 and the Razor engine. Thanks a lot for your help guys. I'm really enjoying learning as much as I can about this.


问:
&amp in url using window.location
I try to use window.location with parameters within twig and javascript.

```<code>function() {
   window.location = '{{ redirect_uri ~ '?status=cancel&review_id=' ~ review_id }}';
});
</code>```

The problem is that the new url has &amp instead of &.

Example:

http://local.dev/app_dev.php/admin?status=cancel&review_id=67

答:
You can use the raw filter, as example:

```<code>function() {
   window.location = '{{ (redirect_uri ~ '?status=cancel&review_id=' ~ review_id)|raw }}';
});
</code>```

Here a working example

Title: &amp in url using window.location

Body:
I try to use window.location with parameters within twig and javascript.

function() {
   window.location = '{{ redirect_uri ~ '?status=cancel&review_id=' ~ review_id }}';
});

The problem is that the new url has &amp instead of &.

Example:

http://local.dev/app_dev.php/admin?status=cancel&review_id=67

Body:
You can use the raw filter, as example:

function() {
   window.location = '{{ (redirect_uri ~ '?status=cancel&review_id=' ~ review_id)|raw }}';
});

Here a working example


问:
Embed Google Drive in Google Site
I am developing a Google Site that display different kinds of Data and soon integrating with files that is connected in Google Drive and this is where my question goes. As far as I know to import a Google Drive by doing this.

```<code>Selected Google Site > Edit > Insert > Then Select a Folder
</code>```

and by that a list of files in my selected folder will display in my site in List View

Thats one solution for me. However I want also to integrate search function like a textbox below that gadget and when i search on that list of files will also show. How can I achieved that?

and also in addition how can I embed the search fucntion of Google search on that? For example I search test it will just not display the file that has a name of test but also files that contains test

any means of help is highly appreciated. TYSM

答:
Try using Apps Script and deploying it as a web app then embedding it in your Google Site. According to the document:

Web apps can also be embedded in Google Sites. (These embedded web apps are sometimes called Google Sites Gadgets.)

To create a script that is bound to Google Sites, visit your site, click the gear icon, then select Manage site. Click Google Apps Scripts, then Add new script. After that, the process is the same as for creating and deploying a web app as above.

For the searching purposes use the field fullText which will check the Full text of the file including name, description, content, and indexable text. See Search for Files documents for further information

```<code>folder.searchFiles('fullText contains "' + search + '"')
</code>```

Useful reference:

Search Google Drive folder from Google Site using Apps Script

Hope this helps.

Title: Embed Google Drive in Google Site

Body:
I am developing a Google Site that display different kinds of Data and soon integrating with files that is connected in Google Drive and this is where my question goes. As far as I know to import a Google Drive by doing this.

Selected Google Site > Edit > Insert > Then Select a Folder

and by that a list of files in my selected folder will display in my site in List View

Thats one solution for me. However I want also to integrate search function like a textbox below that gadget and when i search on that list of files will also show. How can I achieved that?

and also in addition how can I embed the search fucntion of Google search on that? For example I search test it will just not display the file that has a name of test but also files that contains test

any means of help is highly appreciated. TYSM

Body:
Try using Apps Script and deploying it as a web app then embedding it in your Google Site. According to the document:

Web apps can also be embedded in Google Sites. (These embedded web apps are sometimes called Google Sites Gadgets.)

To create a script that is bound to Google Sites, visit your site, click the gear icon, then select Manage site. Click Google Apps Scripts, then Add new script. After that, the process is the same as for creating and deploying a web app as above.

For the searching purposes use the field fullText which will check the Full text of the file including name, description, content, and indexable text. See Search for Files documents for further information

folder.searchFiles('fullText contains "' + search + '"')

Useful reference:

Search Google Drive folder from Google Site using Apps Script

Hope this helps.


问:
How to integrate admob with google play services?
Can anyone please tell me how to integrate admob plugin with google play services plug in unity.I am struggle since long time to solve this problem .But, I am not able to solve it.</p>

答:
You could start using the AdMob for Unity.

The Google Mobile Ads SDK is the latest generation in Google mobile advertising featuring refined ad formats and streamlined APIs for access to mobile ad networks and advertising solutions. The SDK enables mobile app developers to maximize their monetization in native mobile apps.

This repository contains the source code for the Google Mobile Ads Unity plugin. This plugin enables Unity developers to easily serve Google Mobile Ads on Android and iOS apps without having to write Java or Objective-C code. The plugin provides a C# interface for requesting ads that is used by C# scripts in your Unity project.

As stated in the related SO post, Google has official support for AdMob on Unity game engine and this is the GitHub for Google Mobile Ads Unity plugin.

Hope this helps.


问:
Android DeadSystemException
Currently, we are experiencing a DeadSystemException in our HockeyApp crash reporting. It occurs on Android 7.0 and Android 7.1. We don't experience this exception in the previous version of our application (they are currently both used by users), so I guess this exception is caused by some code change. But stack trace is not very helpful for this. Any idea?
Thanks for any suggestions.

Stack trace from HockeyApp:

```<code>java.lang.RuntimeException: android.os.DeadSystemException
at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3781)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: android.os.DeadSystemException
... 8 more
</code>```

答:
The Android Developer docs for android.os.DeadSystemException says the following:

The core Android system has died and is going through a runtime
restart. All running apps will be promptly killed.

The source code does not help much more:

```<code>package android.os;
/**
 * The core Android system has died and is going through a runtime restart. All
 * running apps will be promptly killed.
 */
public class DeadSystemException extends DeadObjectException {
    public DeadSystemException() {
        super();
    }
}
</code>```

Overall, it looks like this is being thrown by the OS and has nothing to do with our code.

Looking at the JavaDoc from the superclass, DeadObjectException, backs this theory up:

The object you are calling has died because its hosting process no
longer exists.

Title: Android DeadSystemException

Body:
Currently, we are experiencing a DeadSystemException in our HockeyApp crash reporting. It occurs on Android 7.0 and Android 7.1. We don't experience this exception in the previous version of our application (they are currently both used by users), so I guess this exception is caused by some code change. But stack trace is not very helpful for this. Any idea?
Thanks for any suggestions.

Stack trace from HockeyApp:

java.lang.RuntimeException: android.os.DeadSystemException
at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3781)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: android.os.DeadSystemException
... 8 more

Body:
The Android Developer docs for android.os.DeadSystemException says the following:

The core Android system has died and is going through a runtime
restart. All running apps will be promptly killed.

The source code does not help much more:

package android.os;
/**
 * The core Android system has died and is going through a runtime restart. All
 * running apps will be promptly killed.
 */
public class DeadSystemException extends DeadObjectException {
    public DeadSystemException() {
        super();
    }
}

Overall, it looks like this is being thrown by the OS and has nothing to do with our code.

Looking at the JavaDoc from the superclass, DeadObjectException, backs this theory up:

The object you are calling has died because its hosting process no
longer exists.


问:
Sorting data by multiple fields and conditions
I want to sort the data according to following conditions:

Sort by type with precedence as [state,city,district].

-Data with type state should be at first place, then data with city and so on.

Duplicate data should be sort by score.

-eg : if 3 rows are with type, then sort it by score.

My data object is:

```<code>$scope.data = [{
 id: 1,
 name: 'ABC',
 type: 'city',
 score: 0.1
}, {
 id: 2,
 name: 'PQR',
 type: 'city',
 score: 0.7
}, {
 id: 3,
 name: 'ABC',
 type: 'state',
 score: 0.3
});
</code>```

And template is:

```<code><div ng-repeat="d in data">
 <span>{{d.name}}</span>
 <span>{{d.type}}</span>
 <span>{{d.score}}</span>
</div>
</code>```

Result should be like this:

```<code>ABC state 0.3
PQR city 0.7
ABC city 0.1
</code>```

Here is the link of plunker.

I want to sort it by multiple fields as well as with a specific precedence.

Any help will be appreciated. Thanks in advance.

答:
You with find all you need in lodash library.

Here is the documentation : https://lodash.com/docs/4.17.4

A start point for you will be the orderBy method : https://lodash.com/docs/4.17.4#orderBy

To resolve your issue :

```<code>$scope.data = lodash.orderBy($scope.data, ['type','score'], ['desc', 'desc']);
</code>```

You can use ngLodash for angularjs (simple install with bower / npm) : https://github.com/rockabox/ng-lodash

Enjoy!

Body:
I want to sort the data according to following conditions:

Sort by type with precedence as [state,city,district].

-Data with type state should be at first place, then data with city and so on.

Duplicate data should be sort by score.

-eg : if 3 rows are with type, then sort it by score.

My data object is:

$scope.data = [{
 id: 1,
 name: 'ABC',
 type: 'city',
 score: 0.1
}, {
 id: 2,
 name: 'PQR',
 type: 'city',
 score: 0.7
}, {
 id: 3,
 name: 'ABC',
 type: 'state',
 score: 0.3
});

And template is:

 {{d.name}}
 {{d.type}}
 {{d.score}}

Result should be like this:

ABC state 0.3
PQR city 0.7
ABC city 0.1

Here is the link of plunker.

I want to sort it by multiple fields as well as with a specific precedence.

Any help will be appreciated. Thanks in advance.

Body:
You with find all you need in lodash library.

Here is the documentation : https://lodash.com/docs/4.17.4

A start point for you will be the orderBy method : https://lodash.com/docs/4.17.4#orderBy

To resolve your issue :

$scope.data = lodash.orderBy($scope.data, ['type','score'], ['desc', 'desc']);

You can use ngLodash for angularjs (simple install with bower / npm) : https://github.com/rockabox/ng-lodash

Enjoy!


问:
How to make mod_rewrite *not* perform home directory expansion when using .htaccess
Filepath: /Users/user_name/Sites/example.com

Browseable at: http://localhost/~user_name/example.com/

In a child directory (chrome) I got a .htaccess like this:

```<code>Options +FollowSymLinks
RewriteEngine on
RewriteRule ^rgba\((\d{1,3}%?,\s?\d{1,3}%?,\s?\d{1,3}%?,\s?[0-1]?\.?\d+)\)$ rgba.php?rgba=$1 [PT]
</code>```

This matches a request like:

```<code>http://localhost/~user_name/example.com/chrome/rgba(255,255,255,0.5)
</code>```

and should rewrite the request to:

```<code>http://localhost/~user_name/example.com/chrome/rgba.php?rgba=(255,255,255,0.5)
</code>```

I put the rgba.php in the chrome directory. Still I get this error msg:

```<code>The requested URL /Users/user_name/Sites/example.com/chrome/rgba.php was not found on this server.
</code>```

I read the part in the manual about Home directory expansion and the [PT] flag but it makes no difference.

If i put up a vhost pointing to the example.com directory it works. I would like it to work both ways =P

So how do I do it?

I run Apache/2.2.15 (Unix) on a Mac OS X

EDIT
AllowOverride is set to All for the users Sites directory. If it wasn´t the rewrite shouldn´t have worked at all.

答: Allow overrides in you configuration file for your home directories.</p>

Body:
Filepath: /Users/user_name/Sites/example.com

Browseable at: http://localhost/~user_name/example.com/

In a child directory (chrome) I got a .htaccess like this:

Options +FollowSymLinks
RewriteEngine on
RewriteRule ^rgba\((\d{1,3}%?,\s?\d{1,3}%?,\s?\d{1,3}%?,\s?[0-1]?\.?\d+)\)$ rgba.php?rgba=$1 [PT]

This matches a request like:

http://localhost/~user_name/example.com/chrome/rgba(255,255,255,0.5)

and should rewrite the request to:

http://localhost/~user_name/example.com/chrome/rgba.php?rgba=(255,255,255,0.5)

I put the rgba.php in the chrome directory. Still I get this error msg:

The requested URL /Users/user_name/Sites/example.com/chrome/rgba.php was not found on this server.

I read the part in the manual about Home directory expansion and the [PT] flag but it makes no difference.

If i put up a vhost pointing to the example.com directory it works. I would like it to work both ways =P

So how do I do it?

I run Apache/2.2.15 (Unix) on a Mac OS X

EDIT
AllowOverride is set to All for the users Sites directory. If it wasn´t the rewrite shouldn´t have worked at all.