问:
soot, identity stmts and the control flow during exception handling
I'm trying to write a try-catch block in soot.

Let's decompile

```<code>public class A {
    public static void main(String[] args) {
        try{
            String a = args[9999];
        }catch(Throwable t){
            t.printStackTrace();
        }
        System.out.println("Hello World");
    }
}
</code>```

I will add the full decompilation to the end of the question. The important parts are

```<code>     0: aload_0
     1: sipush        9999
     4: aaload
     5: astore_1
     6: goto          14
     9: astore_1
    10: aload_1
    11: invokevirtual #3                  // Method java/lang/Throwable.printStackTrace:()V
    14: getstatic     #4                  // Field java/lang/System.out:Ljava/io/PrintStream;
    17: ldc           #5                  // String Hello World
    19: invokevirtual #6                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
    22: return
</code>```

and

```<code>  Exception table:
     from    to  target type
         0     6     9   Class java/lang/Throwable
</code>```

So what this implies is that if any of the instructions 0-6 throw an exception, control will be re-routed to 9 and execution will continue as if normal, the astore_1 there being the storing of the reference to the exception object in a local variable.

However, I'm trying to generate a try-catch block in soot and I found one example that actually does something like this: CatchWrapInstrumenter.java

According to documentation, newTrap

Constructs a new JTrap for the given exception on the given Stmt range with the given Stmt handler.

So when we see

```<code>b.getTraps().add(Jimple.v().newTrap(thrwCls, sFirstNonId, sGotoLast, sCatch));
</code>```

We can guess that this essentially is saying "if there's an exception of type thrwCls thrown in any of the stmts between sFirstNonId, sGotoLast, jump to the handler at sCatch.

So far, this matches expectations.

Now, what bothers me, is that

```<code>Stmt sCatch = Jimple.v().newIdentityStmt(lException1, Jimple.v().newCaughtExceptionRef());
</code>```

is an identity stmt.

Because identity stmts

are statements which define locals to be pre-loaded (upon method entry)
  with special values such as parameters or the this value.

For example, l0 :=
  @this: A defines local l0 to be the this of the method.

This identification is necessary because the local variables are not numbered (normally the this variable is the variable in local variable slot 0 at the bytecode level.)

(page 31 [numbered 23] in the soot paper)

So -- taking again class A as an example -- if I were to generate (simplified)

```<code>Sting a;Throwable t;PrintStream out;

a = arg[9990]               //stmt1
goto stmt5                  //stmt2
t := thrownException;       //stmt3
t.printStackTrace();        //stmt4
out = System.out;           //stmt5
out.println("Hello World")  //stmt6
</code>```

with the intention to register

```<code>newTrap(exception=java.lang.Throwable, beginStmt=stmt1,endStmt=stmt2,handlerStmt=stmt3)
</code>```

, as I would have based on the decompiled A.class, this would actually be illegal because t := thrownException is supposed to be "pre-loaded (upon method entry)".

Yet at the same time, this is exactly what we are to do if the example on page 86 [numbered 78] of the soot paper is to be trusted.

This concept of "pre-loading" something that does not yet exists at the time it does, doesn't make terribly much sense to me and makes me think I could be wrong on the control flow, though I do not see how.

Could somebody please explain what is actually happening, here?

Full decompiled code of the small try-catch example:

```<code>public class A
  minor version: 0
  major version: 51
  flags: ACC_PUBLIC, ACC_SUPER
Constant pool:
   #1 = Methodref          #8.#28         // java/lang/Object."<init>":()V
   #2 = Class              #29            // java/lang/Throwable
   #3 = Methodref          #2.#30         // java/lang/Throwable.printStackTrace:()V
   #4 = Fieldref           #31.#32        // java/lang/System.out:Ljava/io/PrintStream;
   #5 = String             #33            // Hello World
   #6 = Methodref          #34.#35        // java/io/PrintStream.println:(Ljava/lang/String;)V
   #7 = Class              #36            // A
   #8 = Class              #37            // java/lang/Object
   #9 = Utf8               <init>
  #10 = Utf8               ()V
  #11 = Utf8               Code
  #12 = Utf8               LineNumberTable
  #13 = Utf8               LocalVariableTable
  #14 = Utf8               this
  #15 = Utf8               LA;
  #16 = Utf8               main
  #17 = Utf8               ([Ljava/lang/String;)V
  #18 = Utf8               a
  #19 = Utf8               Ljava/lang/String;
  #20 = Utf8               t
  #21 = Utf8               Ljava/lang/Throwable;
  #22 = Utf8               args
  #23 = Utf8               [Ljava/lang/String;
  #24 = Utf8               StackMapTable
  #25 = Class              #29            // java/lang/Throwable
  #26 = Utf8               SourceFile
  #27 = Utf8               A.java
  #28 = NameAndType        #9:#10         // "<init>":()V
  #29 = Utf8               java/lang/Throwable
  #30 = NameAndType        #38:#10        // printStackTrace:()V
  #31 = Class              #39            // java/lang/System
  #32 = NameAndType        #40:#41        // out:Ljava/io/PrintStream;
  #33 = Utf8               Hello World
  #34 = Class              #42            // java/io/PrintStream
  #35 = NameAndType        #43:#44        // println:(Ljava/lang/String;)V
  #36 = Utf8               A
  #37 = Utf8               java/lang/Object
  #38 = Utf8               printStackTrace
  #39 = Utf8               java/lang/System
  #40 = Utf8               out
  #41 = Utf8               Ljava/io/PrintStream;
  #42 = Utf8               java/io/PrintStream
  #43 = Utf8               println
  #44 = Utf8               (Ljava/lang/String;)V
{
  public A();
    descriptor: ()V
    flags: ACC_PUBLIC
    Code:
      stack=1, locals=1, args_size=1
         0: aload_0
         1: invokespecial #1                  // Method java/lang/Object."<init>":()V
         4: return
      LineNumberTable:
        line 1: 0
      LocalVariableTable:
        Start  Length  Slot  Name   Signature
            0       5     0  this   LA;

  public static void main(java.lang.String[]);
    descriptor: ([Ljava/lang/String;)V
    flags: ACC_PUBLIC, ACC_STATIC
    Code:
      stack=2, locals=2, args_size=1
         0: aload_0
         1: sipush        9999
         4: aaload
         5: astore_1
         6: goto          14
         9: astore_1
        10: aload_1
        11: invokevirtual #3                  // Method java/lang/Throwable.printStackTrace:()V
        14: getstatic     #4                  // Field java/lang/System.out:Ljava/io/PrintStream;
        17: ldc           #5                  // String Hello World
        19: invokevirtual #6                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
        22: return
      Exception table:
         from    to  target type
             0     6     9   Class java/lang/Throwable
      LineNumberTable:
        line 4: 0
        line 7: 6
        line 5: 9
        line 6: 10
        line 8: 14
        line 9: 22
      LocalVariableTable:
        Start  Length  Slot  Name   Signature
            6       0     1     a   Ljava/lang/String;
           10       4     1     t   Ljava/lang/Throwable;
            0      23     0  args   [Ljava/lang/String;
      StackMapTable: number_of_entries = 2
        frame_type = 73 /* same_locals_1_stack_item */
          stack = [ class java/lang/Throwable ]
        frame_type = 4 /* same */
}
SourceFile: "A.java"
</code>```

答:
I think you have a misconception of the notion of IdentityStmts. What different IdentityStmts have in common is that they assign values that "magically fall from the sky". At method entry those are parameters and "this", and in exception handlers those are the thrown exceptions. In other words, it's totally fine and expected to have an IdentityStmt with an exception reference inside a method's body at the place where the handler begins. The only assumption that Soot has is that if a statement is a target of a Trap, i.e., the start of the handler, then the first statement in that handler should be an IdentityStmt with an appropriate exception reference.

I hope this answers your question.

Body:
I'm trying to write a try-catch block in soot.

Let's decompile

public class A {
    public static void main(String[] args) {
        try{
            String a = args[9999];
        }catch(Throwable t){
            t.printStackTrace();
        }
        System.out.println("Hello World");
    }
}

I will add the full decompilation to the end of the question. The important parts are

     0: aload_0
     1: sipush        9999
     4: aaload
     5: astore_1
     6: goto          14
     9: astore_1
    10: aload_1
    11: invokevirtual #3                  // Method java/lang/Throwable.printStackTrace:()V
    14: getstatic     #4                  // Field java/lang/System.out:Ljava/io/PrintStream;
    17: ldc           #5                  // String Hello World
    19: invokevirtual #6                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
    22: return

and

  Exception table:
     from    to  target type
         0     6     9   Class java/lang/Throwable

So what this implies is that if any of the instructions 0-6 throw an exception, control will be re-routed to 9 and execution will continue as if normal, the astore_1 there being the storing of the reference to the exception object in a local variable.

However, I'm trying to generate a try-catch block in soot and I found one example that actually does something like this: CatchWrapInstrumenter.java

According to documentation, newTrap

Constructs a new JTrap for the given exception on the given Stmt range with the given Stmt handler.

So when we see

b.getTraps().add(Jimple.v().newTrap(thrwCls, sFirstNonId, sGotoLast, sCatch));

We can guess that this essentially is saying "if there's an exception of type thrwCls thrown in any of the stmts between sFirstNonId, sGotoLast, jump to the handler at sCatch.

So far, this matches expectations.

Now, what bothers me, is that

Stmt sCatch = Jimple.v().newIdentityStmt(lException1, Jimple.v().newCaughtExceptionRef());

is an identity stmt.

Because identity stmts

are statements which define locals to be pre-loaded (upon method entry)
  with special values such as parameters or the this value.

For example, l0 :=
  @this: A defines local l0 to be the this of the method.

This identification is necessary because the local variables are not numbered (normally the this variable is the variable in local variable slot 0 at the bytecode level.)

(page 31 [numbered 23] in the soot paper)

So -- taking again class A as an example -- if I were to generate (simplified)

Sting a;Throwable t;PrintStream out;

a = arg[9990]               //stmt1
goto stmt5                  //stmt2
t := thrownException;       //stmt3
t.printStackTrace();        //stmt4
out = System.out;           //stmt5
out.println("Hello World")  //stmt6

with the intention to register

newTrap(exception=java.lang.Throwable, beginStmt=stmt1,endStmt=stmt2,handlerStmt=stmt3)

, as I would have based on the decompiled A.class, this would actually be illegal because t := thrownException is supposed to be "pre-loaded (upon method entry)".

Yet at the same time, this is exactly what we are to do if the example on page 86 [numbered 78] of the soot paper is to be trusted.

This concept of "pre-loading" something that does not yet exists at the time it does, doesn't make terribly much sense to me and makes me think I could be wrong on the control flow, though I do not see how.

Could somebody please explain what is actually happening, here?

Full decompiled code of the small try-catch example:

public class A
  minor version: 0
  major version: 51
  flags: ACC_PUBLIC, ACC_SUPER
Constant pool:
   #1 = Methodref          #8.#28         // java/lang/Object."<init>":()V
   #2 = Class              #29            // java/lang/Throwable
   #3 = Methodref          #2.#30         // java/lang/Throwable.printStackTrace:()V
   #4 = Fieldref           #31.#32        // java/lang/System.out:Ljava/io/PrintStream;
   #5 = String             #33            // Hello World
   #6 = Methodref          #34.#35        // java/io/PrintStream.println:(Ljava/lang/String;)V
   #7 = Class              #36            // A
   #8 = Class              #37            // java/lang/Object
   #9 = Utf8               <init>
  #10 = Utf8               ()V
  #11 = Utf8               Code
  #12 = Utf8               LineNumberTable
  #13 = Utf8               LocalVariableTable
  #14 = Utf8               this
  #15 = Utf8               LA;
  #16 = Utf8               main
  #17 = Utf8               ([Ljava/lang/String;)V
  #18 = Utf8               a
  #19 = Utf8               Ljava/lang/String;
  #20 = Utf8               t
  #21 = Utf8               Ljava/lang/Throwable;
  #22 = Utf8               args
  #23 = Utf8               [Ljava/lang/String;
  #24 = Utf8               StackMapTable
  #25 = Class              #29            // java/lang/Throwable
  #26 = Utf8               SourceFile
  #27 = Utf8               A.java
  #28 = NameAndType        #9:#10         // "<init>":()V
  #29 = Utf8               java/lang/Throwable
  #30 = NameAndType        #38:#10        // printStackTrace:()V
  #31 = Class              #39            // java/lang/System
  #32 = NameAndType        #40:#41        // out:Ljava/io/PrintStream;
  #33 = Utf8               Hello World
  #34 = Class              #42            // java/io/PrintStream
  #35 = NameAndType        #43:#44        // println:(Ljava/lang/String;)V
  #36 = Utf8               A
  #37 = Utf8               java/lang/Object
  #38 = Utf8               printStackTrace
  #39 = Utf8               java/lang/System
  #40 = Utf8               out
  #41 = Utf8               Ljava/io/PrintStream;
  #42 = Utf8               java/io/PrintStream
  #43 = Utf8               println
  #44 = Utf8               (Ljava/lang/String;)V
{
  public A();
    descriptor: ()V
    flags: ACC_PUBLIC
    Code:
      stack=1, locals=1, args_size=1
         0: aload_0
         1: invokespecial #1                  // Method java/lang/Object."<init>":()V
         4: return
      LineNumberTable:
        line 1: 0
      LocalVariableTable:
        Start  Length  Slot  Name   Signature
            0       5     0  this   LA;

  public static void main(java.lang.String[]);
    descriptor: ([Ljava/lang/String;)V
    flags: ACC_PUBLIC, ACC_STATIC
    Code:
      stack=2, locals=2, args_size=1
         0: aload_0
         1: sipush        9999
         4: aaload
         5: astore_1
         6: goto          14
         9: astore_1
        10: aload_1
        11: invokevirtual #3                  // Method java/lang/Throwable.printStackTrace:()V
        14: getstatic     #4                  // Field java/lang/System.out:Ljava/io/PrintStream;
        17: ldc           #5                  // String Hello World
        19: invokevirtual #6                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
        22: return
      Exception table:
         from    to  target type
             0     6     9   Class java/lang/Throwable
      LineNumberTable:
        line 4: 0
        line 7: 6
        line 5: 9
        line 6: 10
        line 8: 14
        line 9: 22
      LocalVariableTable:
        Start  Length  Slot  Name   Signature
            6       0     1     a   Ljava/lang/String;
           10       4     1     t   Ljava/lang/Throwable;
            0      23     0  args   [Ljava/lang/String;
      StackMapTable: number_of_entries = 2
        frame_type = 73 /* same_locals_1_stack_item */
          stack = [ class java/lang/Throwable ]
        frame_type = 4 /* same */
}
SourceFile: "A.java"


来源: stackexchange

问:
module.js:491 throw err; ^ Error: Cannot find module 'mangoose'
I am new with MEAN.JS, I am getting this error while running my code. i did not find any errors, but i'm a beginner, so i do not know much, here is the code. I am also attaching the error here.

```<code>module.js:491
throw err;
^

Error: Cannot find module 'mangoose'
    at Function.Module._resolveFilename (module.js:489:15)
    at Function.Module._load (module.js:439:25)
    at Module.require (module.js:517:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous>
(/home/rajeev/Documents/practice/nodejs1/contactlist/app.js:2:14)
    at Module._compile (module.js:573:30)
    at Object.Module._extensions..js (module.js:584:10)
    at Module.load (module.js:507:32)
    at tryModuleLoad (module.js:470:12)
    at Function.Module._load (module.js:462:3)
</code>```

app.js

```<code>var express=require('express');
var mongoose=require('mongoose');
var bodyparser=require('body-parser');
var cors=require('cors');
var path=require('path');

var app=express();

//port no
const port=3000;

//testing sever
app.get('/',(req,res)=>{
    res.send('footbar');
});

app.listen(port,()=>{
    console.log('server started at port:'+port);
});
</code>```

package.json

```<code>  "name": "contactlist",
  "version": "1.0.0",
  "description": "a simple mean application",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "rajeev",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.18.2",
    "cors": "^2.8.4",
    "express": "^4.16.2",
    "mongoose": "^4.13.6"
  }
}
</code>```

答:
It should be mongoose

```<code>var express=require('express');
var mangoose=require('mongoose');
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am new with MEAN.JS, I am getting this error while running my code. i did not find any errors, but i'm a beginner, so i do not know much, here is the code. I am also attaching the error here.

module.js:491
throw err;
^

Error: Cannot find module 'mangoose'
    at Function.Module._resolveFilename (module.js:489:15)
    at Function.Module._load (module.js:439:25)
    at Module.require (module.js:517:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous>
(/home/rajeev/Documents/practice/nodejs1/contactlist/app.js:2:14)
    at Module._compile (module.js:573:30)
    at Object.Module._extensions..js (module.js:584:10)
    at Module.load (module.js:507:32)
    at tryModuleLoad (module.js:470:12)
    at Function.Module._load (module.js:462:3)

app.js

var express=require('express');
var mongoose=require('mongoose');
var bodyparser=require('body-parser');
var cors=require('cors');
var path=require('path');

var app=express();

//port no
const port=3000;

//testing sever
app.get('/',(req,res)=>{
    res.send('footbar');
});

app.listen(port,()=>{
    console.log('server started at port:'+port);
});

package.json

  "name": "contactlist",
  "version": "1.0.0",
  "description": "a simple mean application",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "rajeev",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.18.2",
    "cors": "^2.8.4",
    "express": "^4.16.2",
    "mongoose": "^4.13.6"
  }
}

Body:
It should be mongoose

var express=require('express');
var mangoose=require('mongoose');


问:
Python calendar alignment
When I run the code, the calendar day numbers do not align up with the week day they go with. I have tried justify = LEFT and RIGHT and CENTRE. None of these solve my problem even when not having the justify statement it doesn't work</p>

```<code>from tkinter import *
import calendar as cl
import datetime as datet

year = int(datet.date.today().strftime("%Y")) #year
month =  int(datet.date.today().strftime("%m")) #month number

root = Tk()
root.geometry("300x300")

app = Frame(root)
app.grid()

cal = Label(app, text = cl.month(year, month), justify = RIGHT)
cal.grid(row = 0, column = 0)

root.mainloop()
</code>```

答:
Tkinter is using a non-monospace font by default for Label. calendar.month(year, month) is one long string, which if you print in your console will come out as you intend. Change your code to be like so:

```<code>import calendar
import datetime
from tkinter import *

year = int(datetime.date.today().strftime("%Y"))  # year
month = int(datetime.date.today().strftime("%m"))  # month number

root = Tk()
root.geometry("300x300")

app = Frame(root)
app.grid()

cal = Label(app, text=calendar.month(year, month), font=('Consolas', 12))
cal.grid(row=0, column=0)

root.mainloop()
</code>```

Consolas is a monospace font, there are other options aswell.

Note that if you instead broke up each part of the calendar into its own widget you wouldn't have to change the font to get them to align as you'd like.

Title: Python calendar alignment

Body:
When I run the code, the calendar day numbers do not align up with the week day they go with. I have tried justify = LEFT and RIGHT and CENTRE. None of these solve my problem even when not having the justify statement it doesn't work

from tkinter import *
import calendar as cl
import datetime as datet

year = int(datet.date.today().strftime("%Y")) #year
month =  int(datet.date.today().strftime("%m")) #month number

root = Tk()
root.geometry("300x300")

app = Frame(root)
app.grid()

cal = Label(app, text = cl.month(year, month), justify = RIGHT)
cal.grid(row = 0, column = 0)

root.mainloop()

Body:
Tkinter is using a non-monospace font by default for Label. calendar.month(year, month) is one long string, which if you print in your console will come out as you intend. Change your code to be like so:

import calendar
import datetime
from tkinter import *

year = int(datetime.date.today().strftime("%Y"))  # year
month = int(datetime.date.today().strftime("%m"))  # month number

root = Tk()
root.geometry("300x300")

app = Frame(root)
app.grid()

cal = Label(app, text=calendar.month(year, month), font=('Consolas', 12))
cal.grid(row=0, column=0)

root.mainloop()

Consolas is a monospace font, there are other options aswell.

Note that if you instead broke up each part of the calendar into its own widget you wouldn't have to change the font to get them to align as you'd like.


问:
Why _ (underscore) of type Unit and () treated differently?
I have a method which returns Future[Unit], so when I call whenReady

These two options work: whenReady(doItAsync())(_ => {}) and whenReady(doItAsync()) { _ => }

but this doesn't: whenReady(doItAsync())(() => {})

Are not _ of type Unit and empty params list equivalent in this case?

答:
Are not _ of type Unit and empty params list equivalent in this case?

No. _ => {} defines a function with single parameter (which happens in this context to have type Unit), () => {} defines a function with no parameters. Their types are Unit => Unit and () => Unit, or without syntactic sugar Function1[Unit, Unit] and Function0[Unit]. These types aren't actually related: neither of them is a subtype of the other.

You can write a single-argument anonymous function taking Unit with () using pattern-matching: { case () => ... }. But there is no point to doing that.


问:
While validating against XSD, find the exact missing element in the XML using any of DOM, StAX, SAX parsers
I have a XML file and its corresponding XSD file. While validating using StAX parser, I've attached an error handler. Basically, I encounter two types of errors in a well-formed XML file.

1) Incorrect type of data inside an element, for e.g string inside an element that is supposed to have an integer.

2) Missing element: An element that must be present according to XSD is not present in the XML.

Using a StAX parser and custom error handler, I'm able to rectify the first type of error. But for the second type, a CHARACTER event is triggered and the value of the TEXT is the value of immediate next element. I don't know how to figure out the missing element. Also, why the CHARACTER event is triggered and the missing element is completely ignored?

As the StAX parser is forward only, is there a way to rectify both of the errors using other parsers?

```<code>import java.io.File;
import java.io.IOException;
import javax.xml.XMLConstants;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.stax.StAXSource;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.*;
import javax.xml.validation.Validator;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class XMLValidation {

    public static void main(String[] args) {

        XMLValidation xmlValidation = new XMLValidation();
        System.out.println(xmlValidation.validateXMLSchema("PHSHumanSubjectsAndClinicalTrialsInfo-V1.0.xsd", "FullPHSHuman.xml"));
    }

    public boolean validateXMLSchema(String xsdPath, String xmlPath){

        try {
            SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = factory.newSchema(new File(xsdPath));
            StreamSource XML = new StreamSource(xmlPath);
            XMLStreamReader reader = XMLInputFactory.newFactory().createXMLStreamReader(XML);
            Validator validator = schema.newValidator();
            validator.setErrorHandler(new MyErrorHandler(reader));
            validator.validate(new StAXSource(reader));
        } catch (IOException | SAXException | XMLStreamException e) {
            System.out.println("Exception: "+e.getMessage() + " local message " + e.getLocalizedMessage() + " cause " + e.getCause());
            return false;
        }
        return true;
    }
}

class MyErrorHandler implements ErrorHandler {

    private XMLStreamReader reader;

    public MyErrorHandler(XMLStreamReader reader) {
        this.reader = reader;
    }

    @Override
    public void error(SAXParseException e) throws SAXException {
        System.out.println("error");
        warning(e);
    }

    @Override
    public void fatalError(SAXParseException e) throws SAXException {
        System.out.println("fatal error");
        warning(e);
    }

    @Override
    public void warning(SAXParseException e) throws SAXException {
        if(reader.getEventType() == 1 || reader.getEventType() == 2) {
            //The first type of error is detected here.
            System.out.println(reader.getLocalName());
            System.out.println(reader.getNamespaceURI());

        }

        if(reader.getEventType() == XMLStreamConstants.CHARACTERS) {
            int start = reader. getTextStart();
            int length = reader.getTextLength();
            System.out.println(new String(reader.getTextCharacters(), start, length));
        }
    }
}
</code>```

Below is the snippet of the well-formed XML file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<PHSHumanSubjectsAndClinicalTrialsInfo:PHSHumanSubjectsAndClinicalTrialsInfo xmlns:PHSHumanSubjectsAndClinicalTrialsInfo="http://apply.grants.gov/forms/PHSHumanSubjectsAndClinicalTrialsInfo-V1.0" PHSHumanSubjectsAndClinicalTrialsInfo:FormVersion="1.0"
>
<!--    <PHSHumanSubjectsAndClinicalTrialsInfo:HumanSubjectsIndicator
    >Y: </PHSHumanSubjectsAndClinicalTrialsInfo:HumanSubjectsIndicator
    >-->
    <PHSHumanSubjectsAndClinicalTrialsInfo:HumanSubjectsIndicator1
    >Y: Yes</PHSHumanSubjectsAndClinicalTrialsInfo:HumanSubjectsIndicator1
    >
    <PHSHumanSubjectsAndClinicalTrialsInfo:HumanSubjectsIndicator2
    >Y: Yes</PHSHumanSubjectsAndClinicalTrialsInfo:HumanSubjectsIndicator2
    >
</code>```

Here the HumanSubjectsIndicator element is commented to provoke the second scenario. In this case a CHARACTER event is triggered in the 'MyErrorHandler'. The value 'Y:Yes' is obtained reader.getTextCharacters(). This value corresponds to the HumanSubjectsIndicator1 element (found this using the getLocation() method).

Is there a way to get exactly the Local Name of the missing element. If not using StAX, then using other parsers?

Thanks.

答:
The Saxon XSD validator gives you a message like this when a required element is missing:

```<code>Validation error on line 12 column 17 of books.xml:
  FORG0001: In content of element <ITEM>: The content model does not allow element <PRICE>
  to appear immediately after element <PUB-DATE>. It must be preceded by <LANGUAGE>.
  See http://www.w3.org/TR/xmlschema-1/#cvc-complex-type clause 2.4
</code>```

You could try pattern-matching the error message and extracting the name of the missing element.

The reason most schema processors don't give you this information is because of the way they work internally. Typically the schema processor constructs a finite state machine which indicates, for each element in the input, which elements are allowed to come next. If the next element isn't one of those permitted, it's not immediately obvious from the FSM why this is this case. Saxon does some extra analysis to try and improve the diagnostics: if the input contains a disallowed transition from A to C, then it searches the FSM to discover that there are permitted transitions from A to B and from B to C, and constructs an error message to say that B was missing.

Body:
I have a XML file and its corresponding XSD file. While validating using StAX parser, I've attached an error handler. Basically, I encounter two types of errors in a well-formed XML file.

1) Incorrect type of data inside an element, for e.g string inside an element that is supposed to have an integer.

2) Missing element: An element that must be present according to XSD is not present in the XML.

Using a StAX parser and custom error handler, I'm able to rectify the first type of error. But for the second type, a CHARACTER event is triggered and the value of the TEXT is the value of immediate next element. I don't know how to figure out the missing element. Also, why the CHARACTER event is triggered and the missing element is completely ignored?

As the StAX parser is forward only, is there a way to rectify both of the errors using other parsers?

import java.io.File;
import java.io.IOException;
import javax.xml.XMLConstants;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.stax.StAXSource;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.*;
import javax.xml.validation.Validator;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class XMLValidation {

    public static void main(String[] args) {

        XMLValidation xmlValidation = new XMLValidation();
        System.out.println(xmlValidation.validateXMLSchema("PHSHumanSubjectsAndClinicalTrialsInfo-V1.0.xsd", "FullPHSHuman.xml"));
    }

    public boolean validateXMLSchema(String xsdPath, String xmlPath){

        try {
            SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = factory.newSchema(new File(xsdPath));
            StreamSource XML = new StreamSource(xmlPath);
            XMLStreamReader reader = XMLInputFactory.newFactory().createXMLStreamReader(XML);
            Validator validator = schema.newValidator();
            validator.setErrorHandler(new MyErrorHandler(reader));
            validator.validate(new StAXSource(reader));
        } catch (IOException | SAXException | XMLStreamException e) {
            System.out.println("Exception: "+e.getMessage() + " local message " + e.getLocalizedMessage() + " cause " + e.getCause());
            return false;
        }
        return true;
    }
}

class MyErrorHandler implements ErrorHandler {

    private XMLStreamReader reader;

    public MyErrorHandler(XMLStreamReader reader) {
        this.reader = reader;
    }

    @Override
    public void error(SAXParseException e) throws SAXException {
        System.out.println("error");
        warning(e);
    }

    @Override
    public void fatalError(SAXParseException e) throws SAXException {
        System.out.println("fatal error");
        warning(e);
    }

    @Override
    public void warning(SAXParseException e) throws SAXException {
        if(reader.getEventType() == 1 || reader.getEventType() == 2) {
            //The first type of error is detected here.
            System.out.println(reader.getLocalName());
            System.out.println(reader.getNamespaceURI());

        }

        if(reader.getEventType() == XMLStreamConstants.CHARACTERS) {
            int start = reader. getTextStart();
            int length = reader.getTextLength();
            System.out.println(new String(reader.getTextCharacters(), start, length));
        }
    }
}

Below is the snippet of the well-formed XML file:

<?xml version="1.0" encoding="UTF-8"?>
<PHSHumanSubjectsAndClinicalTrialsInfo:PHSHumanSubjectsAndClinicalTrialsInfo xmlns:PHSHumanSubjectsAndClinicalTrialsInfo="http://apply.grants.gov/forms/PHSHumanSubjectsAndClinicalTrialsInfo-V1.0" PHSHumanSubjectsAndClinicalTrialsInfo:FormVersion="1.0"
>

    <PHSHumanSubjectsAndClinicalTrialsInfo:HumanSubjectsIndicator1
    >Y: Yes</PHSHumanSubjectsAndClinicalTrialsInfo:HumanSubjectsIndicator1
    >
    <PHSHumanSubjectsAndClinicalTrialsInfo:HumanSubjectsIndicator2
    >Y: Yes</PHSHumanSubjectsAndClinicalTrialsInfo:HumanSubjectsIndicator2
    >

Here the HumanSubjectsIndicator element is commented to provoke the second scenario. In this case a CHARACTER event is triggered in the 'MyErrorHandler'. The value 'Y:Yes' is obtained reader.getTextCharacters(). This value corresponds to the HumanSubjectsIndicator1 element (found this using the getLocation() method).

Is there a way to get exactly the Local Name of the missing element. If not using StAX, then using other parsers?

Thanks.

Body:
The Saxon XSD validator gives you a message like this when a required element is missing:

Validation error on line 12 column 17 of books.xml:
  FORG0001: In content of element <ITEM>: The content model does not allow element <PRICE>
  to appear immediately after element <PUB-DATE>. It must be preceded by <LANGUAGE>.
  See http://www.w3.org/TR/xmlschema-1/#cvc-complex-type clause 2.4

You could try pattern-matching the error message and extracting the name of the missing element.

The reason most schema processors don't give you this information is because of the way they work internally. Typically the schema processor constructs a finite state machine which indicates, for each element in the input, which elements are allowed to come next. If the next element isn't one of those permitted, it's not immediately obvious from the FSM why this is this case. Saxon does some extra analysis to try and improve the diagnostics: if the input contains a disallowed transition from A to C, then it searches the FSM to discover that there are permitted transitions from A to B and from B to C, and constructs an error message to say that B was missing.


问:
Python - Extracting and Saving Video Frames
So I've followed this tutorial but it doesn't seem to do anything. Simply nothing. It waits a few seconds and closes the program. What is wrong with this code?

```<code>import cv2
vidcap = cv2.VideoCapture('Compton.mp4')
success,image = vidcap.read()
count = 0
success = True
while success:
  success,image = vidcap.read()
  cv2.imwrite("frame%d.jpg" % count, image)     # save frame as JPEG file
  if cv2.waitKey(10) == 27:                     # exit if Escape is hit
      break
  count += 1
</code>```

Also, in the comments it says that this limits the frames to 1000? Why?

EDIT:
I tried doing success = True first but that didn't help. It only created one image that was 0 bytes.

答:
To extend on this question (& answer by @user2700065) for a slightly different cases, if anyone does not want to extract every frame but wants to extract frame every one second. So a 1-minute video will give 60 frames(images).</p>

```<code>import sys
import argparse

import cv2
print(cv2.__version__)

def extractImages(pathIn, pathOut):
    count = 0
    vidcap = cv2.VideoCapture(pathIn)
    success,image = vidcap.read()
    success = True
    while success:
        vidcap.set(cv2.CAP_PROP_POS_MSEC,(count*1000))    # added this line
        success,image = vidcap.read()
        print ('Read a new frame: ', success)
        cv2.imwrite( pathOut + "\\frame%d.jpg" % count, image)     # save frame as JPEG file
        count = count + 1

if __name__=="__main__":
    a = argparse.ArgumentParser()
    a.add_argument("--pathIn", help="path to video")
    a.add_argument("--pathOut", help="path to images")
    args = a.parse_args()
    print(args)
    extractImages(args.pathIn, args.pathOut)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
So I've followed this tutorial but it doesn't seem to do anything. Simply nothing. It waits a few seconds and closes the program. What is wrong with this code?

import cv2
vidcap = cv2.VideoCapture('Compton.mp4')
success,image = vidcap.read()
count = 0
success = True
while success:
  success,image = vidcap.read()
  cv2.imwrite("frame%d.jpg" % count, image)     # save frame as JPEG file
  if cv2.waitKey(10) == 27:                     # exit if Escape is hit
      break
  count += 1

Also, in the comments it says that this limits the frames to 1000? Why?

EDIT:
I tried doing success = True first but that didn't help. It only created one image that was 0 bytes.

Body:
To extend on this question (& answer by @user2700065) for a slightly different cases, if anyone does not want to extract every frame but wants to extract frame every one second. So a 1-minute video will give 60 frames(images).

import sys
import argparse

import cv2
print(cv2.__version__)

def extractImages(pathIn, pathOut):
    count = 0
    vidcap = cv2.VideoCapture(pathIn)
    success,image = vidcap.read()
    success = True
    while success:
        vidcap.set(cv2.CAP_PROP_POS_MSEC,(count*1000))    # added this line
        success,image = vidcap.read()
        print ('Read a new frame: ', success)
        cv2.imwrite( pathOut + "\\frame%d.jpg" % count, image)     # save frame as JPEG file
        count = count + 1

if __name__=="__main__":
    a = argparse.ArgumentParser()
    a.add_argument("--pathIn", help="path to video")
    a.add_argument("--pathOut", help="path to images")
    args = a.parse_args()
    print(args)
    extractImages(args.pathIn, args.pathOut)


问:
Character conversion - fromCharCode problems
I have a Javascript UI talking to an endpoint. The endpoint returns a passphrase challenge as an array of JSON objects. Each object had character index in the passphrase and the character code point value.

```<code>[{"index":3,"nValue":101},{"index":5,"nValue":114},{"index":6}]
</code>```

I'm struggling to convert the code points back to letters. I'm getting RangeError exception. I'm not sure why I can't parse the value to number and pass it to the fromCharCode method.

```<code>for(var i = 0;i<result.length;i++){
    console.log(typeof result[i].nValue);               //prints string
    console.log('returnVal=*'+result[i].nValue+'*');    //prints *e*
    var intChar = parseInt(result[i].nValue);
    console.log(typeof intChar);                        //prints number
    console.log('intChar=*'+intChar+'*');               //prints *NaN*
    console.log('converted='+String.fromCharCode(result[i].nValue));  //empty string
    console.log('converted='+String.fromCodePoint(result[i].nValue));  //trows range exception
}
</code>```

答: {"index":6} has no nValue thus returning undefined

Body:
I have a Javascript UI talking to an endpoint. The endpoint returns a passphrase challenge as an array of JSON objects. Each object had character index in the passphrase and the character code point value.

[{"index":3,"nValue":101},{"index":5,"nValue":114},{"index":6}]

I'm struggling to convert the code points back to letters. I'm getting RangeError exception. I'm not sure why I can't parse the value to number and pass it to the fromCharCode method.

for(var i = 0;i<result.length;i++){
    console.log(typeof result[i].nValue);               //prints string
    console.log('returnVal=*'+result[i].nValue+'*');    //prints *e*
    var intChar = parseInt(result[i].nValue);
    console.log(typeof intChar);                        //prints number
    console.log('intChar=*'+intChar+'*');               //prints *NaN*
    console.log('converted='+String.fromCharCode(result[i].nValue));  //empty string
    console.log('converted='+String.fromCodePoint(result[i].nValue));  //trows range exception
}


问:
Parsing a JSON to meet minimum requirements inside a stored procedure
I have been looking at what I believe to every single page on SQL Server and half stackoverflow, and I can't find a proper solution to this

Our challenge, is to deal with an exiting application that send/receive JSON form SQL Server. So we have to build a STRONG JSON architecture on SQL Server.

We need to validate the format of the JSON (legacy system has its own standard) so messages are in exact expected format.

The thing is, JSON functions are not so advance as XML, and seems there is no way to validate a schema in SQL Server.

We tried with sp_prepare and sp_execute, but that does not seem to work.

We tested something like this:

```<code>Declare @ptSQL1 int;
Exec sp_prepare @ptSQL1 output,
    N'@P1 nvarchar(128), @json NVARCHAR(1000) ',
    N'  SELECT *
            INTO  temp_tblPersons
            FROM OPENJSON (@json, ''$.root'')
            WITH (
                Cname NVARCHAR(100) ''strict$.FirstName'',
                Csurname NVARCHAR(100) ''lax$.surname''
            ) as J
            where Csurname like @P1';

DECLARE @json7 NVARCHAR(1000)
SET @json7 = N'{
    "root": [
        { "FirstName": "Charles" , "surname":"perez" },
        { "FirstName": "Jade" , "surname":"pelaz"  },
        { "FirstName": "Jim" , "surname":"alvarez" },
        { "FirstName": "Luke" , "surname":"alonso" },
        { "FirstName": "Ken"}
    ]
}'

IF (@ptSQL1 = 0) PRINT 'THE SUPPLY JSON IS NOT VALID'
ELSE Exec sp_execute @ptSQL1, N'a%', @json7;
</code>```

but does not meet the sp_prepare/execute behavior.

Our intention it to validate a minimum schema before proceed to process the data, and if the schema doesn't meet the standard, return an ERROR.

How can this be accomplished?

(not sure where we read the @ptSQL1 = 0, but I believe to read somewhere)

答:
Our intention it to validate a minimum schema before proceed to
  process the data, and if the schema doesn't meet the standard, return
  an ERROR.

The JSON must be parsed in order to validate the schema. A prepare doesn't actually execute the query in order to parse the JSON document, plus sp_prepare and sp_execute are internal API system stored procedures not intended to be called directly in T-SQL.

Although one can't currently validate JSON schema in T-SQL (without writing a custom SQLCLR assembly), you could just use TRY/CATCH and handle errors. The example below handles JSON errors differently but I would personally just THROW all errors and handle specific ones in the app code.

```<code>DECLARE @json NVARCHAR(1000);
DECLARE @P1 NVARCHAR(128) = 'a%';

SET @json = N'{
    "root": [
        { "FirstName": "Charles" , "surname":"perez" },
        { "FirstName": "Jade" , "surname":"pelaz"  },
        { "FirstName": "Jim" , "surname":"alvarez" },
        { "FirstName": "Luke" , "surname":"alonso" },
        { "FirstName": "Ken"}
    ]
}';

BEGIN TRY
    SELECT *
                INTO  temp_tblPersons
                FROM OPENJSON (@json, '$.root')
                WITH (
                    Cname NVARCHAR(100) 'strict$.FirstName',
                    Csurname NVARCHAR(100) 'lax$.surname'
                ) as J
                where Csurname like @P1;
END TRY
BEGIN CATCH
    DROP TABLE IF EXISTS temp_tblPersons;
    IF ERROR_MESSAGE() LIKE N'%JSON%'
    BEGIN
        PRINT 'THE SUPPLY JSON IS NOT VALID';
    END
    ELSE
    BEGIN
        THROW;
    END;
END CATCH;
</code>```

Body:
I have been looking at what I believe to every single page on SQL Server and half stackoverflow, and I can't find a proper solution to this

Our challenge, is to deal with an exiting application that send/receive JSON form SQL Server. So we have to build a STRONG JSON architecture on SQL Server.

We need to validate the format of the JSON (legacy system has its own standard) so messages are in exact expected format.

The thing is, JSON functions are not so advance as XML, and seems there is no way to validate a schema in SQL Server.

We tried with sp_prepare and sp_execute, but that does not seem to work.

We tested something like this:

Declare @ptSQL1 int;
Exec sp_prepare @ptSQL1 output,
    N'@P1 nvarchar(128), @json NVARCHAR(1000) ',
    N'  SELECT *
            INTO  temp_tblPersons
            FROM OPENJSON (@json, ''$.root'')
            WITH (
                Cname NVARCHAR(100) ''strict$.FirstName'',
                Csurname NVARCHAR(100) ''lax$.surname''
            ) as J
            where Csurname like @P1';

DECLARE @json7 NVARCHAR(1000)
SET @json7 = N'{
    "root": [
        { "FirstName": "Charles" , "surname":"perez" },
        { "FirstName": "Jade" , "surname":"pelaz"  },
        { "FirstName": "Jim" , "surname":"alvarez" },
        { "FirstName": "Luke" , "surname":"alonso" },
        { "FirstName": "Ken"}
    ]
}'

IF (@ptSQL1 = 0) PRINT 'THE SUPPLY JSON IS NOT VALID'
ELSE Exec sp_execute @ptSQL1, N'a%', @json7;

but does not meet the sp_prepare/execute behavior.

Our intention it to validate a minimum schema before proceed to process the data, and if the schema doesn't meet the standard, return an ERROR.

How can this be accomplished?

(not sure where we read the @ptSQL1 = 0, but I believe to read somewhere)

Body:
Our intention it to validate a minimum schema before proceed to
  process the data, and if the schema doesn't meet the standard, return
  an ERROR.

The JSON must be parsed in order to validate the schema. A prepare doesn't actually execute the query in order to parse the JSON document, plus sp_prepare and sp_execute are internal API system stored procedures not intended to be called directly in T-SQL.

Although one can't currently validate JSON schema in T-SQL (without writing a custom SQLCLR assembly), you could just use TRY/CATCH and handle errors. The example below handles JSON errors differently but I would personally just THROW all errors and handle specific ones in the app code.

DECLARE @json NVARCHAR(1000);
DECLARE @P1 NVARCHAR(128) = 'a%';

SET @json = N'{
    "root": [
        { "FirstName": "Charles" , "surname":"perez" },
        { "FirstName": "Jade" , "surname":"pelaz"  },
        { "FirstName": "Jim" , "surname":"alvarez" },
        { "FirstName": "Luke" , "surname":"alonso" },
        { "FirstName": "Ken"}
    ]
}';

BEGIN TRY
    SELECT *
                INTO  temp_tblPersons
                FROM OPENJSON (@json, '$.root')
                WITH (
                    Cname NVARCHAR(100) 'strict$.FirstName',
                    Csurname NVARCHAR(100) 'lax$.surname'
                ) as J
                where Csurname like @P1;
END TRY
BEGIN CATCH
    DROP TABLE IF EXISTS temp_tblPersons;
    IF ERROR_MESSAGE() LIKE N'%JSON%'
    BEGIN
        PRINT 'THE SUPPLY JSON IS NOT VALID';
    END
    ELSE
    BEGIN
        THROW;
    END;
END CATCH;


问:
How to purge unused source/class files from Directory tree
We have about 280 Java source code spread over 10 packages, and a bunch of txt and image files for a software project. Quite a few of them are not being used currently. They do not break the system, since we can just do a "javac //*.java" and "jar cmf metafile " to build up the executable jar which works. The question:

How do we find the class files never accessed, or image/txt files never used as resources in the jar?

答:
It would be very hard to determine which image/txt files are never used, as they can be loaded in a variety of manners.  A good bet for the image/txt files is to search for the name of each file in your code; if it is not there, it might not be being used; remember, the name of the file could be being generated programmatically and then loaded.

I recently had to do something similar for a game project.  Because content could be brought in via a variety of means, removing unused content took a lot of trial and error.

There are plugins for eclipse that can find unused code.

ContentLicense: CC BY-SA 2.5


问:
Intellij IDEA can not resolve symbol with Play framework
I am using IDEA 13 with Play 2.2.1 and was doing the examples on the play site.

```<code>public static Result index() {
   return redirect(routes.Application.tasks());
}
</code>```

IDEA says "cannot resolve method redirect(?)" and red underlines routes.Application.tasks()

I have done "compile" and then "idea" from the play console.

答:
I had a similar problem - IDEA could not resolve Play! framework dependencies.

In my case there was a problem with .idea folder. I copied project to separate folder and run "activator idea" command in the copied project root folder. Then I compared .idea folders in original project and copied project - there I found a difference! In copied project in folder .idea/libraries there were lots of XML files containing links to dependencies, so I copied them to the same folder to original project, re-indexed project and everything works perfect from that moment :) I did it like this because I didnt want to loose my project settings (deleting .idea folder and run command "activator idea" in original project folder should resolve the problem, but settings for project would be lost).

Hope this helps somehow :).

Body:
I am using IDEA 13 with Play 2.2.1 and was doing the examples on the play site.

public static Result index() {
   return redirect(routes.Application.tasks());
}

IDEA says "cannot resolve method redirect(?)" and red underlines routes.Application.tasks()

I have done "compile" and then "idea" from the play console.


问:
How do I initialise the size of my struct array, depending on the user input in C?
I've created a struct and now I want to initialise an array of those structs, which size would depend on the user's input;

```<code>struct StarsStruct
{
    int SerialNumber = 1;
    char StarName[6] = "Peter";
    double x = 0;
    double y = 0;
};
int NumberOfStars = 0;
if (strcmp(CurrentCommand, "bang") == 0)
    {
        Clear();

        printf("Enter the number of stars to be created: ");
        scanf("%d", &NumberOfStars);

        StarsStruct Stars[NumberOfStars];
    }
</code>```

However, on the last line of code, I'm greeted with an error; "Expression must have a constant value". So am I not able to just get a value from my scanf and use it to initialise the struct array?

答:
Your code has some problems that prevent it from actually being C, the two main ones are:

Attempted initializers inside the struct declaration, that makes no sense (when would those occur, and who would do them?)

Lacking struct when trying to uses the type for the array.

It's also C99, but that's fine of course.

This modified but similar program works:

```<code>struct StarsStruct
{
    int SerialNumber;
    char StarName[6];
    double x;
    double y;
};

int main(void)
{
    int NumberOfStars = 0;
    if (scanf("%d", &NumberOfStars) == 1)
    {
        struct StarsStruct Stars[NumberOfStars];
        printf("size is %zu bytes\n", sizeof Stars);
    }
    return 0;
}
</code>```

If you enter e.g. 14, it prints 448, which implies that each structure is 32 bytes. This makes sense due to padding.

Body:
I've created a struct and now I want to initialise an array of those structs, which size would depend on the user's input;

struct StarsStruct
{
    int SerialNumber = 1;
    char StarName[6] = "Peter";
    double x = 0;
    double y = 0;
};
int NumberOfStars = 0;
if (strcmp(CurrentCommand, "bang") == 0)
    {
        Clear();

        printf("Enter the number of stars to be created: ");
        scanf("%d", &NumberOfStars);

        StarsStruct Stars[NumberOfStars];
    }

However, on the last line of code, I'm greeted with an error; "Expression must have a constant value". So am I not able to just get a value from my scanf and use it to initialise the struct array?

Body:
Your code has some problems that prevent it from actually being C, the two main ones are:

Attempted initializers inside the struct declaration, that makes no sense (when would those occur, and who would do them?)

Lacking struct when trying to uses the type for the array.

It's also C99, but that's fine of course.

This modified but similar program works:

struct StarsStruct
{
    int SerialNumber;
    char StarName[6];
    double x;
    double y;
};

int main(void)
{
    int NumberOfStars = 0;
    if (scanf("%d", &NumberOfStars) == 1)
    {
        struct StarsStruct Stars[NumberOfStars];
        printf("size is %zu bytes\n", sizeof Stars);
    }
    return 0;
}

If you enter e.g. 14, it prints 448, which implies that each structure is 32 bytes. This makes sense due to padding.


问:
Multiple Where Linq Query
I am using linq c# to get the services ids selected by user OrderId

Since the user can have multiple OrderId I need to get the services of each id.

For this I am using foreach loop and getting the ServiceId from the database. This is taking long time to check for every OrderId, and ServiceId can be in list form.

Is there any method to get the result by calling database one time only?

Further the OrderId must be distinguishable for example how many services on each id.

Code

```<code>foreach (var ord in orderInfoDetailList)
{
    // this taking very long time if there are too many orderids
    long orderid = ord.orderObj.OrderID;
    var services = (from i in db.OrderServiceTBs
                    where i.OrderID == orderid
                    select i.ServiceID).ToList();
}
</code>```

答:
It's like you are trying to find all instances of dropdown id's which present in any of the orderInfoDetailList values. If so try the following</p>

```<code>var services =  db.OrderServiceTBs.Where(i=>orderInfoDetailList.Any(x=>x.orderObj.OrderID == i.OrderID)).Select(x=> x.ServiceID).ToList();
</code>```

Title: Multiple Where Linq Query

Body:
I am using linq c# to get the services ids selected by user OrderId

Since the user can have multiple OrderId I need to get the services of each id.

For this I am using foreach loop and getting the ServiceId from the database. This is taking long time to check for every OrderId, and ServiceId can be in list form.

Is there any method to get the result by calling database one time only?

Further the OrderId must be distinguishable for example how many services on each id.

Code

foreach (var ord in orderInfoDetailList)
{
    // this taking very long time if there are too many orderids
    long orderid = ord.orderObj.OrderID;
    var services = (from i in db.OrderServiceTBs
                    where i.OrderID == orderid
                    select i.ServiceID).ToList();
}

Body:
It's like you are trying to find all instances of dropdown id's which present in any of the orderInfoDetailList values. If so try the following

var services =  db.OrderServiceTBs.Where(i=>orderInfoDetailList.Any(x=>x.orderObj.OrderID == i.OrderID)).Select(x=> x.ServiceID).ToList();


问:
Javascript breakpoints in Visual Studio 2017
I just installed Visual Studio 2017. After starting an ASP.NET MVC application I get the message that chrome debugging in Visual Studio is enabled.

But my breakpoints in Visual Studio won't hit. The breakpoints on Razor code seems to be working but Javascript does not. The breakpoints are not fully red like they should be. A restart, rebuild don't seem to take any effect.

I have the following code example

```<code>@Html.Partial("_Test", Model.Test) // debugging works here

<script>
    var i = 1;
    console.log(i); // debugging does not work here or above
</script>

@section scripts {
    <script>
        var a = 11;
        console.log(a); // debugging does not work here or above
    </script>
}
</code>```

I don't have the chrome debugging console open and I checked the option in Visual Studio ('Enable Javascript debugging..') which is enabled.

According to this blog post I thought this should work:
https://blogs.msdn.microsoft.com/webdev/2016/11/21/client-side-debugging-of-asp-net-projects-in-google-chrome/

Am I missing something here? Could it be that this is not working in Visual Studio 2017 somehow?

I only have one extension and that is Resharper, but I guess this is not an issue.

答:
I had the same issue, new to .net core, a solution that worked for me was to add debugger; at the top of the script:</p>

```<code><script>
  debugger;

  -- rest of your jscript here
</script>
</code>```

Body:
I just installed Visual Studio 2017. After starting an ASP.NET MVC application I get the message that chrome debugging in Visual Studio is enabled.

But my breakpoints in Visual Studio won't hit. The breakpoints on Razor code seems to be working but Javascript does not. The breakpoints are not fully red like they should be. A restart, rebuild don't seem to take any effect.

I have the following code example

@Html.Partial("_Test", Model.Test) // debugging works here

@section scripts {

}

I don't have the chrome debugging console open and I checked the option in Visual Studio ('Enable Javascript debugging..') which is enabled.

According to this blog post I thought this should work:
https://blogs.msdn.microsoft.com/webdev/2016/11/21/client-side-debugging-of-asp-net-projects-in-google-chrome/

Am I missing something here? Could it be that this is not working in Visual Studio 2017 somehow?

I only have one extension and that is Resharper, but I guess this is not an issue.

Body:
I had the same issue, new to .net core, a solution that worked for me was to add debugger; at the top of the script:

<script>
  debugger;

  -- rest of your jscript here
</script>


问:
SQL - Select top n grouped by multiple fields, ordered by count
I am attempting to find the top n records when grouped by multiple attributes. I believe it is related to this problem, but I am having difficulty adapting the solution described  to my situation.

To simplify, I have a table with columns (did is short for device_id):

```<code>id int
did int
dateVal dateTime
</code>```

I am trying to find the top n device_id's for each day with the most rows.

For example (ignoring id and the time part of dateTime),

```<code>did dateVal
1   2017-01-01
1   2017-01-01
1   2017-01-01
2   2017-01-01
3   2017-01-01
3   2017-01-01

1   2017-01-02
1   2017-01-02
2   2017-01-02
2   2017-01-02
2   2017-01-02
3   2017-01-02
</code>```

Finding the top 2 would yield...

```<code>1, 2017-01-01
3, 2017-01-01
2, 2017-01-02
1, 2017-01-02
</code>```

My current naive approach is only giving me the top 2 across all dates.

```<code>--Using SQLite
select date(dateVal) || did
from data
group by date(dateVal), did
order by count(*) desc
limit 2
</code>```

I'm using the concatenation operator so that I can later extract the rows.

I am using SQLite, but any general SQL explanation would be appreciated.

答:
I tested the query using sql server </p>

```<code>select top 2 did, dateVal
from (select *, count(*) as c
      from test
      group by did,dateVal) as t
order by t.c desc
</code>```

Body:
I am attempting to find the top n records when grouped by multiple attributes. I believe it is related to this problem, but I am having difficulty adapting the solution described  to my situation.

To simplify, I have a table with columns (did is short for device_id):

id int
did int
dateVal dateTime

I am trying to find the top n device_id's for each day with the most rows.

For example (ignoring id and the time part of dateTime),

did dateVal
1   2017-01-01
1   2017-01-01
1   2017-01-01
2   2017-01-01
3   2017-01-01
3   2017-01-01

1   2017-01-02
1   2017-01-02
2   2017-01-02
2   2017-01-02
2   2017-01-02
3   2017-01-02

Finding the top 2 would yield...

1, 2017-01-01
3, 2017-01-01
2, 2017-01-02
1, 2017-01-02

My current naive approach is only giving me the top 2 across all dates.

--Using SQLite
select date(dateVal) || did
from data
group by date(dateVal), did
order by count(*) desc
limit 2

I'm using the concatenation operator so that I can later extract the rows.

I am using SQLite, but any general SQL explanation would be appreciated.

Body:
I tested the query using sql server

select top 2 did, dateVal
from (select *, count(*) as c
      from test
      group by did,dateVal) as t
order by t.c desc


问:
Cannot start server. Server instance is not configured
While trying to setup the tomcat server for my project I get the following error: Please see the full stack trace below:

```<code>java.lang.ClassNotFoundException: com.springsource.tcserver.serviceability.deploy.TcContainerDeployer
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
at org.apache.tomcat.util.digester.ObjectCreateRule.begin(ObjectCreateRule.java:205)
at org.apache.tomcat.util.digester.Rule.begin(Rule.java:153)
at org.apache.tomcat.util.digester.Digester.startElement(Digester.java:1356)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.startElement(AbstractSAXParser.java:501)
at com.sun.org.apache.xerces.internal.parsers.AbstractXMLDocumentParser.emptyElement(AbstractXMLDocumentParser.java:179)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanStartElement(XMLDocumentFragmentScannerImpl.java:1343)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2755)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:648)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:511)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:808)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:119)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1205)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:522)
at org.apache.tomcat.util.digester.Digester.parse(Digester.java:1642)
at org.apache.catalina.startup.Catalina.load(Catalina.java:510)
at org.apache.catalina.startup.Catalina.load(Catalina.java:548)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.catalina.startup.Bootstrap.load(Bootstrap.java:261)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)

Jun 5, 2013 12:23:21 PM org.apache.catalina.startup.Catalina load
WARNING: Catalina.start using conf/server.xml:
java.lang.ClassNotFoundException: com.springsource.tcserver.serviceability.deploy.TcContainerDeployer
    at org.apache.tomcat.util.digester.Digester.createSAXException(Digester.java:2806)
    at org.apache.tomcat.util.digester.Digester.createSAXException(Digester.java:2832)
    at org.apache.tomcat.util.digester.Digester.startElement(Digester.java:1359)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.startElement(AbstractSAXParser.java:501)
    at com.sun.org.apache.xerces.internal.parsers.AbstractXMLDocumentParser.emptyElement(AbstractXMLDocumentParser.java:179)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanStartElement(XMLDocumentFragmentScannerImpl.java:1343)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2755)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:648)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:511)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:808)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737)
    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:119)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1205)
    at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:522)
    at org.apache.tomcat.util.digester.Digester.parse(Digester.java:1642)
    at org.apache.catalina.startup.Catalina.load(Catalina.java:510)
    at org.apache.catalina.startup.Catalina.load(Catalina.java:548)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.apache.catalina.startup.Bootstrap.load(Bootstrap.java:261)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)
Caused by: java.lang.ClassNotFoundException: com.springsource.tcserver.serviceability.deploy.TcContainerDeployer
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
    at org.apache.tomcat.util.digester.ObjectCreateRule.begin(ObjectCreateRule.java:205)
    at org.apache.tomcat.util.digester.Rule.begin(Rule.java:153)
    at org.apache.tomcat.util.digester.Digester.startElement(Digester.java:1356)
    ... 20 more
Jun 5, 2013 12:23:21 PM org.apache.tomcat.util.digester.Digester startElement
SEVERE: Begin event threw exception
java.lang.ClassNotFoundException: com.springsource.tcserver.serviceability.deploy.TcContainerDeployer
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
    at org.apache.tomcat.util.digester.ObjectCreateRule.begin(ObjectCreateRule.java:205)
    at org.apache.tomcat.util.digester.Rule.begin(Rule.java:153)
    at org.apache.tomcat.util.digester.Digester.startElement(Digester.java:1356)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.startElement(AbstractSAXParser.java:501)
    at com.sun.org.apache.xerces.internal.parsers.AbstractXMLDocumentParser.emptyElement(AbstractXMLDocumentParser.java:179)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanStartElement(XMLDocumentFragmentScannerImpl.java:1343)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2755)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:648)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:511)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:808)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737)
    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:119)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1205)
    at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:522)
    at org.apache.tomcat.util.digester.Digester.parse(Digester.java:1642)
    at org.apache.catalina.startup.Catalina.load(Catalina.java:510)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:568)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
Jun 5, 2013 12:23:21 PM org.apache.catalina.startup.Catalina load
WARNING: Catalina.start using conf/server.xml:
java.lang.ClassNotFoundException: com.springsource.tcserver.serviceability.deploy.TcContainerDeployer
    at org.apache.tomcat.util.digester.Digester.createSAXException(Digester.java:2806)
    at org.apache.tomcat.util.digester.Digester.createSAXException(Digester.java:2832)
    at org.apache.tomcat.util.digester.Digester.startElement(Digester.java:1359)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.startElement(AbstractSAXParser.java:501)
    at com.sun.org.apache.xerces.internal.parsers.AbstractXMLDocumentParser.emptyElement(AbstractXMLDocumentParser.java:179)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanStartElement(XMLDocumentFragmentScannerImpl.java:1343)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2755)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:648)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:511)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:808)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737)
    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:119)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1205)
    at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:522)
    at org.apache.tomcat.util.digester.Digester.parse(Digester.java:1642)
    at org.apache.catalina.startup.Catalina.load(Catalina.java:510)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:568)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
Caused by: java.lang.ClassNotFoundException: com.springsource.tcserver.serviceability.deploy.TcContainerDeployer
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
    at org.apache.tomcat.util.digester.ObjectCreateRule.begin(ObjectCreateRule.java:205)
    at org.apache.tomcat.util.digester.Rule.begin(Rule.java:153)
    at org.apache.tomcat.util.digester.Digester.startElement(Digester.java:1356)
    ... 20 more
Jun 5, 2013 12:23:21 PM org.apache.catalina.startup.Catalina start
SEVERE: Cannot start server. Server instance is not configured.
</code>```

What could be the possible error? In my server configuration I am using "Use Tomcat installation". I had to replace the server.xml, context.xml, portal-ext.properties, catalina.xml to match my project specifications; to use the jdbc resources etc. It is after this change that I find this error...

答:
Some of the configuration files must have got corrupted. I faced this issue and fixed it by uninstaling and reinstalling tomcat. I use tomcat 7. But you can use the same commands with any version

```<code>sudo apt-get purge tomcat7
sudo apt-get install tomcat7
</code>```

Now when you run the server it will show write or read failed in several files. Just give write and read permissions to those directories

```<code>chmod -R a+r {directory_name}
chmod -R a+w {directory_name}
</code>```

Now go to tomcat folder and make a link of some files here

```<code>cd /usr/share/tomcat7
sudo ln -s /var/lib/tomcat7/conf conf
sudo ln -s /var/log/tomcat7 log
sudo ln -s /etc/tomcat7/policy.d/03catalina.policy conf/catalina.policy
sudo chmod -R a+rwx /usr/share/tomcat7/conf
</code>```

This will solve all the problems

Body:
While trying to setup the tomcat server for my project I get the following error: Please see the full stack trace below:

java.lang.ClassNotFoundException: com.springsource.tcserver.serviceability.deploy.TcContainerDeployer
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
at org.apache.tomcat.util.digester.ObjectCreateRule.begin(ObjectCreateRule.java:205)
at org.apache.tomcat.util.digester.Rule.begin(Rule.java:153)
at org.apache.tomcat.util.digester.Digester.startElement(Digester.java:1356)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.startElement(AbstractSAXParser.java:501)
at com.sun.org.apache.xerces.internal.parsers.AbstractXMLDocumentParser.emptyElement(AbstractXMLDocumentParser.java:179)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanStartElement(XMLDocumentFragmentScannerImpl.java:1343)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2755)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:648)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:511)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:808)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:119)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1205)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:522)
at org.apache.tomcat.util.digester.Digester.parse(Digester.java:1642)
at org.apache.catalina.startup.Catalina.load(Catalina.java:510)
at org.apache.catalina.startup.Catalina.load(Catalina.java:548)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.catalina.startup.Bootstrap.load(Bootstrap.java:261)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)

Jun 5, 2013 12:23:21 PM org.apache.catalina.startup.Catalina load
WARNING: Catalina.start using conf/server.xml:
java.lang.ClassNotFoundException: com.springsource.tcserver.serviceability.deploy.TcContainerDeployer
    at org.apache.tomcat.util.digester.Digester.createSAXException(Digester.java:2806)
    at org.apache.tomcat.util.digester.Digester.createSAXException(Digester.java:2832)
    at org.apache.tomcat.util.digester.Digester.startElement(Digester.java:1359)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.startElement(AbstractSAXParser.java:501)
    at com.sun.org.apache.xerces.internal.parsers.AbstractXMLDocumentParser.emptyElement(AbstractXMLDocumentParser.java:179)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanStartElement(XMLDocumentFragmentScannerImpl.java:1343)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2755)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:648)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:511)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:808)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737)
    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:119)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1205)
    at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:522)
    at org.apache.tomcat.util.digester.Digester.parse(Digester.java:1642)
    at org.apache.catalina.startup.Catalina.load(Catalina.java:510)
    at org.apache.catalina.startup.Catalina.load(Catalina.java:548)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.apache.catalina.startup.Bootstrap.load(Bootstrap.java:261)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)
Caused by: java.lang.ClassNotFoundException: com.springsource.tcserver.serviceability.deploy.TcContainerDeployer
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
    at org.apache.tomcat.util.digester.ObjectCreateRule.begin(ObjectCreateRule.java:205)
    at org.apache.tomcat.util.digester.Rule.begin(Rule.java:153)
    at org.apache.tomcat.util.digester.Digester.startElement(Digester.java:1356)
    ... 20 more
Jun 5, 2013 12:23:21 PM org.apache.tomcat.util.digester.Digester startElement
SEVERE: Begin event threw exception
java.lang.ClassNotFoundException: com.springsource.tcserver.serviceability.deploy.TcContainerDeployer
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
    at org.apache.tomcat.util.digester.ObjectCreateRule.begin(ObjectCreateRule.java:205)
    at org.apache.tomcat.util.digester.Rule.begin(Rule.java:153)
    at org.apache.tomcat.util.digester.Digester.startElement(Digester.java:1356)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.startElement(AbstractSAXParser.java:501)
    at com.sun.org.apache.xerces.internal.parsers.AbstractXMLDocumentParser.emptyElement(AbstractXMLDocumentParser.java:179)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanStartElement(XMLDocumentFragmentScannerImpl.java:1343)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2755)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:648)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:511)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:808)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737)
    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:119)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1205)
    at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:522)
    at org.apache.tomcat.util.digester.Digester.parse(Digester.java:1642)
    at org.apache.catalina.startup.Catalina.load(Catalina.java:510)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:568)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
Jun 5, 2013 12:23:21 PM org.apache.catalina.startup.Catalina load
WARNING: Catalina.start using conf/server.xml:
java.lang.ClassNotFoundException: com.springsource.tcserver.serviceability.deploy.TcContainerDeployer
    at org.apache.tomcat.util.digester.Digester.createSAXException(Digester.java:2806)
    at org.apache.tomcat.util.digester.Digester.createSAXException(Digester.java:2832)
    at org.apache.tomcat.util.digester.Digester.startElement(Digester.java:1359)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.startElement(AbstractSAXParser.java:501)
    at com.sun.org.apache.xerces.internal.parsers.AbstractXMLDocumentParser.emptyElement(AbstractXMLDocumentParser.java:179)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanStartElement(XMLDocumentFragmentScannerImpl.java:1343)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2755)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:648)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:511)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:808)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737)
    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:119)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1205)
    at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:522)
    at org.apache.tomcat.util.digester.Digester.parse(Digester.java:1642)
    at org.apache.catalina.startup.Catalina.load(Catalina.java:510)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:568)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
Caused by: java.lang.ClassNotFoundException: com.springsource.tcserver.serviceability.deploy.TcContainerDeployer
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
    at org.apache.tomcat.util.digester.ObjectCreateRule.begin(ObjectCreateRule.java:205)
    at org.apache.tomcat.util.digester.Rule.begin(Rule.java:153)
    at org.apache.tomcat.util.digester.Digester.startElement(Digester.java:1356)
    ... 20 more
Jun 5, 2013 12:23:21 PM org.apache.catalina.startup.Catalina start
SEVERE: Cannot start server. Server instance is not configured.

What could be the possible error? In my server configuration I am using "Use Tomcat installation". I had to replace the server.xml, context.xml, portal-ext.properties, catalina.xml to match my project specifications; to use the jdbc resources etc. It is after this change that I find this error...

Body:
Some of the configuration files must have got corrupted. I faced this issue and fixed it by uninstaling and reinstalling tomcat. I use tomcat 7. But you can use the same commands with any version

sudo apt-get purge tomcat7
sudo apt-get install tomcat7

Now when you run the server it will show write or read failed in several files. Just give write and read permissions to those directories

chmod -R a+r {directory_name}
chmod -R a+w {directory_name}

Now go to tomcat folder and make a link of some files here

cd /usr/share/tomcat7
sudo ln -s /var/lib/tomcat7/conf conf
sudo ln -s /var/log/tomcat7 log
sudo ln -s /etc/tomcat7/policy.d/03catalina.policy conf/catalina.policy
sudo chmod -R a+rwx /usr/share/tomcat7/conf

This will solve all the problems


问:
Immutable Struct in Golang
Is it possible to define an immutable struct in Golang? Once initialized then only read operation on struct's field, no modification of field values. If so, how to do that.</p>

答:
It is possible to make a struct read-only outside of its package by making its members non-exported and providing readers. For example:

```<code>package mypackage

type myReadOnly struct {
  value int
}

func (s myReadOnly) Value() int {
  return s.value
}

func NewMyReadonly(value int) myReadOnly{
  return myReadOnly{value: value}
}
</code>```

And usage:

```<code>myReadonly := mypackage.NewMyReadonly(3)
fmt.Println(myReadonly.Value())  // Prints 3
</code>```

Title: Immutable Struct in Golang

Body:
It is possible to make a struct read-only outside of its package by making its members non-exported and providing readers. For example:

package mypackage

type myReadOnly struct {
  value int
}

func (s myReadOnly) Value() int {
  return s.value
}

func NewMyReadonly(value int) myReadOnly{
  return myReadOnly{value: value}
}

And usage:

myReadonly := mypackage.NewMyReadonly(3)
fmt.Println(myReadonly.Value())  // Prints 3


问:
Retrieving a random record from DB
Wondering what is the best way to retrieve a random record from the database in my Ruby on Rails (2.3.9) applications. </p>

<p>The closest I got was using the below. SQLITE3 liked it by in production MySQL did not. </p>

```<code>#class PostsController < ApplicationController
...
@posts = Post.all(:order => "RANDOM()")
...
end

#view
<% @posts.each do |post| %>
...
<% end %>
</code>```

答: The function is RAND() in MySQL.  Use it instead of RANDOM().

Title: Retrieving a random record from DB

Body:
Wondering what is the best way to retrieve a random record from the database in my Ruby on Rails (2.3.9) applications.

The closest I got was using the below. SQLITE3 liked it by in production MySQL did not.

#class PostsController < ApplicationController
...
@posts = Post.all(:order => "RANDOM()")
...
end

#view
<% @posts.each do |post| %>
...
<% end %>


问:
Updated android studio and got fail with Gstreamer build
Updated to Android Studio 3.0.0 with new android gradle plugin.
While buildin project got message:

```<code>What went wrong:
Execution failed for task `':app:externalNativeBuildDebug'`.

Expected output file at `gst-build-arm64-v8a/libgstreamer_android.so` for target `gstreamer_android` but there was none
</code>```

but libgstreamer_android.so library file is already there. For native code I use ndk-build. Does anyone have this issue?

答:
Add to build.gradle file of our android module field targets.

```<code>android {
  defaultConfig {
    externalNativeBuild {
      ndkBuild {
        targets "name_of_native_module_in_android_mk_file"
      }
  ...
}
</code>```

Don't add gstreamer_android.

Body:
Updated to Android Studio 3.0.0 with new android gradle plugin.
While buildin project got message:

What went wrong:
Execution failed for task `':app:externalNativeBuildDebug'`.

Expected output file at `gst-build-arm64-v8a/libgstreamer_android.so` for target `gstreamer_android` but there was none

but libgstreamer_android.so library file is already there. For native code I use ndk-build. Does anyone have this issue?

Body:
Add to build.gradle file of our android module field targets.

android {
  defaultConfig {
    externalNativeBuild {
      ndkBuild {
        targets "name_of_native_module_in_android_mk_file"
      }
  ...
}

Don't add gstreamer_android.


问:
CSS - Unable to center vertically
I am trying to center vertically 4 divs present in a Bootstrap row.
Here is my basic code :

```<code><div class="row">
     <div class="col-md-3"><button type="button" style="float:right; height: 40px;">Contact</button></div>
     <div class="col-md-3">Activity 1</div>
     <div class="col-md-3">Activity 2</div>
     <div class="col-md-3">Activity 3</div>
</div>
</code>```

So, I can't use Flexbox because I need to keep the button on the right of the row in medium screen and justify-self:flex-end is not enough to keep the button on the right of the row. I can't also move the row with the button at the end of the code, because I need to keep it in first for mobile devices.
I have also tried to use display:table and display:table-cell and it still not working.

Anyone has an idea ?

答:
try with specifying class as below which helps to your solution.</p>

```<code>.col-md-3 ~ .col-md-3
{display:table-cell;}
</code>```

Title: CSS - Unable to center vertically

Body:
I am trying to center vertically 4 divs present in a Bootstrap row.
Here is my basic code :

<button type="button" style="float:right; height: 40px;">Contact</button>

Activity 1

Activity 2

Activity 3

So, I can't use Flexbox because I need to keep the button on the right of the row in medium screen and justify-self:flex-end is not enough to keep the button on the right of the row. I can't also move the row with the button at the end of the code, because I need to keep it in first for mobile devices.
I have also tried to use display:table and display:table-cell and it still not working.

Anyone has an idea ?

Body:
try with specifying class as below which helps to your solution.

.col-md-3 ~ .col-md-3
{display:table-cell;}


问:
Loop inside of a loop, in React JSX
I am trying to render in react, jsx, a loop inside of a loop
Like bellow:

```<code>{this.state.ans.map(function(item) {
    return (
        {this.state.quest.map(
            function(item1) {return (item1)}
        )}
        {item}
    )
})}
</code>```

This does not work any other suggestions

答:
You forgot the wrapping div in your first map statement:

```<code>render() {
  return (
    <div>
      {this.state.ans.map(item =>
        <div> // this div was missing
          {this.state.quest.map(quest => quest)}
          {item}
        </div>
      )}
    </div>
  )
}
</code>```

Title: Loop inside of a loop, in React JSX

Body:
I am trying to render in react, jsx, a loop inside of a loop
Like bellow:

{this.state.ans.map(function(item) {
    return (
        {this.state.quest.map(
            function(item1) {return (item1)}
        )}
        {item}
    )
})}

This does not work any other suggestions

Body:
You forgot the wrapping div in your first map statement:

render() {
  return (
    <div>
      {this.state.ans.map(item =>
        <div> // this div was missing
          {this.state.quest.map(quest => quest)}
          {item}
        </div>
      )}
    </div>
  )
}


问:
Insert Path of a file with \\ in mysql using java
I am making a standalone application using java,and in that i need to insert the path of the image that user chooses from file chooser.
I am getting the path of the file but when i store it in the database(mysql) it doesn't stores the \,so when i retrieve that path,the file doesn't show up.

How to store the path of file with \\ so that one gets escaped using java code?

i tried using replaceall method but its giving an error of illegal character set.

```<code>filename.replaceall("\","\\");
</code>```

But this didn't work out.

答:
Since String is immutable and all methods you call on it doesn't change Strings internal value, but rather return the modified result, you need to assign the result of the replace to a variable. Also, since you want replace chars, not regex patterns, the replace() method is more than sufficient. The replaceAll() takes regex and the \ is a special character in regex as well.

```<code>filename = filename.replace("\\", "\\\\");
</code>```

However, forward slashes are supposed to work as good in Windows.

```<code>filename = filename.replace("\\", "/");
</code>```

However #2, you might want to store it in DB using PreparedStatement which sanitizes bad and SQL-injection-sensitive characters for you away. Prepare here.

Unrelated to the concrete problem, why would you like to store the file path in a DB? This is prone to portability errors. I'd suggest to store only the (unique) filename and have the actual files in a single common path which is configureable as application setting.

Body:
I am making a standalone application using java,and in that i need to insert the path of the image that user chooses from file chooser.
I am getting the path of the file but when i store it in the database(mysql) it doesn't stores the \,so when i retrieve that path,the file doesn't show up.

How to store the path of file with \\ so that one gets escaped using java code?

i tried using replaceall method but its giving an error of illegal character set.

filename.replaceall("\","\\");

But this didn't work out.

Body:
Since String is immutable and all methods you call on it doesn't change Strings internal value, but rather return the modified result, you need to assign the result of the replace to a variable. Also, since you want replace chars, not regex patterns, the replace() method is more than sufficient. The replaceAll() takes regex and the \ is a special character in regex as well.

filename = filename.replace("\\", "\\\\");

However, forward slashes are supposed to work as good in Windows.

filename = filename.replace("\\", "/");

However #2, you might want to store it in DB using PreparedStatement which sanitizes bad and SQL-injection-sensitive characters for you away. Prepare here.

Unrelated to the concrete problem, why would you like to store the file path in a DB? This is prone to portability errors. I'd suggest to store only the (unique) filename and have the actual files in a single common path which is configureable as application setting.