问:
Z3 Java API documentation
I have installed the Z3 API for Java and I am trying to use it but I can't find any documentation that explains how to use this API.

The only resource I have found so far is the source code and the example program, so I wanted to know if anyone was aware of any other documentation for the Z3 Java API.

答: You can find the API reference at https://z3prover.github.io/api/html/namespacecom_1_1microsoft_1_1z3.html</p>

Title: Z3 Java API documentation


来源: stackexchange

问:
Querying from an API to a Google Spreadsheet / G Apps Script and obtaining filtered results
I'm trying to build a spreadsheet based around DataDT's excellent API for 1-minute Forex data. I'm trying to build a function that 1) Reads a value ("Date time") from a cell 2) Searches for that value in a given URL from the aforementioned API 3) Prints 2 other properties (open & close price) for that same date.

In other words, It would take input from rows N and O, and output the relevant values (OPEN and CLOSE from the API) in rows H and I.

(Link to current GSpreadsheet)

This spreadsheet would link macroeconomic news and historic prices and possibly reveal useful insights for Forex users.

I already managed to query data from the API effectively but I can't find a way to filter only for the datetimes I'm asking. Much less iterating for different dates! With the help from user @Cooper I got the following code that can query entire pages from the API but can't efficiently filter yet. I'd appreciate any help that you might provide.

This is the current status of the code in Appscript:

(Code.gs)

```<code>function searchOnEdit(e) {
  //e.source.toast('Entry');// I use these lines for debugging
  var sh=e.range.getSheet();
  if(sh.getName()!='API') return;
  var checkedValue='TRUE';//these are the defaults if you install the checkboxes from the Insert Menu
  var uncheckedValue='FALSE';
  if(e.range.columnStart==17 && e.range.rowStart>1 && e.value==checkedValue) {
    e.range.setValue(uncheckedValue);//this was commented out it should not have been sorry for that Cooper
    //e.source.toast('flag1');
    var r=sh.getRange(e.range.rowStart,1,1,sh.getLastColumn()).getValues()[0];
    var obj={datetime:r[14],url:r[13],event:e};
    var dObj=getDataDT1(obj);
    //Logger.log(dObj);
    sh.getRange(e.range.rowStart,4).setValue(dObj.OPEN);//loading OPEN on your spreadsheet
    sh.getRange(e.range.rowStart,5).setValue(dObj.CLOSE);//loadding CLOSE on your spreadsheet
  }
}

//{datetime:'',url:'',event:e}
function getDataDT1(obj) {
  Logger.log(JSON.stringify(obj));//I need to see this
  var r=UrlFetchApp.fetch(obj.url);
  var data=JSON.parse(r.getContentText("UTF-8"));
  //Logger.log(data);
  var pair='USDJPY';
  var dat=new Date(obj.datetime);
  var dtv=new Date(dat.getFullYear(),dat.getMonth(),dat.getDate(),dat.getHours(),dat.getMinutes()).valueOf();
  for(var i=0;i<data.length;i++) {
    var dt=data[i].DATE_TIME.split(' ');
    var sd=new Date(data[i].DATE_TIME);
    var sdv=new Date(sd.getFullYear(),sd.getMonth(),sd.getDate(),sd.getHours(),sd.getMinutes()).valueOf();
    if(sdv==dtv) {
      var d=dt[0].split('-');
      var t=dt[1].split(':');
      var datestring=Utilities.formatString('%s/%s/%s',d[1],d[2],d[0]);
      var timestring=Utilities.formatString('%s:%s',t[0],t[1]);
      var rObj={DATE:datestring,TIME:timestring,PAIR:pair,OPEN:data[i].OPEN.toFixed(3),CLOSE:data[i].CLOSE.toFixed(3)};
      break;
    }
  }
  //Logger.log(rObj);
  return rObj;
}
</code>```

(Appscript.json)

```<code>{
  "timeZone": "America/Caracas",
  "dependencies": {
  },
  "exceptionLogging": "STACKDRIVER",
  "oauthScopes":  ["https://www.googleapis.com/auth/userinfo.email","https://www.googleapis.com/auth/script.external_request","https://www.googleapis.com/auth/script.scriptapp","https://www.googleapis.com/auth/spreadsheets"]
}
</code>```

(Trigger.js)

```<code>function createSearchOnEditTrigger() {
  var ss=SpreadsheetApp.getActive();
  ScriptApp.newTrigger('searchOnEdit').forSpreadsheet(ss.getId()).onEdit().create();
}
</code>```

答:
onEdit Search

You will need to add a column of checkboxes to column 17 and also create an installable onEdit trigger.  You may use the code provided or do it manually via the Edit/Project Triggers menu. When using the trigger creation code please check to insure that only one trigger was creates as multiple triggers can cause problems.

Also, don't make the mistake of naming your installable trigger onEdit(e) because it will respond to the simple trigger and the installable trigger causing problems.

I have an animation below showing you how it operates and also you can see the spreadsheet layout as well.  Please notice the hidden columns.  I had to do that to make the animation as small as possible. But I didn't delete any of your columns.

It's best to wait for the the check box to get reset back to off before checking another check box.  It is possible to check them so fast that script can't keep up and some searches may be missed.

I also had to add these scopes manually:

"oauthScopes":["https://www.googleapis.com/auth/userinfo.email","https://www.googleapis.com/auth/script.external_request","https://www.googleapis.com/auth/spreadsheets"]

You can put them into your appsscript.json file which is viewable using the View/Show Manifest File. Here's a reference that just barely shows you what they look like. But the basic idea is to put a comma after the last entry before the closing bracket and add the needed lines.

After you have created the trigger it's better to go into View/Current Project triggers and set the Notifications to Immediate.  If you get scoping errors it will tell you which ones to add.  You add them and then run a function and you can reauthorize the access with the additional scopes.  You can even run a null function like function dummy(){};.

This is the onEdit function:

```<code>function searchOnEdit(e) {
  //e.source.toast('Entry');// I use these lines for debugging
  var sh=e.range.getSheet();
  if(sh.getName()!='API') return;
  var checkedValue='TRUE';//these are the defaults if you install the checkboxes from the Insert Menu
  var uncheckedValue='FALSE';
  if(e.range.columnStart==17 && e.range.rowStart>1 && e.value==checkedValue) {
    e.range.setValue(uncheckedValue);
    //e.source.toast('flag1');
    var r=sh.getRange(e.range.rowStart,1,1,sh.getLastColumn()).getValues()[0];
    var obj={datetime:r[14],url:r[13],event:e};//you dont really need e here
    var dObj=getDataDT1(obj);
    //Logger.log(dObj);
    sh.getRange(e.range.rowStart,4).setValue(dObj.OPEN);//loading OPEN on your spreadsheet
    sh.getRange(e.range.rowStart,5).setValue(dObj.CLOSE);//loadding CLOSE on your spreadsheet
  }
}
</code>```

This is the search function.  I tried caching the data but it was too large. So if you can reduce the size significantly that would help speed things up for consecutive searches.

```<code>//{datetime:'',url:'',event:e}
function getDataDT1(obj) {
  var r=UrlFetchApp.fetch(obj.url);
  var data=JSON.parse(r.getContentText("UTF-8"));
  //Logger.log(data);
  var pair='USDJPY';
  var dat=new Date(obj.datetime);
  var dtv=new Date(dat.getFullYear(),dat.getMonth(),dat.getDate(),dat.getHours(),dat.getMinutes()).valueOf();
  for(var i=0;i<data.length;i++) {
    var dt=data[i].DATE_TIME.split(' ');
    var sd=new Date(data[i].DATE_TIME);
    var sdv=new Date(sd.getFullYear(),sd.getMonth(),sd.getDate(),sd.getHours(),sd.getMinutes()).valueOf();
    if(sdv==dtv) {
      var d=dt[0].split('-');
      var t=dt[1].split(':');
      var datestring=Utilities.formatString('%s/%s/%s',d[1],d[2],d[0]);
      var timestring=Utilities.formatString('%s:%s',t[0],t[1]);
      var rObj={DATE:datestring,TIME:timestring,PAIR:pair,OPEN:data[i].OPEN.toFixed(3),CLOSE:data[i].CLOSE.toFixed(3)};
      break;
    }
  }
  //Logger.log(rObj);
  return rObj;
}
</code>```

This is the create Trigger function.  Becareful not to run this more than once and always go check to see that there is only one and set the notifications to immediate when you first turn it on so you'll get emails pretty quickly after errors occur.

```<code>function createSearchOnEditTrigger() {
  var ss=SpreadsheetApp.getActive();
  ScriptApp.newTrigger('searchOnEdit').forSpreadsheet(ss.getId()).onEdit().create();
}
</code>```

Animation:

This is a copy of your spreadsheet with the check boxes.

If you have any difficulties feel free to come back and get some help. I know some of this stuff sounds a bit daunting but it's kind of like going metric. Once you've measured and weighed a few things it begins to sound and feel natural.

Here's my code exactly as I have it in my script which is running right now.  Perhaps I have a typo in it due to editing in comments.  This has some debugging lines in which run the Logger and display toasts which you should probably comment out.

```<code>function searchOnEdit(e) {
  e.source.toast('Entry');
  var sh=e.range.getSheet();
  if(sh.getName()!='API') return;
  var checkedValue='TRUE';
  var uncheckedValue='FALSE';
  if(e.range.columnStart==17 && e.range.rowStart>1 && e.value==checkedValue) {
    e.range.setValue(uncheckedValue);
    e.source.toast('flag1');
    var r=sh.getRange(e.range.rowStart,1,1,sh.getLastColumn()).getValues()[0];
    var obj={datetime:r[14],url:r[13],event:e};
    var dObj=getDataDT1(obj);
    Logger.log(dObj);
    sh.getRange(e.range.rowStart,4).setValue(dObj.OPEN);
    sh.getRange(e.range.rowStart,5).setValue(dObj.CLOSE);
  }
}

//{datetime:'',url:''}
function getDataDT1(obj) {
  var r=UrlFetchApp.fetch(obj.url);
  var data=JSON.parse(r.getContentText("UTF-8"));
  //Logger.log(data);
  var pair='USDJPY';
  var dat=new Date(obj.datetime);
  var dtv=new Date(dat.getFullYear(),dat.getMonth(),dat.getDate(),dat.getHours(),dat.getMinutes()).valueOf();
  for(var i=0;i<data.length;i++) {
    var dt=data[i].DATE_TIME.split(' ');
    var sd=new Date(data[i].DATE_TIME);
    var sdv=new Date(sd.getFullYear(),sd.getMonth(),sd.getDate(),sd.getHours(),sd.getMinutes()).valueOf();
    if(sdv==dtv) {
      var d=dt[0].split('-');
      var t=dt[1].split(':');
      var datestring=Utilities.formatString('%s/%s/%s',d[1],d[2],d[0]);
      var timestring=Utilities.formatString('%s:%s',t[0],t[1]);
      var rObj={DATE:datestring,TIME:timestring,PAIR:pair,OPEN:data[i].OPEN.toFixed(3),CLOSE:data[i].CLOSE.toFixed(3)};
      break;
    }
  }
  //Logger.log(rObj);
  return rObj;
}

function createSearchOnEditTrigger() {
  var ss=SpreadsheetApp.getActive();
  ScriptApp.newTrigger('searchOnEdit').forSpreadsheet(ss.getId()).onEdit().create();
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to build a spreadsheet based around DataDT's excellent API for 1-minute Forex data. I'm trying to build a function that 1) Reads a value ("Date time") from a cell 2) Searches for that value in a given URL from the aforementioned API 3) Prints 2 other properties (open & close price) for that same date.

In other words, It would take input from rows N and O, and output the relevant values (OPEN and CLOSE from the API) in rows H and I.

(Link to current GSpreadsheet)

This spreadsheet would link macroeconomic news and historic prices and possibly reveal useful insights for Forex users.

I already managed to query data from the API effectively but I can't find a way to filter only for the datetimes I'm asking. Much less iterating for different dates! With the help from user @Cooper I got the following code that can query entire pages from the API but can't efficiently filter yet. I'd appreciate any help that you might provide.

This is the current status of the code in Appscript:

(Code.gs)

function searchOnEdit(e) {
  //e.source.toast('Entry');// I use these lines for debugging
  var sh=e.range.getSheet();
  if(sh.getName()!='API') return;
  var checkedValue='TRUE';//these are the defaults if you install the checkboxes from the Insert Menu
  var uncheckedValue='FALSE';
  if(e.range.columnStart==17 && e.range.rowStart>1 && e.value==checkedValue) {
    e.range.setValue(uncheckedValue);//this was commented out it should not have been sorry for that Cooper
    //e.source.toast('flag1');
    var r=sh.getRange(e.range.rowStart,1,1,sh.getLastColumn()).getValues()[0];
    var obj={datetime:r[14],url:r[13],event:e};
    var dObj=getDataDT1(obj);
    //Logger.log(dObj);
    sh.getRange(e.range.rowStart,4).setValue(dObj.OPEN);//loading OPEN on your spreadsheet
    sh.getRange(e.range.rowStart,5).setValue(dObj.CLOSE);//loadding CLOSE on your spreadsheet
  }
}

//{datetime:'',url:'',event:e}
function getDataDT1(obj) {
  Logger.log(JSON.stringify(obj));//I need to see this
  var r=UrlFetchApp.fetch(obj.url);
  var data=JSON.parse(r.getContentText("UTF-8"));
  //Logger.log(data);
  var pair='USDJPY';
  var dat=new Date(obj.datetime);
  var dtv=new Date(dat.getFullYear(),dat.getMonth(),dat.getDate(),dat.getHours(),dat.getMinutes()).valueOf();
  for(var i=0;i<data.length;i++) {
    var dt=data[i].DATE_TIME.split(' ');
    var sd=new Date(data[i].DATE_TIME);
    var sdv=new Date(sd.getFullYear(),sd.getMonth(),sd.getDate(),sd.getHours(),sd.getMinutes()).valueOf();
    if(sdv==dtv) {
      var d=dt[0].split('-');
      var t=dt[1].split(':');
      var datestring=Utilities.formatString('%s/%s/%s',d[1],d[2],d[0]);
      var timestring=Utilities.formatString('%s:%s',t[0],t[1]);
      var rObj={DATE:datestring,TIME:timestring,PAIR:pair,OPEN:data[i].OPEN.toFixed(3),CLOSE:data[i].CLOSE.toFixed(3)};
      break;
    }
  }
  //Logger.log(rObj);
  return rObj;
}

(Appscript.json)

{
  "timeZone": "America/Caracas",
  "dependencies": {
  },
  "exceptionLogging": "STACKDRIVER",
  "oauthScopes":  ["https://www.googleapis.com/auth/userinfo.email","https://www.googleapis.com/auth/script.external_request","https://www.googleapis.com/auth/script.scriptapp","https://www.googleapis.com/auth/spreadsheets"]
}

(Trigger.js)

function createSearchOnEditTrigger() {
  var ss=SpreadsheetApp.getActive();
  ScriptApp.newTrigger('searchOnEdit').forSpreadsheet(ss.getId()).onEdit().create();
}

Body:
onEdit Search

You will need to add a column of checkboxes to column 17 and also create an installable onEdit trigger.  You may use the code provided or do it manually via the Edit/Project Triggers menu. When using the trigger creation code please check to insure that only one trigger was creates as multiple triggers can cause problems.

Also, don't make the mistake of naming your installable trigger onEdit(e) because it will respond to the simple trigger and the installable trigger causing problems.

I have an animation below showing you how it operates and also you can see the spreadsheet layout as well.  Please notice the hidden columns.  I had to do that to make the animation as small as possible. But I didn't delete any of your columns.

It's best to wait for the the check box to get reset back to off before checking another check box.  It is possible to check them so fast that script can't keep up and some searches may be missed.

I also had to add these scopes manually:

"oauthScopes":["https://www.googleapis.com/auth/userinfo.email","https://www.googleapis.com/auth/script.external_request","https://www.googleapis.com/auth/spreadsheets"]

You can put them into your appsscript.json file which is viewable using the View/Show Manifest File. Here's a reference that just barely shows you what they look like. But the basic idea is to put a comma after the last entry before the closing bracket and add the needed lines.

After you have created the trigger it's better to go into View/Current Project triggers and set the Notifications to Immediate.  If you get scoping errors it will tell you which ones to add.  You add them and then run a function and you can reauthorize the access with the additional scopes.  You can even run a null function like function dummy(){};.

This is the onEdit function:

function searchOnEdit(e) {
  //e.source.toast('Entry');// I use these lines for debugging
  var sh=e.range.getSheet();
  if(sh.getName()!='API') return;
  var checkedValue='TRUE';//these are the defaults if you install the checkboxes from the Insert Menu
  var uncheckedValue='FALSE';
  if(e.range.columnStart==17 && e.range.rowStart>1 && e.value==checkedValue) {
    e.range.setValue(uncheckedValue);
    //e.source.toast('flag1');
    var r=sh.getRange(e.range.rowStart,1,1,sh.getLastColumn()).getValues()[0];
    var obj={datetime:r[14],url:r[13],event:e};//you dont really need e here
    var dObj=getDataDT1(obj);
    //Logger.log(dObj);
    sh.getRange(e.range.rowStart,4).setValue(dObj.OPEN);//loading OPEN on your spreadsheet
    sh.getRange(e.range.rowStart,5).setValue(dObj.CLOSE);//loadding CLOSE on your spreadsheet
  }
}

This is the search function.  I tried caching the data but it was too large. So if you can reduce the size significantly that would help speed things up for consecutive searches.

//{datetime:'',url:'',event:e}
function getDataDT1(obj) {
  var r=UrlFetchApp.fetch(obj.url);
  var data=JSON.parse(r.getContentText("UTF-8"));
  //Logger.log(data);
  var pair='USDJPY';
  var dat=new Date(obj.datetime);
  var dtv=new Date(dat.getFullYear(),dat.getMonth(),dat.getDate(),dat.getHours(),dat.getMinutes()).valueOf();
  for(var i=0;i<data.length;i++) {
    var dt=data[i].DATE_TIME.split(' ');
    var sd=new Date(data[i].DATE_TIME);
    var sdv=new Date(sd.getFullYear(),sd.getMonth(),sd.getDate(),sd.getHours(),sd.getMinutes()).valueOf();
    if(sdv==dtv) {
      var d=dt[0].split('-');
      var t=dt[1].split(':');
      var datestring=Utilities.formatString('%s/%s/%s',d[1],d[2],d[0]);
      var timestring=Utilities.formatString('%s:%s',t[0],t[1]);
      var rObj={DATE:datestring,TIME:timestring,PAIR:pair,OPEN:data[i].OPEN.toFixed(3),CLOSE:data[i].CLOSE.toFixed(3)};
      break;
    }
  }
  //Logger.log(rObj);
  return rObj;
}

This is the create Trigger function.  Becareful not to run this more than once and always go check to see that there is only one and set the notifications to immediate when you first turn it on so you'll get emails pretty quickly after errors occur.

function createSearchOnEditTrigger() {
  var ss=SpreadsheetApp.getActive();
  ScriptApp.newTrigger('searchOnEdit').forSpreadsheet(ss.getId()).onEdit().create();
}

Animation:

This is a copy of your spreadsheet with the check boxes.

If you have any difficulties feel free to come back and get some help. I know some of this stuff sounds a bit daunting but it's kind of like going metric. Once you've measured and weighed a few things it begins to sound and feel natural.

Here's my code exactly as I have it in my script which is running right now.  Perhaps I have a typo in it due to editing in comments.  This has some debugging lines in which run the Logger and display toasts which you should probably comment out.

function searchOnEdit(e) {
  e.source.toast('Entry');
  var sh=e.range.getSheet();
  if(sh.getName()!='API') return;
  var checkedValue='TRUE';
  var uncheckedValue='FALSE';
  if(e.range.columnStart==17 && e.range.rowStart>1 && e.value==checkedValue) {
    e.range.setValue(uncheckedValue);
    e.source.toast('flag1');
    var r=sh.getRange(e.range.rowStart,1,1,sh.getLastColumn()).getValues()[0];
    var obj={datetime:r[14],url:r[13],event:e};
    var dObj=getDataDT1(obj);
    Logger.log(dObj);
    sh.getRange(e.range.rowStart,4).setValue(dObj.OPEN);
    sh.getRange(e.range.rowStart,5).setValue(dObj.CLOSE);
  }
}

//{datetime:'',url:''}
function getDataDT1(obj) {
  var r=UrlFetchApp.fetch(obj.url);
  var data=JSON.parse(r.getContentText("UTF-8"));
  //Logger.log(data);
  var pair='USDJPY';
  var dat=new Date(obj.datetime);
  var dtv=new Date(dat.getFullYear(),dat.getMonth(),dat.getDate(),dat.getHours(),dat.getMinutes()).valueOf();
  for(var i=0;i<data.length;i++) {
    var dt=data[i].DATE_TIME.split(' ');
    var sd=new Date(data[i].DATE_TIME);
    var sdv=new Date(sd.getFullYear(),sd.getMonth(),sd.getDate(),sd.getHours(),sd.getMinutes()).valueOf();
    if(sdv==dtv) {
      var d=dt[0].split('-');
      var t=dt[1].split(':');
      var datestring=Utilities.formatString('%s/%s/%s',d[1],d[2],d[0]);
      var timestring=Utilities.formatString('%s:%s',t[0],t[1]);
      var rObj={DATE:datestring,TIME:timestring,PAIR:pair,OPEN:data[i].OPEN.toFixed(3),CLOSE:data[i].CLOSE.toFixed(3)};
      break;
    }
  }
  //Logger.log(rObj);
  return rObj;
}

function createSearchOnEditTrigger() {
  var ss=SpreadsheetApp.getActive();
  ScriptApp.newTrigger('searchOnEdit').forSpreadsheet(ss.getId()).onEdit().create();
}


问:
Why am I getting an error that says Property assignment expected when I'm not even using TypeScript?
My Code is

```<code>import React from 'react';
import { Text, StyleSheet, View } from 'react-native';

const ComponentsScreen = () => {
  return {
    <View>
        <Text style={styles.testStyle}>This is the components screen</Text>
    </View>
    };
};

const styles = StyleSheet.create({
    testStyle: {
        fontSize: 30
    }
});

export default ComponentsScreen;
</code>```

I am getting an error which says Property Assignment Expected at my opening View tag, Declaration or Statement expected error at my closing View tag and at the bracket which closes ComponentsScreen, and Expression expected at the bracket closing my return statement. Any solutions?

答:
In component screen jsx uses return statment in parantheses rather than curly braces {} .

So just replace this :

```<code>const ComponentsScreen = () => {
  return (
    <View>
        <Text style={styles.testStyle}>This is the components screen</Text>
    </View>
    );
};
</code>```

Hope it helps. feel free for doubts

Body:
My Code is

import React from 'react';
import { Text, StyleSheet, View } from 'react-native';

const ComponentsScreen = () => {
  return {
    <View>
        <Text style={styles.testStyle}>This is the components screen</Text>
    </View>
    };
};

const styles = StyleSheet.create({
    testStyle: {
        fontSize: 30
    }
});

export default ComponentsScreen;

I am getting an error which says Property Assignment Expected at my opening View tag, Declaration or Statement expected error at my closing View tag and at the bracket which closes ComponentsScreen, and Expression expected at the bracket closing my return statement. Any solutions?

Body:
In component screen jsx uses return statment in parantheses rather than curly braces {} .

So just replace this :

const ComponentsScreen = () => {
  return (
    <View>
        <Text style={styles.testStyle}>This is the components screen</Text>
    </View>
    );
};

Hope it helps. feel free for doubts


问:
How can I access the ApplicationContext from within a JAX-WS web service?
Similar to How can I access the ServletContext from within a JAX-WS web service?, is there a way to access applicationContext, easier than this?</p>

```<code>import javax.annotation.Resource;
import javax.jws.WebService;
import javax.servlet.ServletContext;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.handler.MessageContext;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

@WebService
public class MyWebService {
    // boilerplate code begins :(

    @Resource
    private WebServiceContext context;
    private WebApplicationContext webApplicationContext = null;

    /**
     * @return
     * @throws IllegalStateException
     */
    private WebApplicationContext getWebApplicationContext()
            throws IllegalStateException {
        if (webApplicationContext != null)
            return webApplicationContext;
        ServletContext servletContext =
                (ServletContext) context.getMessageContext().get(
                        MessageContext.SERVLET_CONTEXT);
        webApplicationContext =
                WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
        return webApplicationContext;
    }
}
</code>```

答: I would install a Filter that saves ServletContext before chaining in a ThreadLocal</p>

OwnerDisplayName: pihentagy

ContentLicense: CC BY-SA 2.5

Body:
Similar to How can I access the ServletContext from within a JAX-WS web service?, is there a way to access applicationContext, easier than this?

import javax.annotation.Resource;
import javax.jws.WebService;
import javax.servlet.ServletContext;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.handler.MessageContext;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

@WebService
public class MyWebService {
    // boilerplate code begins :(

    @Resource
    private WebServiceContext context;
    private WebApplicationContext webApplicationContext = null;

    /**
     * @return
     * @throws IllegalStateException
     */
    private WebApplicationContext getWebApplicationContext()
            throws IllegalStateException {
        if (webApplicationContext != null)
            return webApplicationContext;
        ServletContext servletContext =
                (ServletContext) context.getMessageContext().get(
                        MessageContext.SERVLET_CONTEXT);
        webApplicationContext =
                WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
        return webApplicationContext;
    }
}

OwnerDisplayName: Maurice Perry


问:
A Little RegEx Help Please - Part 2
Here's the input string:

```<code>loadMedia('mediacontainer1', 'http://www.something.com/videos/JohnsAwesomeVideo.flv', 'http://www.something.com/videos/JohnsAwesomeCaption.xml', '/videos/video-splash-image.gif')
</code>```

With this RegExp: (?<=')[^']+.xml(?=')

... we get this:

```<code>http://www.something.com/videos/JohnsAwesomeCaption.xml
</code>```

... which is exactly what I wanted. BUT this time I'd like to select the complete string EXCEPT for the above. Basically an inverse selection. The output should look like this:

```<code>loadMedia('mediacontainer1', 'http://www.something.com/videos/JohnsAwesomeVideo.flv', '', '/videos/video-splash-image.gif')
</code>```

Thanks!

答:
Not sure which language you are using but in Java you can do:

```<code>str = "loadMedia('mediacontainer1', 'http://www.something.com/videos/JohnsAwesomeVideo.flv', 'http://www.something.com/videos/JohnsAwesomeCaption.xml', '/videos/video-splash-image.gif')";
System.out.println(str.replaceFirst("(?<=')[^']+\\.xml(?=')", ""));
</code>```

Or in php use this code:

```<code>$str = "loadMedia('mediacontainer1', 'http://www.something.com/videos/JohnsAwesomeVideo.flv', 'http://www.something.com/videos/JohnsAwesomeCaption.xml', '/videos/video-splash-image.gif')";
echo preg_replace("~(?<=')[^']+\.xml(?=')~", "", $str);
</code>```

OUTPUT (from both)

```<code>loadMedia('mediacontainer1', 'http://www.something.com/videos/JohnsAwesomeVideo.flv', '', '/videos/video-splash-image.gif')
</code>```

EDIT

Use following Java code to break the string into 2 parts as per your comments:

```<code>Pattern p = Pattern.compile("^(.*)(?<=')[^']+\\.xml(?=')(.*)$");
Matcher m = p.matcher(str);
if (m.find())
   System.out.println("Output: " + m.group(1) + "<br /><br />" + m.group(2));
</code>```

OUTPUT

```<code>Matched: loadMedia('mediacontainer1', 'http://www.something.com/videos/JohnsAwesomeVideo.flv', '<br /><br />', '/videos/video-splash-image.gif')
</code>```

ContentLicense: CC BY-SA 3.0

Title: A Little RegEx Help Please - Part 2

Body:
Here's the input string:

loadMedia('mediacontainer1', 'http://www.something.com/videos/JohnsAwesomeVideo.flv', 'http://www.something.com/videos/JohnsAwesomeCaption.xml', '/videos/video-splash-image.gif')

With this RegExp: (?<=')[^']+.xml(?=')

... we get this:

http://www.something.com/videos/JohnsAwesomeCaption.xml

... which is exactly what I wanted. BUT this time I'd like to select the complete string EXCEPT for the above. Basically an inverse selection. The output should look like this:

loadMedia('mediacontainer1', 'http://www.something.com/videos/JohnsAwesomeVideo.flv', '', '/videos/video-splash-image.gif')

Thanks!

Body:
Not sure which language you are using but in Java you can do:

str = "loadMedia('mediacontainer1', 'http://www.something.com/videos/JohnsAwesomeVideo.flv', 'http://www.something.com/videos/JohnsAwesomeCaption.xml', '/videos/video-splash-image.gif')";
System.out.println(str.replaceFirst("(?<=')[^']+\\.xml(?=')", ""));

Or in php use this code:

$str = "loadMedia('mediacontainer1', 'http://www.something.com/videos/JohnsAwesomeVideo.flv', 'http://www.something.com/videos/JohnsAwesomeCaption.xml', '/videos/video-splash-image.gif')";
echo preg_replace("~(?<=')[^']+\.xml(?=')~", "", $str);

OUTPUT (from both)

loadMedia('mediacontainer1', 'http://www.something.com/videos/JohnsAwesomeVideo.flv', '', '/videos/video-splash-image.gif')

EDIT

Use following Java code to break the string into 2 parts as per your comments:

Pattern p = Pattern.compile("^(.*)(?<=')[^']+\\.xml(?=')(.*)$");
Matcher m = p.matcher(str);
if (m.find())
   System.out.println("Output: " + m.group(1) + "<br /><br />" + m.group(2));

OUTPUT

Matched: loadMedia('mediacontainer1', 'http://www.something.com/videos/JohnsAwesomeVideo.flv', '<br /><br />', '/videos/video-splash-image.gif')


问:
Django SearchFilter is displaying all the data when the search field is empty
I have implemented search feature using Django SearchFilter DRF which is perfectly working but the issue is I don't want to display all the query when I pass nothing in the search field. It is by default returning all the query. I don't know how to handle it.

views.py

```<code>    class EventSearchView(generics.ListAPIView):
          permission_classes = (AllowAny,)
          queryset = Event.objects.all()
          search_fields = ["name", "description","content"]
          filter_backends = (filters.SearchFilter,)
          serializer_class = EventSearchSerializer
          pagination_class = LargeResultsSetPagination
</code>```

When I search for fields "name", "description" it is working fine but when I search nothing and hit the url without search fields by default it is returning all the query, but I want to display nothing.

How can I achieve that?

答:
Try to override get_queryset method to check if query_params contains data or not:

```<code>class EventSearchView(generics.ListAPIView):
    permission_classes = (AllowAny,)
    search_fields = ["name", "description","content"]
    filter_backends = (filters.SearchFilter,)
    serializer_class = EventSearchSerializer
    pagination_class = LargeResultsSetPagination

    def get_queryset(self):
        if self.request.query_params:
            return Event.objects.all()
    return Event.objects.none()
</code>```

Body:
I have implemented search feature using Django SearchFilter DRF which is perfectly working but the issue is I don't want to display all the query when I pass nothing in the search field. It is by default returning all the query. I don't know how to handle it.

views.py

    class EventSearchView(generics.ListAPIView):
          permission_classes = (AllowAny,)
          queryset = Event.objects.all()
          search_fields = ["name", "description","content"]
          filter_backends = (filters.SearchFilter,)
          serializer_class = EventSearchSerializer
          pagination_class = LargeResultsSetPagination

When I search for fields "name", "description" it is working fine but when I search nothing and hit the url without search fields by default it is returning all the query, but I want to display nothing.

How can I achieve that?

Body:
Try to override get_queryset method to check if query_params contains data or not:

class EventSearchView(generics.ListAPIView):
    permission_classes = (AllowAny,)
    search_fields = ["name", "description","content"]
    filter_backends = (filters.SearchFilter,)
    serializer_class = EventSearchSerializer
    pagination_class = LargeResultsSetPagination

    def get_queryset(self):
        if self.request.query_params:
            return Event.objects.all()
    return Event.objects.none()


问:
Single multi-tenanted firestore or many single tenanted firestores?
I'm building a SaaS system that allows users to define their own data models and enter data according to those models.  It's a bit like airtable.

One user might model a bookshop, and would have a Book model, with title and ISBN fields.  Another user might model medical records, and would have "date of last visit" as a field.

In the case of the bookshop, I want users to be able to search on title and ISBN.  In the case of the medical records, I want users to be able to search on the date of the last visit.

I am using Firestore as my backend.

Firestore requires an index to enable a search.  So that approach will not scale as # of customers increases.

My thought therefore was to have a Firestore instance for each customer, and those specific instances would have the necessary indexes.

I'm sure there are downsides to doing this though.

What would folks recommend to best solve this need?

答:
What you are trying to achieve is some kind of weird, since you will not provide at least a few standard common properties for each user of your Bookshop.

When you want to perform a search in a Cloud Firestore database, you need the exact name of the property on which you want to search for. Having dynamic properties might not help you solve the search feature. However, you can create a document with a property of type array that can hold the name of all properties the users have chosen and perform a search on every property, but this solution will be much too expensive.

In my opinion, a possible solution might be to create at least a few common properties, so you can have the properties on which you can search. When someone creates, for example, a book shop you can display at the beginning all available properties a user can choose. Once you create a shop, you can have different users with different shop properties. This means that if a user does not choose a property, when you perform a search on that property, the results won't contain his/her products. This will work, only if you have predefined properties.


问:
Android eclipse DDMS - Can't access data/data/ on phone to pull files
While testing my apps, I use emulators and my own phone to see if everything is working ok.  My apps are also writing data to shared preferences and a text file.

I can pull the data from my emulators through the DDMS in eclipse so I can read the data files on my computer, but when I try to open those folders through the DDMS on my phone, nothing happens.  I click the data folder and nothing happens.

My phone is rooted.  Is there any way I could pull the files from my phone?  I know that Android keeps these folders private, but there must be a way.  The emulator is just way too slow.

答:
No one seems to understand that a retail Nexus One even after being rooted still will not let you browse the file system using DDMS File Explorer. We are talking about real phones here and not the emulator. If you happen to have a Nexus One Developer Phone you can browse the file system using DDMS Filer Explorer, but a retail Nexus One that has been rooted you can't. Got it?

So I hope that answers the question of not being able to use the DDMS File Explorer to browse the file system of a rooted retail Nexus One. After rooting a retail Nexus One there is still something that remains to be done to use DDMS to use the File Explorer to browse the phones File System. I don't know what it is. Maybe someone else knowns.


问:
How to access inputs from Textfields in NativeScript and save them to variables like you can with document.getElementByID
So I'm just trying to save values from textfields to variables javascript.

I'm seeing that I should do something like this from another post

```<code>var view = require("ui/core/view");
function pageLoaded(args) {
    var page = args.object;
    var textfield= view.getViewById(page, "textfieldID");
}
</code>```

however, I do not really understand how exactly I should be using it.  where do I call pageloaded and what arguments?

答:
In nativescript angular,

We have to use two data biding for this.

in your component.html file :

```<code><TextField
    hint="username"
    [(ngModel)]='username'>
</TextField>
</code>```

in your component.ts file declare the variable username: string = '';

the [(ngModel)] is used for two way data binding so you can access the value from your textfield.

but take a note that you have to import NativeScriptFormsModule in import:[] array of your module file in order to use two way data binding.

Body:
So I'm just trying to save values from textfields to variables javascript.

I'm seeing that I should do something like this from another post

var view = require("ui/core/view");
function pageLoaded(args) {
    var page = args.object;
    var textfield= view.getViewById(page, "textfieldID");
}

however, I do not really understand how exactly I should be using it.  where do I call pageloaded and what arguments?

Body:
In nativescript angular,

We have to use two data biding for this.

in your component.html file :

<TextField
    hint="username"
    [(ngModel)]='username'>
</TextField>

in your component.ts file declare the variable username: string = '';

the [(ngModel)] is used for two way data binding so you can access the value from your textfield.

but take a note that you have to import NativeScriptFormsModule in import:[] array of your module file in order to use two way data binding.


问:
How can I stop my camera clipping through terrain?
Having a bit of a problem in Unity3D. I have a fly camera with both a box collider and rigidbody, and it still moves through my terrain, which has a terrain collider and a rigidbody. The thing is, it interacts with my capsules just fine, bounces them away and everything. Obvious this is the exact opposite of what I want ha ha...

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FlyCamera : MonoBehaviour
{.
    /*
Writen by Windexglow 11-13-10.  Use it, edit it, steal it I don't care.
Converted to C# 27-02-13 - no credit wanted.
Simple flycam I made, since I couldn't find any others made public.
Made simple to use (drag and drop, done) for regular keyboard layout
wasd : basic movement
shift : Makes camera accelerate
space : Moves camera on X and Z axis only.  So camera doesn't gain any height*/

float mainSpeed = 25.0f; //regular speed
float shiftAdd = 250.0f; //multiplied by how long shift is held.  Basically running
float maxShift = 1000.0f; //Maximum speed when holdin gshift
float camSens = 0.25f; //How sensitive it with mouse
private Vector3 lastMouse = new Vector3(255, 255, 255); //kind of in the middle of the screen, rather than at the top (play)
private float totalRun = 1.0f;

void Update()
{
    if (Input.GetKey(KeyCode.R))
    {
        transform.position = new Vector3(26f, 4f, 14f);
    }

    lastMouse = Input.mousePosition - lastMouse;
    lastMouse = new Vector3(-lastMouse.y * camSens, lastMouse.x * camSens, 0);
    lastMouse = new Vector3(transform.eulerAngles.x + lastMouse.x, transform.eulerAngles.y + lastMouse.y, 0);
    transform.eulerAngles = lastMouse;
    lastMouse = Input.mousePosition;
    //Mouse  camera angle done.

    //Keyboard commands
    float f = 0.0f;
    Vector3 p = GetBaseInput();
    if (Input.GetKey(KeyCode.LeftShift))
    {
        totalRun += Time.deltaTime;
        p = p * totalRun * shiftAdd;
        p.x = Mathf.Clamp(p.x, -maxShift, maxShift);
        p.y = Mathf.Clamp(p.y, -maxShift, maxShift);
        p.z = Mathf.Clamp(p.z, -maxShift, maxShift);
    }
    else
    {
        totalRun = Mathf.Clamp(totalRun * 0.5f, 1f, 1000f);
        p = p * mainSpeed;
    }

    p = p * Time.deltaTime;
    Vector3 newPosition = transform.position;
    if (Input.GetKey(KeyCode.Space))
    { //If player wants to move on X and Z axis only
        transform.Translate(p);
        newPosition.x = transform.position.x;
        newPosition.z = transform.position.z;
        transform.position = newPosition;
    }
    else
    {
        transform.Translate(p);
    }

}

private Vector3 GetBaseInput()
{ //returns the basic values, if it's 0 than it's not active.
    Vector3 p_Velocity = new Vector3();
    if (Input.GetKey(KeyCode.W))
    {
        if (transform.position.x > 2 && transform.position.x < 53)
        {
            if (transform.position.y > 0 && transform.position.y < 40)
            {
                if (transform.position.z > 5 && transform.position.z < 52)
                {
                    p_Velocity += new Vector3(0, 0, 1);
                }

            }

        }

    }
    if (Input.GetKey(KeyCode.S))
    {
        if (transform.position.x > 2 && transform.position.x < 53)
        {
            if (transform.position.y > 0 && transform.position.y < 40)
            {
                if (transform.position.z > 5 && transform.position.z < 52)
                {
                    p_Velocity += new Vector3(0, 0, -1);
                }

            }

        }

    }
    if (Input.GetKey(KeyCode.A))
    {
        if (transform.position.x > 2 && transform.position.x < 53)
        {
            if (transform.position.y > 0 && transform.position.y < 40)
            {
                if (transform.position.z > 5 && transform.position.z < 52)
                {
                    p_Velocity += new Vector3(-1, 0, 0);
                }

            }

        }

    }
    if (Input.GetKey(KeyCode.D))
    {
        if (transform.position.x > 2 && transform.position.x < 53)
        {
            if (transform.position.y > 0 && transform.position.y < 40)
            {
                if (transform.position.z > 5 && transform.position.z < 52)
                {
                    p_Velocity += new Vector3(1, 0, 0);
                }

            }

        }

    }
    return p_Velocity;

}
</code>```

}

This flycam isn't mine so if it's not optimal for the use I'm looking for, please notify me about that too.

答:
Basically you are. Transforming it not adding velocity thats why it is crossing the collider
You need to get reference of the rigidbody then add velocity to it
Then it won't cross the collider

You need to modify your code for that
Where you are transforming
Instead of transforming
You need to
Rigidbody.velocity= vector3(.....)

Body:
Having a bit of a problem in Unity3D. I have a fly camera with both a box collider and rigidbody, and it still moves through my terrain, which has a terrain collider and a rigidbody. The thing is, it interacts with my capsules just fine, bounces them away and everything. Obvious this is the exact opposite of what I want ha ha...

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FlyCamera : MonoBehaviour
{.
    /*
Writen by Windexglow 11-13-10.  Use it, edit it, steal it I don't care.
Converted to C# 27-02-13 - no credit wanted.
Simple flycam I made, since I couldn't find any others made public.
Made simple to use (drag and drop, done) for regular keyboard layout
wasd : basic movement
shift : Makes camera accelerate
space : Moves camera on X and Z axis only.  So camera doesn't gain any height*/

float mainSpeed = 25.0f; //regular speed
float shiftAdd = 250.0f; //multiplied by how long shift is held.  Basically running
float maxShift = 1000.0f; //Maximum speed when holdin gshift
float camSens = 0.25f; //How sensitive it with mouse
private Vector3 lastMouse = new Vector3(255, 255, 255); //kind of in the middle of the screen, rather than at the top (play)
private float totalRun = 1.0f;

void Update()
{
    if (Input.GetKey(KeyCode.R))
    {
        transform.position = new Vector3(26f, 4f, 14f);
    }

    lastMouse = Input.mousePosition - lastMouse;
    lastMouse = new Vector3(-lastMouse.y * camSens, lastMouse.x * camSens, 0);
    lastMouse = new Vector3(transform.eulerAngles.x + lastMouse.x, transform.eulerAngles.y + lastMouse.y, 0);
    transform.eulerAngles = lastMouse;
    lastMouse = Input.mousePosition;
    //Mouse  camera angle done.

    //Keyboard commands
    float f = 0.0f;
    Vector3 p = GetBaseInput();
    if (Input.GetKey(KeyCode.LeftShift))
    {
        totalRun += Time.deltaTime;
        p = p * totalRun * shiftAdd;
        p.x = Mathf.Clamp(p.x, -maxShift, maxShift);
        p.y = Mathf.Clamp(p.y, -maxShift, maxShift);
        p.z = Mathf.Clamp(p.z, -maxShift, maxShift);
    }
    else
    {
        totalRun = Mathf.Clamp(totalRun * 0.5f, 1f, 1000f);
        p = p * mainSpeed;
    }

    p = p * Time.deltaTime;
    Vector3 newPosition = transform.position;
    if (Input.GetKey(KeyCode.Space))
    { //If player wants to move on X and Z axis only
        transform.Translate(p);
        newPosition.x = transform.position.x;
        newPosition.z = transform.position.z;
        transform.position = newPosition;
    }
    else
    {
        transform.Translate(p);
    }

}

private Vector3 GetBaseInput()
{ //returns the basic values, if it's 0 than it's not active.
    Vector3 p_Velocity = new Vector3();
    if (Input.GetKey(KeyCode.W))
    {
        if (transform.position.x > 2 && transform.position.x < 53)
        {
            if (transform.position.y > 0 && transform.position.y < 40)
            {
                if (transform.position.z > 5 && transform.position.z < 52)
                {
                    p_Velocity += new Vector3(0, 0, 1);
                }

            }

        }

    }
    if (Input.GetKey(KeyCode.S))
    {
        if (transform.position.x > 2 && transform.position.x < 53)
        {
            if (transform.position.y > 0 && transform.position.y < 40)
            {
                if (transform.position.z > 5 && transform.position.z < 52)
                {
                    p_Velocity += new Vector3(0, 0, -1);
                }

            }

        }

    }
    if (Input.GetKey(KeyCode.A))
    {
        if (transform.position.x > 2 && transform.position.x < 53)
        {
            if (transform.position.y > 0 && transform.position.y < 40)
            {
                if (transform.position.z > 5 && transform.position.z < 52)
                {
                    p_Velocity += new Vector3(-1, 0, 0);
                }

            }

        }

    }
    if (Input.GetKey(KeyCode.D))
    {
        if (transform.position.x > 2 && transform.position.x < 53)
        {
            if (transform.position.y > 0 && transform.position.y < 40)
            {
                if (transform.position.z > 5 && transform.position.z < 52)
                {
                    p_Velocity += new Vector3(1, 0, 0);
                }

            }

        }

    }
    return p_Velocity;

}

}

This flycam isn't mine so if it's not optimal for the use I'm looking for, please notify me about that too.


问:
Trouble Writing back to text file using PHP fwrite from file selected from a dropdown form
I am having trouble writing back to a text file selected from a html form with a dropdown menu, the script is able to read but is unable to write back, returns "Unable to Open File".using PHP fopen and fwrite

This is the index.html code:

```<code><html>
<head></head>
<title>Edit Server Side Text Files</title>
<body>
<form action="function.php" method="post">
<select name="list">
  <option value="./files/banned-kdf.txt">banned-kdf.txt</option>
  <option value="./files/blackList.txt">blackList.txt</option>
</select>
<input type="submit" name="edit" value="Edit" />
</form>
</body>
</html>
</code>```

And this is the function.php code:

```<code><?php

if(isset($_POST["edit"])) {
   $filename = $_POST["list"];
   global $filename;
//   var_dump($filename);
   $myfile = fopen("$filename", "r") or die("Unable to open file!");
   $filecontent =  fread($myfile,filesize("$filename"));
   fclose($myfile);
 }
?>
<html>
<form action="<?php echo $PHP_SELF;?>" method="post">
<textarea name="textareaContent" rows="50" cols="100">
<?

if(isset($filecontent)) { echo $filecontent; }

?>
</textarea>
<br>
<br>
<input type="submit" name="update" value="Update" />
 </textarea>
<?
//write to text file
 if(isset($_POST["update"])) {
// The following two lines are just for troubleshooting and have been commented out.
//   echo $_POST["update"];
//   var_dump($filename);
   $myfile = fopen("$filename", "w") or die("Unable to open file!");
   fwrite($myfile, $_POST["textareaContent"]);
   fclose($myfile);
 }
 ?>

 </form>
 <br>
 <br>
<a href="/index.html">Return to List Selection</a>
</html>
</code>```

答:
You're not sending file name in the second form, just code, so, $filename is undefined. Add it in an input hidden:

global $variable; is not useful here, because the variable will not be present on next script execution, when processing the form.

```<code><?php

// Default value for contents:
$filecontent = '';

// Ok, read the file here
if(isset($_POST["edit"])) {
   $filename = $_POST["list"];

   global $filename; // This will not be useful

   $myfile = fopen("$filename", "r") or die("Unable to open file!");
   $filecontent =  fread($myfile,filesize("$filename"));
   fclose($myfile);
 }
// If request comes from second form, process it
if(isset($_POST['update'])) {
   // Get file name from input hidden
   $filename = $_POST["filename"];

   $myfile = fopen("$filename", "w") or die("Unable to open file!");
   fwrite($myfile, $_POST["textareaContent"]);
   fclose($myfile);
   // End the script, no need to show the form again
   die('File updated successfully.');
}
?>
<html>
<form action="<?php echo $PHP_SELF;?>" method="post">
<input type="hidden" name="filename" value ="<?php
    // Send filename within form
    echo $filename;
?>">
<textarea name="textareaContent" rows="50" cols="100">
<?
// No if needed here, we already have a value
echo $filecontent;
?>
</textarea>
<br>
<br>
<input type="submit" name="update" value="Update" />

 </form>
 <br>
 <br>
<a href="/index.html">Return to List Selection</a>
</html>
</code>```

Body:
I am having trouble writing back to a text file selected from a html form with a dropdown menu, the script is able to read but is unable to write back, returns "Unable to Open File".using PHP fopen and fwrite

This is the index.html code:

<title>Edit Server Side Text Files</title>

<form action="function.php" method="post">
<select name="list">
  <option value="./files/banned-kdf.txt">banned-kdf.txt</option>
  <option value="./files/blackList.txt">blackList.txt</option>
</select>
<input type="submit" name="edit" value="Edit" />
</form>

And this is the function.php code:

<?php

if(isset($_POST["edit"])) {
   $filename = $_POST["list"];
   global $filename;
//   var_dump($filename);
   $myfile = fopen("$filename", "r") or die("Unable to open file!");
   $filecontent =  fread($myfile,filesize("$filename"));
   fclose($myfile);
 }
?>

<form action="<?php echo $PHP_SELF;?>" method="post">
<textarea name="textareaContent" rows="50" cols="100">
<?

if(isset($filecontent)) { echo $filecontent; }

?>
</textarea>

<input type="submit" name="update" value="Update" />
 </textarea>
<?
//write to text file
 if(isset($_POST["update"])) {
// The following two lines are just for troubleshooting and have been commented out.
//   echo $_POST["update"];
//   var_dump($filename);
   $myfile = fopen("$filename", "w") or die("Unable to open file!");
   fwrite($myfile, $_POST["textareaContent"]);
   fclose($myfile);
 }
 ?>

 </form>

Return to List Selection

Body:
You're not sending file name in the second form, just code, so, $filename is undefined. Add it in an input hidden:

global $variable; is not useful here, because the variable will not be present on next script execution, when processing the form.

<?php

// Default value for contents:
$filecontent = '';

// Ok, read the file here
if(isset($_POST["edit"])) {
   $filename = $_POST["list"];

   global $filename; // This will not be useful

   $myfile = fopen("$filename", "r") or die("Unable to open file!");
   $filecontent =  fread($myfile,filesize("$filename"));
   fclose($myfile);
 }
// If request comes from second form, process it
if(isset($_POST['update'])) {
   // Get file name from input hidden
   $filename = $_POST["filename"];

   $myfile = fopen("$filename", "w") or die("Unable to open file!");
   fwrite($myfile, $_POST["textareaContent"]);
   fclose($myfile);
   // End the script, no need to show the form again
   die('File updated successfully.');
}
?>
<html>
<form action="<?php echo $PHP_SELF;?>" method="post">
<input type="hidden" name="filename" value ="<?php
    // Send filename within form
    echo $filename;
?>">
<textarea name="textareaContent" rows="50" cols="100">
<?
// No if needed here, we already have a value
echo $filecontent;
?>
</textarea>
<br>
<br>
<input type="submit" name="update" value="Update" />

 </form>
 <br>
 <br>
<a href="/index.html">Return to List Selection</a>
</html>


问:
TensorRT - TensorFlow deserialization fails with Serialization Error in verifyHeader
I'm running the nvcr.io/nvidia/tensorflow:19.12-tf2-py3 docker image with the following runtime information:

Tensorflow 2.0.0  (tf.__version__)

Python 3.6 (!python --version)

TensorRT 6.0.1 (!dpkg -l | grep nvinfer)

cuda 10.2

I have built a model in TensorFlow 2.0 and converted+saved it to a dir:

```<code>1/
├── assets/
|   └── trt-serialized-engine.TRTEngineOp_0
├── variables/
|   ├── variables.data-00000-of-00002
|   ├── variables.data-00001-of-00002
|   └── variables.index
└── saved_model.pb

</code>```

Now when I try deserializing the cuda engine with the TensorRT python API:

import tensorrt as trt
TRT_LOGGER = trt.Logger(trt.Logger.VERBOSE)

serialized_engine = './tmp/unet-FP32/1/assets/trt-serialized-engine.TRTEngineOp_0'
# serialized_engine = './tmp/unet-FP32/1/saved_model.pb'

trt_runtime = trt.Runtime(TRT_LOGGER)

with open(serialized_engine, 'rb') as f:
    engine = trt_runtime.deserialize_cuda_engine(f.read())
```

<p>I receive the following error messages:</p>

```[TensorRT] ERROR: ../rtSafe/coreReadArchive.cpp (31) - Serialization Error in verifyHeader: 0 (Magic tag does not match)
[TensorRT] ERROR: INVALID_STATE: std::exception
[TensorRT] ERROR: INVALID_CONFIG: Deserialize the cuda engine failed.
```

I do the saving and loading on the exact same machine, inside the exact same docker container. Am I wrong to assume that 'trt-serialized-engine.TRTEngineOp_0' contains the actual serialized model?

I have also tried doing it with the uff-parserm, but the uff shipped in the NVidia container is incompatible with tensorflow 2.0.

Any ideas how to deserialize my trt engine?

答: If the engine was created and ran on different versions, this may happen. TensorRT engines are not compatible across different TensorRT versions. Go to this reference for more info.</p>

Body:
I'm running the nvcr.io/nvidia/tensorflow:19.12-tf2-py3 docker image with the following runtime information:

Tensorflow 2.0.0  (tf.__version__)

Python 3.6 (!python --version)

TensorRT 6.0.1 (!dpkg -l | grep nvinfer)

cuda 10.2

I have built a model in TensorFlow 2.0 and converted+saved it to a dir:

1/
├── assets/
|   └── trt-serialized-engine.TRTEngineOp_0
├── variables/
|   ├── variables.data-00000-of-00002
|   ├── variables.data-00001-of-00002
|   └── variables.index
└── saved_model.pb

Now when I try deserializing the cuda engine with the TensorRT python API:

import tensorrt as trt
TRT_LOGGER = trt.Logger(trt.Logger.VERBOSE)

serialized_engine = './tmp/unet-FP32/1/assets/trt-serialized-engine.TRTEngineOp_0'
# serialized_engine = './tmp/unet-FP32/1/saved_model.pb'

trt_runtime = trt.Runtime(TRT_LOGGER)

with open(serialized_engine, 'rb') as f:
    engine = trt_runtime.deserialize_cuda_engine(f.read())

I receive the following error messages:

[TensorRT] ERROR: ../rtSafe/coreReadArchive.cpp (31) - Serialization Error in verifyHeader: 0 (Magic tag does not match)
[TensorRT] ERROR: INVALID_STATE: std::exception
[TensorRT] ERROR: INVALID_CONFIG: Deserialize the cuda engine failed.

I do the saving and loading on the exact same machine, inside the exact same docker container. Am I wrong to assume that 'trt-serialized-engine.TRTEngineOp_0' contains the actual serialized model?

I have also tried doing it with the uff-parserm, but the uff shipped in the NVidia container is incompatible with tensorflow 2.0.

Any ideas how to deserialize my trt engine?


问:
Package 'python-pybabel' has no installation candidate
I do install odoo version 8 in ubuntu version 16 ,
then I  doing like this link https://www.getopenerp.com/easy-odoo8-installation/
. In step 3 , it is wrong  it say "E:Package 'python-pybabel' has no installation candidate". what happens?</p>

答:
This python-pybabel has been replaced by another package called python-babel. So try:

```<code>$ sudo apt-get install python-babel
</code>```

This should work

Body:
This python-pybabel has been replaced by another package called python-babel. So try:

$ sudo apt-get install python-babel

This should work


问:
Lift a key’s values to top level whilst preserving rest of object using Ramda
I would like to build it into my compose function so that record’s values go to the top level of the object, whilst the rest of the keys stay in tact:

```<code>{
  record: {
    seasons: [
      1
    ],
    colors: [
      2
    ]
  },
  tag_ids: [
    2091
  ]
}
</code>```

The result I am after:

```<code>{
  seasons: [
    1
  ],
  colors: [
    2
  ],
  tag_ids: [
    2091
  ]
}
</code>```

Any of the keys may or may not exist.

I have always scratched my head with the ramda way to do it in a compose function. Currently I am looking at toPairs and doing some pretty long winded transforms with no luck.

答:
This may be simpler in plain JS rather than Ramda:

```<code>const data = { record: { seasons: [1], colors: [2] }, tag_ids: [2091] }

const flattenRecord = ({record = {}, ...rest}) => ({...record, ...rest})

flattenRecord(data) //=> {"colors": [2], "seasons": [1], "tag_ids": [2091]}
</code>```

If you would still like to utilise Ramda for the solution, consider looking into R.mergeLeft (or R.mergeRight) and R.omit.

Body:
I would like to build it into my compose function so that record’s values go to the top level of the object, whilst the rest of the keys stay in tact:

{
  record: {
    seasons: [
      1
    ],
    colors: [
      2
    ]
  },
  tag_ids: [
    2091
  ]
}

The result I am after:

{
  seasons: [
    1
  ],
  colors: [
    2
  ],
  tag_ids: [
    2091
  ]
}

Any of the keys may or may not exist.

I have always scratched my head with the ramda way to do it in a compose function. Currently I am looking at toPairs and doing some pretty long winded transforms with no luck.

Body:
This may be simpler in plain JS rather than Ramda:

const data = { record: { seasons: [1], colors: [2] }, tag_ids: [2091] }

const flattenRecord = ({record = {}, ...rest}) => ({...record, ...rest})

flattenRecord(data) //=> {"colors": [2], "seasons": [1], "tag_ids": [2091]}

If you would still like to utilise Ramda for the solution, consider looking into R.mergeLeft (or R.mergeRight) and R.omit.


问:
Convert CV Mat object to std::vector<Eigen::Vector3d> without loop
I have a RGB CV::Mat object and I want to convert it to std::vector<Eigen::Vector3d> to be used in open3d pointcloud color, is it possible to do this without loop?

Thanks.

答:
Easy, provided you go the other way around:</p>

```<code>std::vector<Eigen::Vector3d> pixel_data(height * width);
cv::Mat mat = cv::Mat(height, width, CV_64FC3, &(pixel_data[0](0)));
fill_the_matrix_as_you_wish(mat);
</code>```

Body:
Easy, provided you go the other way around:

std::vector<Eigen::Vector3d> pixel_data(height * width);
cv::Mat mat = cv::Mat(height, width, CV_64FC3, &(pixel_data[0](0)));
fill_the_matrix_as_you_wish(mat);


问:
React Native Hamburger onPress Issue
I am trying to navigate the drawer by including onPress() on the hamburger of the header but it didn't work with the navigation.toggleDrawer() function.

Here is the code :

```<code>import * as React from 'react';
import { Button, View } from 'react-native';
import { createDrawerNavigator } from '@react-navigation/drawer';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { Ionicons } from '@expo/vector-icons';

function HomeScreen({ navigation }) {

  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>

      <Button
        onPress={() => navigation.navigate('Notifications')}
        title="Go to notifications"
      />
    </View>
  );
}

function NotificationsScreen({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Button onPress={() => navigation.navigate('Home')} title="Go back home" />
    </View>
  );
}

const Drawer = createDrawerNavigator();

function draw() {
  return (

      <Drawer.Navigator initialRouteName="Home" >
        <Drawer.Screen name="Home" component={HomeScreen}
        options={{
        drawerIcon: () => <Ionicons name='md-home' size={30} color='#130f40' />,
          }}
         />
        <Drawer.Screen name="Notifications" component={NotificationsScreen}
        options={{
        drawerIcon: () => <Ionicons name='md-notifications' size={30} color='#130f40' />,
          }}
         />
      </Drawer.Navigator>

  );
}

const Stack = createStackNavigator();

function Def(){
  return (
    <NavigationContainer>
    <Stack.Navigator>
    <Stack.Screen
        name="Home"
        component={draw}
        options={{
          title: 'My home',
          headerStyle: {
            backgroundColor: '#5f27cd',
          },
          headerTintColor: '#fff',
          headerTitleStyle: {
            fontWeight: 'bold',
          },

          headerLeft: () =>  (<Ionicons name='md-menu' style={{paddingLeft: "20px"}} size={30} color='white' onPress={() => navigation.toggleDrawer()} />),

        }}

      />
    </Stack.Navigator>
    </NavigationContainer>
  )
}

export default Def;
</code>```

I had added the navigation.toggleDrawer() function in Ionicons with onPress() function but it didn't work. Error says navigation is not define.

答:
Try this

```<code> headerLeft: ({navigation}) =>  (<Ionicons name='md-menu' style={{paddingLeft: "20px"}} size={30} color='white' onPress={() => navigation.toggleDrawer()} />)
</code>```

Hope it helps

Title: React Native Hamburger onPress Issue

Body:
I am trying to navigate the drawer by including onPress() on the hamburger of the header but it didn't work with the navigation.toggleDrawer() function.

Here is the code :

import * as React from 'react';
import { Button, View } from 'react-native';
import { createDrawerNavigator } from '@react-navigation/drawer';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { Ionicons } from '@expo/vector-icons';

function HomeScreen({ navigation }) {

  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>

      <Button
        onPress={() => navigation.navigate('Notifications')}
        title="Go to notifications"
      />
    </View>
  );
}

function NotificationsScreen({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Button onPress={() => navigation.navigate('Home')} title="Go back home" />
    </View>
  );
}

const Drawer = createDrawerNavigator();

function draw() {
  return (

      <Drawer.Navigator initialRouteName="Home" >
        <Drawer.Screen name="Home" component={HomeScreen}
        options={{
        drawerIcon: () => <Ionicons name='md-home' size={30} color='#130f40' />,
          }}
         />
        <Drawer.Screen name="Notifications" component={NotificationsScreen}
        options={{
        drawerIcon: () => <Ionicons name='md-notifications' size={30} color='#130f40' />,
          }}
         />
      </Drawer.Navigator>

  );
}

const Stack = createStackNavigator();

function Def(){
  return (
    <NavigationContainer>
    <Stack.Navigator>
    <Stack.Screen
        name="Home"
        component={draw}
        options={{
          title: 'My home',
          headerStyle: {
            backgroundColor: '#5f27cd',
          },
          headerTintColor: '#fff',
          headerTitleStyle: {
            fontWeight: 'bold',
          },

          headerLeft: () =>  (<Ionicons name='md-menu' style={{paddingLeft: "20px"}} size={30} color='white' onPress={() => navigation.toggleDrawer()} />),

        }}

      />
    </Stack.Navigator>
    </NavigationContainer>
  )
}

export default Def;

I had added the navigation.toggleDrawer() function in Ionicons with onPress() function but it didn't work. Error says navigation is not define.

Body:
Try this

 headerLeft: ({navigation}) =>  (<Ionicons name='md-menu' style={{paddingLeft: "20px"}} size={30} color='white' onPress={() => navigation.toggleDrawer()} />)

Hope it helps


问:
How to retrieve a list of contacts that belong to a specific group without limit error
I am unable to read contacts of a group.

I use the method contactGroups.List (https://people.googleapis.com/v1/contactGroups) to read all groups.

Then I read all the contacts with the supplied resource names for the given group with the people.get method (https://people.googleapis.com/v1/resourceName).

This works, but since a request is required for every contact, I immediately get the error:

Quota exceeded for quota metric 'Read requests' and limit 'Read requests per minute per user' of service 'people.googleapis.com' for consumer.

The limit is 75 requests / 60s / user.

Is there another way?

答:
You could wrap your request with a try/catch and repeat the call after 2sec if a HttpError with code 429 (limit reached) is raised.

I'm not sure what language you are using so here is something generic.

```<code>Function my_call(request):
    Try:
        Return request.execute()
    Catch HttpError as error:
        If error.resp.status == 429:
            sleep(2sec)
            Return my_call(request)
        Else:
            Raise error
</code>```

Where the request is built by the people.get method and the HttpError can be included from the googleapi module/library I believe.

Note that it would probably be more efficient (API calls wise) to use the people.connection.list method and retrieve
the contacts from the response instead.

Body:
You could wrap your request with a try/catch and repeat the call after 2sec if a HttpError with code 429 (limit reached) is raised.

I'm not sure what language you are using so here is something generic.

Function my_call(request):
    Try:
        Return request.execute()
    Catch HttpError as error:
        If error.resp.status == 429:
            sleep(2sec)
            Return my_call(request)
        Else:
            Raise error

Where the request is built by the people.get method and the HttpError can be included from the googleapi module/library I believe.

Note that it would probably be more efficient (API calls wise) to use the people.connection.list method and retrieve
the contacts from the response instead.


问:
xsl to convert xml to json
Input XML

```<code><Root>
    <Result>
        <System>
            <Name>ABC</Name>
            <ID pname="PAD">
                <value>4567</value>
            </ID>
            <lastTime>2013-11-06T17:36:46.000-05:00</lastTime>
        </System>
        <line>Metals</line>
    </Result>
    <Result>
        <System>
            <Name>CAYS</Name>
            <ID pname="PAD">
                <value>MCIERT</value>
            </ID>
            <ID pname="ATPAD">
                <value>56412</value>
            </ID>
            <lastTime>2013-12-06T16:43:36.000-05:00</lastTime>
        </System>
        <System>
            <Name>CAYS</Name>
            <ID pname="CAD">
                <value>DGSG</value>
            </ID>
            <ID pname="ARCAD">
                <value>2847114</value>
            </ID>
            <lastTime>2013-12-07T20:02:38.000-05:00</lastTime>
        </System>
        <line>Minerals</line>
    </Result>
</Root>
</code>```

Output Json

```<code>{
"Root": {
"Result": [
  {
    "System": {
      "Name": "ABC",
      "ID": {
        "pname": "PAD",
        "value": "4567"
      },
      "lastTime": "2013-11-06T17:36:46.000-05:00"
    },
    "line": "Metals"
  },
  {
    "System": [
      {
        "Name": "CAYS",
        "ID": [
          {
            "pname": "PAD",
            "value": "MCIERT"
          },
          {
            "pname": "ATPAD",
            "value": "56412"
          }
        ],
        "lastTime": "2013-12-06T16:43:36.000-05:00"
      },
      {
        "Name": "CAYS",
        "ID": [
          {
            "pname": "CAD",
            "value": "DGSG"
          },
          {
            "pname": "ARCAD",
            "value": "2847114"
          }
        ],
        "lastTime": "2013-12-07T20:02:38.000-05:00"
      }
    ],
    "line": "Minerals"
  }
]
}
}
</code>```

How to write the generic xslt stylesheet which will  convert input xml to json

Input might have so many Results under root, Systems and Names under results and also ID name and the values under  systems.

答:
@sancelot posted a comment with a link to a github stylesheet which I tested alongside the answered instance (I upvoted).  Additional detail here to show the following examples.

Example XML:

```<code><avpList>
  <eComStringAttributeValuePairList attributeName="orderTypeCode" qualifierCodeName="order" qualifierCodeList="OrderTypeCode" qualifierCodeListVersion="2">220</eComStringAttributeValuePairList>
  <eComStringAttributeValuePairList attributeName="orderPriority">647</eComStringAttributeValuePairList>
  <eComStringAttributeValuePairList attributeName="customerDocumentReference">0</eComStringAttributeValuePairList>
</avpList>
</code>```

If I have a mixed attribute node value and use the upvoted answer I get the following output:

```<code>            "avpList": {
            "eComStringAttributeValuePairList": [
                {
                    "attributeName": "orderTypeCode",
                    "qualifierCodeName": "order",
                    "qualifierCodeList": "OrderTypeCode",
                    "qualifierCodeListVersion": "2",
                },
                {
                    "attributeName": "orderPriority",
                },
                {
                    "attributeName": "customerDocumentReference",
                }
            ]
        }
</code>```

Running it though JSONLint shows the issues with the trailing commas in addition to the missing element value.

```<code>Error: Parse error on line 30: ...Version": "2",                    }
</code>```

Scripts parsed using XML Spy 2019.

Using the commented Github link and parsing produces the following JSON which validates on first pass through the linter.  Please note that if you're expected any form of typed data in your JSON, neither stylesheets do it.

```<code>            "avpList": {
            "eComStringAttributeValuePairList": [
                {
                    "attributeName": "orderTypeCode",
                    "qualifierCodeName": "order",
                    "qualifierCodeList": "OrderTypeCode",
                    "qualifierCodeListVersion": "2",
                    "text": "220"
                },
                {
                    "attributeName": "orderPriority",
                    "text": "647"
                },
                {
                    "attributeName": "customerDocumentReference",
                    "text": "0"
                }
            ]
        }
</code>```

Title: xsl to convert xml to json

Body:
Input XML

<Root>
    <Result>
        <System>
            <Name>ABC</Name>
            <ID pname="PAD">
                <value>4567</value>
            </ID>
            <lastTime>2013-11-06T17:36:46.000-05:00</lastTime>
        </System>
        <line>Metals</line>
    </Result>
    <Result>
        <System>
            <Name>CAYS</Name>
            <ID pname="PAD">
                <value>MCIERT</value>
            </ID>
            <ID pname="ATPAD">
                <value>56412</value>
            </ID>
            <lastTime>2013-12-06T16:43:36.000-05:00</lastTime>
        </System>
        <System>
            <Name>CAYS</Name>
            <ID pname="CAD">
                <value>DGSG</value>
            </ID>
            <ID pname="ARCAD">
                <value>2847114</value>
            </ID>
            <lastTime>2013-12-07T20:02:38.000-05:00</lastTime>
        </System>
        <line>Minerals</line>
    </Result>
</Root>

Output Json

{
"Root": {
"Result": [
  {
    "System": {
      "Name": "ABC",
      "ID": {
        "pname": "PAD",
        "value": "4567"
      },
      "lastTime": "2013-11-06T17:36:46.000-05:00"
    },
    "line": "Metals"
  },
  {
    "System": [
      {
        "Name": "CAYS",
        "ID": [
          {
            "pname": "PAD",
            "value": "MCIERT"
          },
          {
            "pname": "ATPAD",
            "value": "56412"
          }
        ],
        "lastTime": "2013-12-06T16:43:36.000-05:00"
      },
      {
        "Name": "CAYS",
        "ID": [
          {
            "pname": "CAD",
            "value": "DGSG"
          },
          {
            "pname": "ARCAD",
            "value": "2847114"
          }
        ],
        "lastTime": "2013-12-07T20:02:38.000-05:00"
      }
    ],
    "line": "Minerals"
  }
]
}
}

How to write the generic xslt stylesheet which will  convert input xml to json

Input might have so many Results under root, Systems and Names under results and also ID name and the values under  systems.

Body:
@sancelot posted a comment with a link to a github stylesheet which I tested alongside the answered instance (I upvoted).  Additional detail here to show the following examples.

Example XML:

<avpList>
  <eComStringAttributeValuePairList attributeName="orderTypeCode" qualifierCodeName="order" qualifierCodeList="OrderTypeCode" qualifierCodeListVersion="2">220</eComStringAttributeValuePairList>
  <eComStringAttributeValuePairList attributeName="orderPriority">647</eComStringAttributeValuePairList>
  <eComStringAttributeValuePairList attributeName="customerDocumentReference">0</eComStringAttributeValuePairList>
</avpList>

If I have a mixed attribute node value and use the upvoted answer I get the following output:

            "avpList": {
            "eComStringAttributeValuePairList": [
                {
                    "attributeName": "orderTypeCode",
                    "qualifierCodeName": "order",
                    "qualifierCodeList": "OrderTypeCode",
                    "qualifierCodeListVersion": "2",
                },
                {
                    "attributeName": "orderPriority",
                },
                {
                    "attributeName": "customerDocumentReference",
                }
            ]
        }

Running it though JSONLint shows the issues with the trailing commas in addition to the missing element value.

Error: Parse error on line 30: ...Version": "2",                    }

Scripts parsed using XML Spy 2019.

Using the commented Github link and parsing produces the following JSON which validates on first pass through the linter.  Please note that if you're expected any form of typed data in your JSON, neither stylesheets do it.

            "avpList": {
            "eComStringAttributeValuePairList": [
                {
                    "attributeName": "orderTypeCode",
                    "qualifierCodeName": "order",
                    "qualifierCodeList": "OrderTypeCode",
                    "qualifierCodeListVersion": "2",
                    "text": "220"
                },
                {
                    "attributeName": "orderPriority",
                    "text": "647"
                },
                {
                    "attributeName": "customerDocumentReference",
                    "text": "0"
                }
            ]
        }


问:
Remove "trace" field from ResponseStatusException
In my spring  controller I return a ResponseStatusException if no entity is found, like this:

```<code>@GetMapping("/categories/{id}")
  public ResponseEntity<Category> getCategoryById(@PathVariable(value = "id") String id) {
    try {
      return new ResponseEntity<Category>(categoryService.findById(id), HttpStatus.OK);
    } catch (CategoryNotFoundException ex) {
      throw new ResponseStatusException(HttpStatus.NOT_FOUND, ex.getMessage());
    }
  }
</code>```

I would expect the answer to be something like:

```<code>{
    "timestamp": "2019-02-22T12:25:29.913+0000",
    "status": 404,
    "error": "Not Found",
    "message": "could not find category with ID: XYZ'.",
    "path": "/categories/XYZ"
}
</code>```

But the response also includes a long field "trace" with the nested exception.

Is there a way to get rid of the trace field?

答:
Open application.properties and add the below line:

```<code>server.error.include-stacktrace=never
</code>```

Body:
In my spring  controller I return a ResponseStatusException if no entity is found, like this:

@GetMapping("/categories/{id}")
  public ResponseEntity<Category> getCategoryById(@PathVariable(value = "id") String id) {
    try {
      return new ResponseEntity<Category>(categoryService.findById(id), HttpStatus.OK);
    } catch (CategoryNotFoundException ex) {
      throw new ResponseStatusException(HttpStatus.NOT_FOUND, ex.getMessage());
    }
  }

I would expect the answer to be something like:

{
    "timestamp": "2019-02-22T12:25:29.913+0000",
    "status": 404,
    "error": "Not Found",
    "message": "could not find category with ID: XYZ'.",
    "path": "/categories/XYZ"
}

But the response also includes a long field "trace" with the nested exception.

Is there a way to get rid of the trace field?

Body:
Open application.properties and add the below line:

server.error.include-stacktrace=never


问:
How to make 3D carousel rotate automatically, no clicks required and stop at mouse hover
I found this 3D carousel online and wondering how to make it rotate infinitely without clicking buttons and stops at mouse hover, then continues to rotate again when there is no hover.

```<code>var carousel = $(".carousel"),
    currdeg  = 0;

$(".next").on("click", { d: "n" }, rotate);
$(".prev").on("click", { d: "p" }, rotate);

function rotate(e){
  if(e.data.d=="n"){
    currdeg = currdeg - 60;
  }
  if(e.data.d=="p"){
    currdeg = currdeg + 60;
  }
  carousel.css({
    "-webkit-transform": "rotateY("+currdeg+"deg)",
    "-moz-transform": "rotateY("+currdeg+"deg)",
    "-o-transform": "rotateY("+currdeg+"deg)",
    "transform": "rotateY("+currdeg+"deg)"
  });
}
</code>```

Here is a codepen

答:
I think this is what you want, just used setInterval() to trigger the animation:

var carousel = $(".carousel"),
    currdeg  = 0;

setInterval(rotate, 1000);

function rotate(e){
  currdeg = currdeg - 60
  /*if(e.data.d=="n"){
    currdeg = currdeg - 60;
  }
  if(e.data.d=="p"){
    currdeg = currdeg + 60;
  }*/
  carousel.css({
    "-webkit-transform": "rotateY("+currdeg+"deg)",
    "-moz-transform": "rotateY("+currdeg+"deg)",
    "-o-transform": "rotateY("+currdeg+"deg)",
    "transform": "rotateY("+currdeg+"deg)"
  });
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background: #333;
  padding: 70px 0;
  font: 15px/20px Arial, sans-serif;
}

.container {
  margin: 0 auto;
  width: 250px;
  height: 200px;
  position: relative;
  perspective: 1000px;
}

.carousel {
  height: 100%;
  width: 100%;
  position: absolute;
  transform-style: preserve-3d;
  transition: transform 1s;
}

.item {
  display: block;
  position: absolute;
  background: #000;
  width: 250px;
  height: 200px;
  line-height: 200px;
  font-size: 5em;
  text-align: center;
  color: #FFF;
  opacity: 0.95;
  border-radius: 10px;
}

.a {
  transform: rotateY(0deg) translateZ(250px);
  background: #ed1c24;
}
.b {
  transform: rotateY(60deg) translateZ(250px);
  background: #0072bc;
}
.c {
  transform: rotateY(120deg) translateZ(250px);
  background: #39b54a;
}
.d {
  transform: rotateY(180deg) translateZ(250px);
  background: #f26522;
}
.e {
  transform: rotateY(240deg) translateZ(250px);
  background: #630460;
}
.f {
  transform: rotateY(300deg) translateZ(250px);
  background: #8c6239;
}

.next, .prev {
  color: #444;
  position: absolute;
  top: 100px;
  padding: 1em 2em;
  cursor: pointer;
  background: #CCC;
  border-radius: 5px;
  border-top: 1px solid #FFF;
  box-shadow: 0 5px 0 #999;
  transition: box-shadow 0.1s, top 0.1s;
}
.next:hover, .prev:hover { color: #000; }
.next:active, .prev:active {
  top: 104px;
  box-shadow: 0 1px 0 #999;
}
.next { right: 5em; }
.prev { left: 5em; }</code>```

A

B

C

D

E

F

```

Body:
I found this 3D carousel online and wondering how to make it rotate infinitely without clicking buttons and stops at mouse hover, then continues to rotate again when there is no hover.

var carousel = $(".carousel"),
    currdeg  = 0;

$(".next").on("click", { d: "n" }, rotate);
$(".prev").on("click", { d: "p" }, rotate);

function rotate(e){
  if(e.data.d=="n"){
    currdeg = currdeg - 60;
  }
  if(e.data.d=="p"){
    currdeg = currdeg + 60;
  }
  carousel.css({
    "-webkit-transform": "rotateY("+currdeg+"deg)",
    "-moz-transform": "rotateY("+currdeg+"deg)",
    "-o-transform": "rotateY("+currdeg+"deg)",
    "transform": "rotateY("+currdeg+"deg)"
  });
}

Here is a codepen

Body:
I think this is what you want, just used setInterval() to trigger the animation:

var carousel = $(".carousel"),
    currdeg  = 0;

setInterval(rotate, 1000);

function rotate(e){
  currdeg = currdeg - 60
  /*if(e.data.d=="n"){
    currdeg = currdeg - 60;
  }
  if(e.data.d=="p"){
    currdeg = currdeg + 60;
  }*/
  carousel.css({
    "-webkit-transform": "rotateY("+currdeg+"deg)",
    "-moz-transform": "rotateY("+currdeg+"deg)",
    "-o-transform": "rotateY("+currdeg+"deg)",
    "transform": "rotateY("+currdeg+"deg)"
  });
}

body {
  background: #333;
  padding: 70px 0;
  font: 15px/20px Arial, sans-serif;
}

.container {
  margin: 0 auto;
  width: 250px;
  height: 200px;
  position: relative;
  perspective: 1000px;
}

.carousel {
  height: 100%;
  width: 100%;
  position: absolute;
  transform-style: preserve-3d;
  transition: transform 1s;
}

.item {
  display: block;
  position: absolute;
  background: #000;
  width: 250px;
  height: 200px;
  line-height: 200px;
  font-size: 5em;
  text-align: center;
  color: #FFF;
  opacity: 0.95;
  border-radius: 10px;
}

.a {
  transform: rotateY(0deg) translateZ(250px);
  background: #ed1c24;
}
.b {
  transform: rotateY(60deg) translateZ(250px);
  background: #0072bc;
}
.c {
  transform: rotateY(120deg) translateZ(250px);
  background: #39b54a;
}
.d {
  transform: rotateY(180deg) translateZ(250px);
  background: #f26522;
}
.e {
  transform: rotateY(240deg) translateZ(250px);
  background: #630460;
}
.f {
  transform: rotateY(300deg) translateZ(250px);
  background: #8c6239;
}

.next, .prev {
  color: #444;
  position: absolute;
  top: 100px;
  padding: 1em 2em;
  cursor: pointer;
  background: #CCC;
  border-radius: 5px;
  border-top: 1px solid #FFF;
  box-shadow: 0 5px 0 #999;
  transition: box-shadow 0.1s, top 0.1s;
}
.next:hover, .prev:hover { color: #000; }
.next:active, .prev:active {
  top: 104px;
  box-shadow: 0 1px 0 #999;
}
.next { right: 5em; }
.prev { left: 5em; }

<div class="container">
  <div class="carousel">
    <div class="item a">A</div>
    <div class="item b">B</div>
    <div class="item c">C</div>
    <div class="item d">D</div>
    <div class="item e">E</div>
    <div class="item f">F</div>
  </div>
</div>
<!--<div class="next">Next</div>
<div class="prev">Prev</div>-->
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>


问:
How to have data persist in GKE kubernetes StatefulSet with postgres?
So I'm just trying to get a web app running on GKE experimentally to familiarize myself with Kubernetes and GKE.

I have a statefulSet (Postgres) with a persistent volume/ persistent volume claim which is mounted to the Postgres pod as expected.  The problem I'm having is having the Postgres data endure. If I mount the PV at var/lib/postgres the data gets overridden with each pod update. If I mount at var/lib/postgres/data I get the warning:

initdb: directory "/var/lib/postgresql/data" exists but is not empty
It contains a lost+found directory, perhaps due to it being a mount point.
Using a mount point directly as the data directory is not recommended.
Create a subdirectory under the mount point.

Using Docker alone having the volume mount point at var/lib/postgresql/data works as expected and data endures, but I don't know what to do now in GKE. How does one set this up properly?

Setup file:

```<code>---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: sm-pd-volume-claim
spec:
  storageClassName: "standard"
  accessModes:
  - ReadWriteOnce
  resources:
    requests:
      storage: 1G
---
apiVersion: "apps/v1"
kind: "StatefulSet"
metadata:
  name: "postgis-db"
  namespace: "default"
  labels:
    app: "postgis-db"
spec:
  serviceName: "postgis-db"
  replicas: 1
  selector:
    matchLabels:
      app: "postgis-db"
  template:
    metadata:
      labels:
        app: "postgis-db"
    spec:
      terminationGracePeriodSeconds: 25
      containers:
      - name: "postgis"
        image: "mdillon/postgis"
        ports:
        - containerPort: 5432
          name: postgis-port
        volumeMounts:
        - name: sm-pd-volume
          mountPath: /var/lib/postgresql/data
      volumes:
      - name: sm-pd-volume
        persistentVolumeClaim:
          claimName: sm-pd-volume-claim
</code>```

答:
You are getting this error because the postgres pod has tried to mount the data directory on / folder.  It is not recommended to do so.

You have to create subdirectory to resolve this issues on the statefulset manifest yaml files.

```<code>  volumeMounts:
    - name: sm-pd-volume
      mountPath: /var/lib/postgresql/data
      subPath: data
</code>```

Body:
So I'm just trying to get a web app running on GKE experimentally to familiarize myself with Kubernetes and GKE.

I have a statefulSet (Postgres) with a persistent volume/ persistent volume claim which is mounted to the Postgres pod as expected.  The problem I'm having is having the Postgres data endure. If I mount the PV at var/lib/postgres the data gets overridden with each pod update. If I mount at var/lib/postgres/data I get the warning:

initdb: directory "/var/lib/postgresql/data" exists but is not empty
It contains a lost+found directory, perhaps due to it being a mount point.
Using a mount point directly as the data directory is not recommended.
Create a subdirectory under the mount point.

Using Docker alone having the volume mount point at var/lib/postgresql/data works as expected and data endures, but I don't know what to do now in GKE. How does one set this up properly?

Setup file:

---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: sm-pd-volume-claim
spec:
  storageClassName: "standard"
  accessModes:
  - ReadWriteOnce
  resources:
    requests:
      storage: 1G
---
apiVersion: "apps/v1"
kind: "StatefulSet"
metadata:
  name: "postgis-db"
  namespace: "default"
  labels:
    app: "postgis-db"
spec:
  serviceName: "postgis-db"
  replicas: 1
  selector:
    matchLabels:
      app: "postgis-db"
  template:
    metadata:
      labels:
        app: "postgis-db"
    spec:
      terminationGracePeriodSeconds: 25
      containers:
      - name: "postgis"
        image: "mdillon/postgis"
        ports:
        - containerPort: 5432
          name: postgis-port
        volumeMounts:
        - name: sm-pd-volume
          mountPath: /var/lib/postgresql/data
      volumes:
      - name: sm-pd-volume
        persistentVolumeClaim:
          claimName: sm-pd-volume-claim

Body:
You are getting this error because the postgres pod has tried to mount the data directory on / folder.  It is not recommended to do so.

You have to create subdirectory to resolve this issues on the statefulset manifest yaml files.

  volumeMounts:
    - name: sm-pd-volume
      mountPath: /var/lib/postgresql/data
      subPath: data


问:
How to select hierarchical records from two tables using join
Actually I want to select matched records from two tables with hierarchical data from the first table

I have two tables:

tmpos_category table with columns (category_refid(pk),category_name,parent_ref_id). i am storing hierarchical data in it.

tmpos_menu_child table with columns (id(pk),title,category_ref_ids(fk)). category_ref_ids field from tmpos_menu_child table references the category_refid field of tmpos_category table.

this is a tmpos_category table with hierarchical categories

tmpos_menu_child table with category_ref_ids as fk refrances category(category_refid ) column

SELECT DISTINCT ct.category_name,ct.category_refid,ct.parent_ref_id
from tmpos_category ct
JOIN tmpos_menu_child tmc
ON ct.category_refid = tmc.category_ref_ids
```

Now My Question is when i join tmpos_category table and tmpos_menu_child table i will get all distinct matched category but i also want selected category parent records

答:
So when using this schema with parent_ref_id on the category table, it is going to be tough to move up the hierarchy and get all ancestor categories without writing queries that hardcode 1 join for each parent.

If you're only ever going to have 2 or 3 generations (child, parent, grandparent for example) then this is okay, but with more (or variable levels) it can get messy. One solution is to use "recursive syntax" but not all SQL implementations support it as far as I know.

Bill Karwin has an excellent slide deck that details the pros/cons of your schema (commonly referred to as "adjacency lists").

you can find that on slides 6-17 here:

https://www.slideshare.net/billkarwin/models-for-hierarchical-data

He details your problem rather nicely, and offers several other strategies for modeling hierarchies if you end up having trouble with your current schema. I personally like the last one detailed in that deck, which is called a "closure table"

EDIT

If you are in fact only trying to include one or two parent levels, then your query will look quite similar to any query joining 3 or more tables, only you will have to join the categories table to itself. It should be pretty easy to find examples of this if you google "join a table to itself" or something similar

Body:
Actually I want to select matched records from two tables with hierarchical data from the first table

I have two tables:

tmpos_category table with columns (category_refid(pk),category_name,parent_ref_id). i am storing hierarchical data in it.

tmpos_menu_child table with columns (id(pk),title,category_ref_ids(fk)). category_ref_ids field from tmpos_menu_child table references the category_refid field of tmpos_category table.

this is a tmpos_category table with hierarchical categories

tmpos_menu_child table with category_ref_ids as fk refrances category(category_refid ) column

SELECT DISTINCT ct.category_name,ct.category_refid,ct.parent_ref_id
from tmpos_category ct
JOIN tmpos_menu_child tmc
ON ct.category_refid = tmc.category_ref_ids

Now My Question is when i join tmpos_category table and tmpos_menu_child table i will get all distinct matched category but i also want selected category parent records


问:
highlight last 3 number in the string
how to highlight last 3 number in the string:
ab9c5lek94ke72koe8nsk9

i want output:

ab9c5lek94ke72koe8nsk9

i tried following:

```<code>$str = "ab9c5lek94ke72koe8nsk9";
$numbers = preg_replace('/[^0-9]/', '', $str );
$last3 = substr($numbers, -3);
$highlights = str_split($last3);
$output = preg_replace('/'.implode('|', $highlights).'/i', '<b>$0</b>', $str);

</code>```

but it highlight:

ab9c5lek94ke72koe8nsk9

答:
You can have a regex like below:

```<code>/(\d)([^\d]*)(\d)([^\d]*)(\d)([^\d]*)$/
</code>```

which is basically (\d)([^\d]*) 3 times with a $ sign at the end. It means we are matching a digit followed by 0 or more non digit characters. Note that we do need the $ sign at the end to match only last 3 digits.

Snippet:

```<code><?php

$str = "ab9c5lek94ke2koe8nsk9";

echo preg_replace('/(\d)([^\d]*)(\d)([^\d]*)(\d)([^\d]*)$/',"<b>$1</b>$2<b>$3</b>$4<b>$5</b>$6",$str);
</code>```

Demo: https://3v4l.org/PoYCG

The replacement string is just having the bold tags with group number of the matched strings which are to be highlighted.

Title: highlight last 3 number in the string

Body:
how to highlight last 3 number in the string:
ab9c5lek94ke72koe8nsk9

i want output:

ab9c5lek94ke72koe8nsk9

i tried following:

$str = "ab9c5lek94ke72koe8nsk9";
$numbers = preg_replace('/[^0-9]/', '', $str );
$last3 = substr($numbers, -3);
$highlights = str_split($last3);
$output = preg_replace('/'.implode('|', $highlights).'/i', '$0', $str);

but it highlight:

ab9c5lek94ke72koe8nsk9

Body:
You can have a regex like below:

/(\d)([^\d]*)(\d)([^\d]*)(\d)([^\d]*)$/

which is basically (\d)([^\d]*) 3 times with a $ sign at the end. It means we are matching a digit followed by 0 or more non digit characters. Note that we do need the $ sign at the end to match only last 3 digits.

Snippet:

<?php

$str = "ab9c5lek94ke2koe8nsk9";

echo preg_replace('/(\d)([^\d]*)(\d)([^\d]*)(\d)([^\d]*)$/',"<b>$1</b>$2<b>$3</b>$4<b>$5</b>$6",$str);

Demo: https://3v4l.org/PoYCG

The replacement string is just having the bold tags with group number of the matched strings which are to be highlighted.


问:
Recycler view with sqlite kotlin
I am trying to delete the SQLite DB notes and using kotlin and rendering is done by recyclerview. But my delete won't do the job, it's not deleting. Very new to this please help.

holder class

```<code>class MyHolder (Itemview : View):RecyclerView.ViewHolder(Itemview) {

var titleHolder: TextView = Itemview.findViewById(R.id.tv_title)

var descriptionHolder: TextView = Itemview.findViewById(R.id.tv_content)

var imgEditHolder: ImageView = Itemview.findViewById(R.id.im_edit)

var imgDeleteHolder: Button = Itemview.findViewById(R.id.im_delete)
}

Adapter Onbindervieewholder  method

override fun onBindViewHolder(holder: MyHolder, position: Int) {

            var Mynotes = noteLiist[position]

            holder.titleHolder.text = Mynotes.nodeTitle
            holder.descriptionHolder.text = Mynotes.nodeDescritption
            holder.imgDeleteHolder.setOnClickListener {
                View.OnClickListener {
                    val dbManager = SqlDBManager(this.context!!)
                    val selectionArgs = arrayOf(Mynotes.nodeID.toString())
                    dbManager.Delete("ID=?", selectionArgs)
                    LoadQuery("%")
                }
            }

        }

[![db manager class][1]][1]

  [1]: https://i.stack.imgur.com/D6SjZ.png
</code>```

答:
On your onClickListener after initializing your database class, do this:</p>

```<code>val data = dbManager.DatabaseHelperNotes(context).writableDatabase
data.delete("table_name","where clause",null)
</code>```

Title: Recycler view with sqlite kotlin

Body:
I am trying to delete the SQLite DB notes and using kotlin and rendering is done by recyclerview. But my delete won't do the job, it's not deleting. Very new to this please help.

holder class

class MyHolder (Itemview : View):RecyclerView.ViewHolder(Itemview) {

var titleHolder: TextView = Itemview.findViewById(R.id.tv_title)

var descriptionHolder: TextView = Itemview.findViewById(R.id.tv_content)

var imgEditHolder: ImageView = Itemview.findViewById(R.id.im_edit)

var imgDeleteHolder: Button = Itemview.findViewById(R.id.im_delete)
}

Adapter Onbindervieewholder  method

override fun onBindViewHolder(holder: MyHolder, position: Int) {

            var Mynotes = noteLiist[position]

            holder.titleHolder.text = Mynotes.nodeTitle
            holder.descriptionHolder.text = Mynotes.nodeDescritption
            holder.imgDeleteHolder.setOnClickListener {
                View.OnClickListener {
                    val dbManager = SqlDBManager(this.context!!)
                    val selectionArgs = arrayOf(Mynotes.nodeID.toString())
                    dbManager.Delete("ID=?", selectionArgs)
                    LoadQuery("%")
                }
            }

        }

[![db manager class][1]][1]

  [1]: https://i.stack.imgur.com/D6SjZ.png

Body:
On your onClickListener after initializing your database class, do this:

val data = dbManager.DatabaseHelperNotes(context).writableDatabase
data.delete("table_name","where clause",null)