问:
Read file from Amazon S3 with nodeJS and post it to another server with axios
Im trying to read a file (image) from amazon S3 and post it to another server with multipart/form.

```<code>  let imageParams = { Bucket: 'my-bucket', Key: 'imageName.jpg' };

  let formData = new FormData();

  formData.append('file', s3.getObject(imageParams).createReadStream());

  let apiResponse = await api.post("/fileUpload", formData,
    { params: { token: process.env.API_TOKEN } },
    { headers: {'Content-Type': 'multipart/form-data' } } );
</code>```

But im not managing it to work, it returns me:

```<code>Error: Request failed with status code 415
</code>```

maybe im misunderstanding how the createReadStream() works?

答:
Use concat for pipe the stream. Otherwise form data send only the first chunk of stream, and the server don't know how to handle it.

For example

```<code>const axios = require('axios');
const {S3} = require('aws-sdk');
const FormData = require('form-data');
const s3 = new S3();
var concat = require('concat-stream')

const api = axios.default.create({
    baseURL: 'http://example.com',

})

const readStream = s3.getObject({Bucket: 'bucket', Key: 'file'}).createReadStream();
readStream.pipe(concat(filebuffer => {
    const formData = new FormData();
    formData.append('file', filebuffer);
    formData.getLength((err, length) => {
        console.log(length)
        const headers = formData.getHeaders({'content-length': length})
        console.log({headers})
        return api({
            method: 'post',
            url: "/upload",
            headers: headers,
            data: formData
        })
    })

}))
</code>```

Body:
Im trying to read a file (image) from amazon S3 and post it to another server with multipart/form.

  let imageParams = { Bucket: 'my-bucket', Key: 'imageName.jpg' };

  let formData = new FormData();

  formData.append('file', s3.getObject(imageParams).createReadStream());

  let apiResponse = await api.post("/fileUpload", formData,
    { params: { token: process.env.API_TOKEN } },
    { headers: {'Content-Type': 'multipart/form-data' } } );

But im not managing it to work, it returns me:

Error: Request failed with status code 415

maybe im misunderstanding how the createReadStream() works?

Body:
Use concat for pipe the stream. Otherwise form data send only the first chunk of stream, and the server don't know how to handle it.

For example

const axios = require('axios');
const {S3} = require('aws-sdk');
const FormData = require('form-data');
const s3 = new S3();
var concat = require('concat-stream')

const api = axios.default.create({
    baseURL: 'http://example.com',

})

const readStream = s3.getObject({Bucket: 'bucket', Key: 'file'}).createReadStream();
readStream.pipe(concat(filebuffer => {
    const formData = new FormData();
    formData.append('file', filebuffer);
    formData.getLength((err, length) => {
        console.log(length)
        const headers = formData.getHeaders({'content-length': length})
        console.log({headers})
        return api({
            method: 'post',
            url: "/upload",
            headers: headers,
            data: formData
        })
    })

}))


来源: stackexchange

问:
Do I need to use PrevState even if I spread the state into a variable?
I am testing some code to try and understand the race condition regarding the use of setState().

my code can be found here

my code below:

```<code>import React from "react";

export default class App extends React.Component {
  state = {
    id: "",
    ids: [{ id: 7 }, { id: 14 }]
  };

  // here is where I create the id numbers
  uniqueIdCreatorHandler = incrementAmount => {
    let ids = [...this.state.ids];
    let highestId = 0;
    if (ids.length > 0) {
      highestId = ids
        .map(value => {
          return value.id;
        })
        .reduce((a, b) => {
          return Math.max(a, b);
        });
    }
    let newId = highestId + incrementAmount;
    ids.push({ id: newId });
    this.setState({ ids: ids });
  };

  idDeleterHanlder = currentIndex => {
    let ids = this.state.ids;
    ids.splice(currentIndex, 1);
    this.setState({ ids: ids });
  };
  //below is when I test performing the function twice, in order to figure if the result would be a race condition
  double = (firstIncrementAmount, secondIncrementAmount) => {
    this.uniqueIdCreatorHandler(firstIncrementAmount);
    this.uniqueIdCreatorHandler(secondIncrementAmount);
  };

  render() {
    let ids = this.state.ids.map((id, index) => {
      return (
        <p onClick={() => this.idDeleterHanlder(index)} key={id.id}>
          id:{id.id}
        </p>
      );
    });

    return (
      <div className="App">
        <button onClick={() => this.uniqueIdCreatorHandler(1)}>
          Push new id
        </button>
        <button onClick={() => this.double(1, 2)}>Add some Ids</button>
        <p>all ids below:</p>
        {ids}
      </div>
    );
  }
}

</code>```

when invoking the double function on the second button only the secondIncrementAmount works. You can test it by changing the argument values on the call made on the onClick method.

I think that I should somehow use prevState on this.setState in order to fix this.

How could I avoid this issue here? This matter started at CodeReview but I did not realize how could I fix this.

There is also a recommendation to spread the mapped ids into Math.max and I could not figure out how and Why to do it. Isn't the creation of the new array by mapping the spreaded key values safe enough?

答:
This isn't the most elegant solution but you can pass a callback to setState(see https://reactjs.org/docs/react-component.html#setstate).

If you modify uniqueIdCreatorHandler like this:

```<code>uniqueIdCreatorHandler = (incrementAmount, next) => {
  let ids = [...this.state.ids];
  let highestId = 0;
  if (ids.length > 0) {
    highestId = ids
      .map(value => {
        return value.id;
      })
      .reduce((a, b) => {
         return Math.max(a, b);
    });
  }
  let newId = highestId + incrementAmount;
  ids.push({ id: newId });
  this.setState({ ids: ids }, next); //next will be called once the setState is finished
};
</code>```

You can call it inside double like this.

```<code>double = (firstIncrementAmount, secondIncrementAmount) => {
  this.uniqueIdCreatorHandler(
    firstIncrementAmount,
    () => this.uniqueIdCreatorHandler(secondIncrementAmount)
  );
};
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am testing some code to try and understand the race condition regarding the use of setState().

my code can be found here

my code below:

import React from "react";

export default class App extends React.Component {
  state = {
    id: "",
    ids: [{ id: 7 }, { id: 14 }]
  };

  // here is where I create the id numbers
  uniqueIdCreatorHandler = incrementAmount => {
    let ids = [...this.state.ids];
    let highestId = 0;
    if (ids.length > 0) {
      highestId = ids
        .map(value => {
          return value.id;
        })
        .reduce((a, b) => {
          return Math.max(a, b);
        });
    }
    let newId = highestId + incrementAmount;
    ids.push({ id: newId });
    this.setState({ ids: ids });
  };

  idDeleterHanlder = currentIndex => {
    let ids = this.state.ids;
    ids.splice(currentIndex, 1);
    this.setState({ ids: ids });
  };
  //below is when I test performing the function twice, in order to figure if the result would be a race condition
  double = (firstIncrementAmount, secondIncrementAmount) => {
    this.uniqueIdCreatorHandler(firstIncrementAmount);
    this.uniqueIdCreatorHandler(secondIncrementAmount);
  };

  render() {
    let ids = this.state.ids.map((id, index) => {
      return (

 this.idDeleterHanlder(index)} key={id.id}>
          id:{id.id}

      );
    });

    return (

        <button onClick={() => this.uniqueIdCreatorHandler(1)}>
          Push new id
        </button>
        <button onClick={() => this.double(1, 2)}>Add some Ids</button>

all ids below:

        {ids}

    );
  }
}

when invoking the double function on the second button only the secondIncrementAmount works. You can test it by changing the argument values on the call made on the onClick method.

I think that I should somehow use prevState on this.setState in order to fix this.

How could I avoid this issue here? This matter started at CodeReview but I did not realize how could I fix this.

There is also a recommendation to spread the mapped ids into Math.max and I could not figure out how and Why to do it. Isn't the creation of the new array by mapping the spreaded key values safe enough?

Body:
This isn't the most elegant solution but you can pass a callback to setState(see https://reactjs.org/docs/react-component.html#setstate).

If you modify uniqueIdCreatorHandler like this:

uniqueIdCreatorHandler = (incrementAmount, next) => {
  let ids = [...this.state.ids];
  let highestId = 0;
  if (ids.length > 0) {
    highestId = ids
      .map(value => {
        return value.id;
      })
      .reduce((a, b) => {
         return Math.max(a, b);
    });
  }
  let newId = highestId + incrementAmount;
  ids.push({ id: newId });
  this.setState({ ids: ids }, next); //next will be called once the setState is finished
};

You can call it inside double like this.

double = (firstIncrementAmount, secondIncrementAmount) => {
  this.uniqueIdCreatorHandler(
    firstIncrementAmount,
    () => this.uniqueIdCreatorHandler(secondIncrementAmount)
  );
};


问:
How to resolve symbolic links in a shell script
Given an absolute or relative path (in a Unix-like system), I would like to determine the full path of the target after resolving any intermediate symlinks. Bonus points for also resolving ~username notation at the same time.

If the target is a directory, it might be possible to chdir() into the directory and then call getcwd(), but I really want to do this from a shell script rather than writing a C helper. Unfortunately, shells have a tendency to try to hide the existence of symlinks from the user (this is bash on OS X):

```<code>$ ls -ld foo bar
drwxr-xr-x   2 greg  greg  68 Aug 11 22:36 bar
lrwxr-xr-x   1 greg  greg   3 Aug 11 22:36 foo -> bar
$ cd foo
$ pwd
/Users/greg/tmp/foo
$
</code>```

What I want is a function resolve() such that when executed from the tmp directory in the above example, resolve("foo") == "/Users/greg/tmp/bar".

答:
In case where pwd can't be used (e.g. calling a scripts from a different location), use realpath (with or without dirname):

```<code>$(dirname $(realpath $PATH_TO_BE_RESOLVED))
</code>```

Works both when calling through (multiple) symlink(s) or when directly calling the script - from any location.

ContentLicense: CC BY-SA 2.5

Body:
Given an absolute or relative path (in a Unix-like system), I would like to determine the full path of the target after resolving any intermediate symlinks. Bonus points for also resolving ~username notation at the same time.

If the target is a directory, it might be possible to chdir() into the directory and then call getcwd(), but I really want to do this from a shell script rather than writing a C helper. Unfortunately, shells have a tendency to try to hide the existence of symlinks from the user (this is bash on OS X):

$ ls -ld foo bar
drwxr-xr-x   2 greg  greg  68 Aug 11 22:36 bar
lrwxr-xr-x   1 greg  greg   3 Aug 11 22:36 foo -> bar
$ cd foo
$ pwd
/Users/greg/tmp/foo
$

What I want is a function resolve() such that when executed from the tmp directory in the above example, resolve("foo") == "/Users/greg/tmp/bar".

Body:
In case where pwd can't be used (e.g. calling a scripts from a different location), use realpath (with or without dirname):

$(dirname $(realpath $PATH_TO_BE_RESOLVED))

Works both when calling through (multiple) symlink(s) or when directly calling the script - from any location.


问:
grails maven dependency resolution
I have a grails plugin with following BuildCofnig.groovy

```<code>grails.project.class.dir = "target/classes"
grails.project.test.class.dir = "target/test-classes"
grails.project.test.reports.dir = "target/test-reports"
//grails.project.war.file = "target/${appName}-${appVersion}.war"
grails.project.dependency.resolution = {
    // inherit Grails' default dependencies
    inherits("global") {

    }

    log "warn" // log level of Ivy resolver, either 'error', 'warn', 'info', 'debug' or 'verbose'
    repositories {
        grailsPlugins()
        grailsHome()
        mavenCentral()
        mavenLocal()
        mavenRepo "http://repository.codehaus.org"
        flatDir name: 'lib', dirs: "${userHome}/libs"
    }

    dependencies {

        runtime('mysql:mysql-connector-java:5.1.9')

        compile('net.sf.jasperreports:jasperreports:4.0.1') {
            excludes 'antlr', 'commons-beanutils', 'commons-collections', 'commons-logging',
                     'ant', 'mondrian', 'commons-javaflow', 'barbecue', 'xml-apis-ext', 'xml-apis', 'xalan', 'groovy', 'groovy-all', 'hibernate', 'saaj-api', 'servlet-api',
                     'xercesImpl', 'xmlParserAPIs', 'spring-core', 'bsh', 'spring-beans', 'jaxen', 'barcode4j', 'batik-svg-dom', 'batik-xml', 'batik-awt-util', 'batik-dom',
                     'batik-css', 'batik-gvt', 'batik-script', 'batik-svggen', 'batik-util', 'batik-bridge', 'persistence-api', 'jdtcore', 'bcmail-jdk14', 'bcprov-jdk14', 'bctsp-jdk14'
        }
        compile('vomsws:VomsWsClient:1.0')
        compile('com.jaxfront:jaxfront-core:1.0',
                'com.jaxfront:jaxfront-html:1.0')
        compile('freemarker:freemarker:2.3.8')
        compile('org.apache.poi:poi:3.6')
        compile('commons-net:commons-net:3.0')
        compile('commons-httpclient:commons-httpclient:3.1')
    }
}
</code>```

I can pacakge plugin successfully. However when I import this plugin in a fresh Grails project and try to do run-app. I get following exception stack tace:

```<code>  [groovyc] Compiling 452 source files to C:\Users\Alam Sher\.grails\1.3.2\projects\witribe-test-gui\plugin-classes
: java.lang.NoClassDefFoundError: org/apache/xerces/xni/parser/XMLParseException
    at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:116)
    at _GrailsCompile_groovy$_run_closure4_closure10.doCall(_GrailsCompile_groovy:118)
    at _GrailsCompile_groovy$_run_closure4_closure10.doCall(_GrailsCompile_groovy)
    at _GrailsSettings_groovy$_run_closure10.doCall(_GrailsSettings_groovy:282)
    at _GrailsSettings_groovy$_run_closure10.call(_GrailsSettings_groovy)
    at _GrailsCompile_groovy$_run_closure4.doCall(_GrailsCompile_groovy:105)
    at _GrailsCompile_groovy$_run_closure3.doCall(_GrailsCompile_groovy:68)
    at _GrailsPackage_groovy$_run_closure2_closure9.doCall(_GrailsPackage_groovy:84)
    at _GrailsPackage_groovy$_run_closure2_closure9.doCall(_GrailsPackage_groovy)
    at _GrailsSettings_groovy$_run_closure10.doCall(_GrailsSettings_groovy:282)
    at _GrailsSettings_groovy$_run_closure10.call(_GrailsSettings_groovy)
    at _GrailsPackage_groovy$_run_closure2.doCall(_GrailsPackage_groovy:83)
    at RunApp$_run_closure1.doCall(RunApp.groovy:28)
    at gant.Gant$_dispatch_closure5.doCall(Gant.groovy:381)
    at gant.Gant$_dispatch_closure7.doCall(Gant.groovy:415)
    at gant.Gant$_dispatch_closure7.doCall(Gant.groovy)
    at gant.Gant.withBuildListeners(Gant.groovy:427)
    at gant.Gant.this$2$withBuildListeners(Gant.groovy)
    at gant.Gant$this$2$withBuildListeners.callCurrent(Unknown Source)
    at gant.Gant.dispatch(Gant.groovy:415)
    at gant.Gant.this$2$dispatch(Gant.groovy)
    at gant.Gant.invokeMethod(Gant.groovy)
    at gant.Gant.executeTargets(Gant.groovy:590)
    at gant.Gant.executeTargets(Gant.groovy:589)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:115)
Caused by: java.lang.NoClassDefFoundError: org/apache/xerces/xni/parser/XMLParseException
    at java.lang.Class.getDeclaredFields0(Native Method)
    at java.lang.Class.privateGetDeclaredFields(Class.java:2291)
    at java.lang.Class.getDeclaredFields(Class.java:1743)
    at org.codehaus.groovy.vmplugin.v5.Java5.configureClassNode(Java5.java:313)
    at org.codehaus.groovy.control.ResolveVisitor.checkCyclicInheritence(ResolveVisitor.java:1269)
    at org.codehaus.groovy.control.ResolveVisitor.visitClass(ResolveVisitor.java:1246)
    at org.codehaus.groovy.control.ResolveVisitor.startResolving(ResolveVisitor.java:148)
    at org.codehaus.groovy.tools.javac.JavaAwareCompilationUnit$1.call(JavaAwareCompilationUnit.java:63)
    at org.codehaus.groovy.control.CompilationUnit.applyToPrimaryClassNodes(CompilationUnit.java:931)
    at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:509)
    at org.codehaus.groovy.control.CompilationUnit.processPhaseOperations(CompilationUnit.java:487)
    at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:464)
    at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:448)
    at org.codehaus.groovy.tools.FileSystemCompiler.compile(FileSystemCompiler.java:57)
    at org.codehaus.groovy.tools.FileSystemCompiler.doCompilation(FileSystemCompiler.java:170)
    at org.codehaus.groovy.ant.Groovyc.compile(Groovyc.java:830)
    at org.codehaus.groovy.ant.Groovyc.execute(Groovyc.java:552)
    at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:288)
    at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
    ... 24 more
Caused by: java.lang.ClassNotFoundException: org.apache.xerces.xni.parser.XMLParseException
    at org.codehaus.groovy.tools.RootLoader.findClass(RootLoader.java:156)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at org.codehaus.groovy.tools.RootLoader.loadClass(RootLoader.java:128)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
    ... 43 more
--- Nested Exception ---
java.lang.NoClassDefFoundError: org/apache/xerces/xni/parser/XMLParseException
    at java.lang.Class.getDeclaredFields0(Native Method)
    at java.lang.Class.privateGetDeclaredFields(Class.java:2291)
    at java.lang.Class.getDeclaredFields(Class.java:1743)
    at org.codehaus.groovy.vmplugin.v5.Java5.configureClassNode(Java5.java:313)
    at org.codehaus.groovy.control.ResolveVisitor.checkCyclicInheritence(ResolveVisitor.java:1269)
    at org.codehaus.groovy.control.ResolveVisitor.visitClass(ResolveVisitor.java:1246)
    at org.codehaus.groovy.control.ResolveVisitor.startResolving(ResolveVisitor.java:148)
    at org.codehaus.groovy.tools.javac.JavaAwareCompilationUnit$1.call(JavaAwareCompilationUnit.java:63)
    at org.codehaus.groovy.control.CompilationUnit.applyToPrimaryClassNodes(CompilationUnit.java:931)
    at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:509)
    at org.codehaus.groovy.control.CompilationUnit.processPhaseOperations(CompilationUnit.java:487)
    at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:464)
    at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:448)
    at org.codehaus.groovy.tools.FileSystemCompiler.compile(FileSystemCompiler.java:57)
    at org.codehaus.groovy.tools.FileSystemCompiler.doCompilation(FileSystemCompiler.java:170)
    at org.codehaus.groovy.ant.Groovyc.compile(Groovyc.java:830)
    at org.codehaus.groovy.ant.Groovyc.execute(Groovyc.java:552)
    at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:288)
    at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
    at _GrailsCompile_groovy$_run_closure4_closure10.doCall(_GrailsCompile_groovy:118)
    at _GrailsCompile_groovy$_run_closure4_closure10.doCall(_GrailsCompile_groovy)
    at _GrailsSettings_groovy$_run_closure10.doCall(_GrailsSettings_groovy:282)
    at _GrailsSettings_groovy$_run_closure10.call(_GrailsSettings_groovy)
    at _GrailsCompile_groovy$_run_closure4.doCall(_GrailsCompile_groovy:105)
    at _GrailsCompile_groovy$_run_closure3.doCall(_GrailsCompile_groovy:68)
    at _GrailsPackage_groovy$_run_closure2_closure9.doCall(_GrailsPackage_groovy:84)
    at _GrailsPackage_groovy$_run_closure2_closure9.doCall(_GrailsPackage_groovy)
    at _GrailsSettings_groovy$_run_closure10.doCall(_GrailsSettings_groovy:282)
    at _GrailsSettings_groovy$_run_closure10.call(_GrailsSettings_groovy)
    at _GrailsPackage_groovy$_run_closure2.doCall(_GrailsPackage_groovy:83)
    at RunApp$_run_closure1.doCall(RunApp.groovy:28)
    at gant.Gant$_dispatch_closure5.doCall(Gant.groovy:381)
    at gant.Gant$_dispatch_closure7.doCall(Gant.groovy:415)
    at gant.Gant$_dispatch_closure7.doCall(Gant.groovy)
    at gant.Gant.withBuildListeners(Gant.groovy:427)
    at gant.Gant.this$2$withBuildListeners(Gant.groovy)
    at gant.Gant$this$2$withBuildListeners.callCurrent(Unknown Source)
    at gant.Gant.dispatch(Gant.groovy:415)
    at gant.Gant.this$2$dispatch(Gant.groovy)
    at gant.Gant.invokeMethod(Gant.groovy)
    at gant.Gant.executeTargets(Gant.groovy:590)
    at gant.Gant.executeTargets(Gant.groovy:589)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:115)
Caused by: java.lang.ClassNotFoundException: org.apache.xerces.xni.parser.XMLParseException
    at org.codehaus.groovy.tools.RootLoader.findClass(RootLoader.java:156)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at org.codehaus.groovy.tools.RootLoader.loadClass(RootLoader.java:128)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
    ... 43 more
Compilation error: java.lang.NoClassDefFoundError: org/apache/xerces/xni/parser/XMLParseException
</code>```

Kind of lost what's the problem here.. Frankly speaking I'm new to this dependency management using Maven and have no clue what so ever.

Your suggestions, recommendations are welcome.

答: When I see the number of exclusion you set, one should certainly correspond to the class not found .... Search for the good one ;-)</p>

ContentLicense: CC BY-SA 3.0

Title: grails maven dependency resolution

Body:
I have a grails plugin with following BuildCofnig.groovy

grails.project.class.dir = "target/classes"
grails.project.test.class.dir = "target/test-classes"
grails.project.test.reports.dir = "target/test-reports"
//grails.project.war.file = "target/${appName}-${appVersion}.war"
grails.project.dependency.resolution = {
    // inherit Grails' default dependencies
    inherits("global") {

    }

    log "warn" // log level of Ivy resolver, either 'error', 'warn', 'info', 'debug' or 'verbose'
    repositories {
        grailsPlugins()
        grailsHome()
        mavenCentral()
        mavenLocal()
        mavenRepo "http://repository.codehaus.org"
        flatDir name: 'lib', dirs: "${userHome}/libs"
    }

    dependencies {

        runtime('mysql:mysql-connector-java:5.1.9')

        compile('net.sf.jasperreports:jasperreports:4.0.1') {
            excludes 'antlr', 'commons-beanutils', 'commons-collections', 'commons-logging',
                     'ant', 'mondrian', 'commons-javaflow', 'barbecue', 'xml-apis-ext', 'xml-apis', 'xalan', 'groovy', 'groovy-all', 'hibernate', 'saaj-api', 'servlet-api',
                     'xercesImpl', 'xmlParserAPIs', 'spring-core', 'bsh', 'spring-beans', 'jaxen', 'barcode4j', 'batik-svg-dom', 'batik-xml', 'batik-awt-util', 'batik-dom',
                     'batik-css', 'batik-gvt', 'batik-script', 'batik-svggen', 'batik-util', 'batik-bridge', 'persistence-api', 'jdtcore', 'bcmail-jdk14', 'bcprov-jdk14', 'bctsp-jdk14'
        }
        compile('vomsws:VomsWsClient:1.0')
        compile('com.jaxfront:jaxfront-core:1.0',
                'com.jaxfront:jaxfront-html:1.0')
        compile('freemarker:freemarker:2.3.8')
        compile('org.apache.poi:poi:3.6')
        compile('commons-net:commons-net:3.0')
        compile('commons-httpclient:commons-httpclient:3.1')
    }
}

I can pacakge plugin successfully. However when I import this plugin in a fresh Grails project and try to do run-app. I get following exception stack tace:

  [groovyc] Compiling 452 source files to C:\Users\Alam Sher\.grails\1.3.2\projects\witribe-test-gui\plugin-classes
: java.lang.NoClassDefFoundError: org/apache/xerces/xni/parser/XMLParseException
    at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:116)
    at _GrailsCompile_groovy$_run_closure4_closure10.doCall(_GrailsCompile_groovy:118)
    at _GrailsCompile_groovy$_run_closure4_closure10.doCall(_GrailsCompile_groovy)
    at _GrailsSettings_groovy$_run_closure10.doCall(_GrailsSettings_groovy:282)
    at _GrailsSettings_groovy$_run_closure10.call(_GrailsSettings_groovy)
    at _GrailsCompile_groovy$_run_closure4.doCall(_GrailsCompile_groovy:105)
    at _GrailsCompile_groovy$_run_closure3.doCall(_GrailsCompile_groovy:68)
    at _GrailsPackage_groovy$_run_closure2_closure9.doCall(_GrailsPackage_groovy:84)
    at _GrailsPackage_groovy$_run_closure2_closure9.doCall(_GrailsPackage_groovy)
    at _GrailsSettings_groovy$_run_closure10.doCall(_GrailsSettings_groovy:282)
    at _GrailsSettings_groovy$_run_closure10.call(_GrailsSettings_groovy)
    at _GrailsPackage_groovy$_run_closure2.doCall(_GrailsPackage_groovy:83)
    at RunApp$_run_closure1.doCall(RunApp.groovy:28)
    at gant.Gant$_dispatch_closure5.doCall(Gant.groovy:381)
    at gant.Gant$_dispatch_closure7.doCall(Gant.groovy:415)
    at gant.Gant$_dispatch_closure7.doCall(Gant.groovy)
    at gant.Gant.withBuildListeners(Gant.groovy:427)
    at gant.Gant.this$2$withBuildListeners(Gant.groovy)
    at gant.Gant$this$2$withBuildListeners.callCurrent(Unknown Source)
    at gant.Gant.dispatch(Gant.groovy:415)
    at gant.Gant.this$2$dispatch(Gant.groovy)
    at gant.Gant.invokeMethod(Gant.groovy)
    at gant.Gant.executeTargets(Gant.groovy:590)
    at gant.Gant.executeTargets(Gant.groovy:589)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:115)
Caused by: java.lang.NoClassDefFoundError: org/apache/xerces/xni/parser/XMLParseException
    at java.lang.Class.getDeclaredFields0(Native Method)
    at java.lang.Class.privateGetDeclaredFields(Class.java:2291)
    at java.lang.Class.getDeclaredFields(Class.java:1743)
    at org.codehaus.groovy.vmplugin.v5.Java5.configureClassNode(Java5.java:313)
    at org.codehaus.groovy.control.ResolveVisitor.checkCyclicInheritence(ResolveVisitor.java:1269)
    at org.codehaus.groovy.control.ResolveVisitor.visitClass(ResolveVisitor.java:1246)
    at org.codehaus.groovy.control.ResolveVisitor.startResolving(ResolveVisitor.java:148)
    at org.codehaus.groovy.tools.javac.JavaAwareCompilationUnit$1.call(JavaAwareCompilationUnit.java:63)
    at org.codehaus.groovy.control.CompilationUnit.applyToPrimaryClassNodes(CompilationUnit.java:931)
    at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:509)
    at org.codehaus.groovy.control.CompilationUnit.processPhaseOperations(CompilationUnit.java:487)
    at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:464)
    at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:448)
    at org.codehaus.groovy.tools.FileSystemCompiler.compile(FileSystemCompiler.java:57)
    at org.codehaus.groovy.tools.FileSystemCompiler.doCompilation(FileSystemCompiler.java:170)
    at org.codehaus.groovy.ant.Groovyc.compile(Groovyc.java:830)
    at org.codehaus.groovy.ant.Groovyc.execute(Groovyc.java:552)
    at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:288)
    at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
    ... 24 more
Caused by: java.lang.ClassNotFoundException: org.apache.xerces.xni.parser.XMLParseException
    at org.codehaus.groovy.tools.RootLoader.findClass(RootLoader.java:156)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at org.codehaus.groovy.tools.RootLoader.loadClass(RootLoader.java:128)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
    ... 43 more
--- Nested Exception ---
java.lang.NoClassDefFoundError: org/apache/xerces/xni/parser/XMLParseException
    at java.lang.Class.getDeclaredFields0(Native Method)
    at java.lang.Class.privateGetDeclaredFields(Class.java:2291)
    at java.lang.Class.getDeclaredFields(Class.java:1743)
    at org.codehaus.groovy.vmplugin.v5.Java5.configureClassNode(Java5.java:313)
    at org.codehaus.groovy.control.ResolveVisitor.checkCyclicInheritence(ResolveVisitor.java:1269)
    at org.codehaus.groovy.control.ResolveVisitor.visitClass(ResolveVisitor.java:1246)
    at org.codehaus.groovy.control.ResolveVisitor.startResolving(ResolveVisitor.java:148)
    at org.codehaus.groovy.tools.javac.JavaAwareCompilationUnit$1.call(JavaAwareCompilationUnit.java:63)
    at org.codehaus.groovy.control.CompilationUnit.applyToPrimaryClassNodes(CompilationUnit.java:931)
    at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:509)
    at org.codehaus.groovy.control.CompilationUnit.processPhaseOperations(CompilationUnit.java:487)
    at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:464)
    at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:448)
    at org.codehaus.groovy.tools.FileSystemCompiler.compile(FileSystemCompiler.java:57)
    at org.codehaus.groovy.tools.FileSystemCompiler.doCompilation(FileSystemCompiler.java:170)
    at org.codehaus.groovy.ant.Groovyc.compile(Groovyc.java:830)
    at org.codehaus.groovy.ant.Groovyc.execute(Groovyc.java:552)
    at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:288)
    at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
    at _GrailsCompile_groovy$_run_closure4_closure10.doCall(_GrailsCompile_groovy:118)
    at _GrailsCompile_groovy$_run_closure4_closure10.doCall(_GrailsCompile_groovy)
    at _GrailsSettings_groovy$_run_closure10.doCall(_GrailsSettings_groovy:282)
    at _GrailsSettings_groovy$_run_closure10.call(_GrailsSettings_groovy)
    at _GrailsCompile_groovy$_run_closure4.doCall(_GrailsCompile_groovy:105)
    at _GrailsCompile_groovy$_run_closure3.doCall(_GrailsCompile_groovy:68)
    at _GrailsPackage_groovy$_run_closure2_closure9.doCall(_GrailsPackage_groovy:84)
    at _GrailsPackage_groovy$_run_closure2_closure9.doCall(_GrailsPackage_groovy)
    at _GrailsSettings_groovy$_run_closure10.doCall(_GrailsSettings_groovy:282)
    at _GrailsSettings_groovy$_run_closure10.call(_GrailsSettings_groovy)
    at _GrailsPackage_groovy$_run_closure2.doCall(_GrailsPackage_groovy:83)
    at RunApp$_run_closure1.doCall(RunApp.groovy:28)
    at gant.Gant$_dispatch_closure5.doCall(Gant.groovy:381)
    at gant.Gant$_dispatch_closure7.doCall(Gant.groovy:415)
    at gant.Gant$_dispatch_closure7.doCall(Gant.groovy)
    at gant.Gant.withBuildListeners(Gant.groovy:427)
    at gant.Gant.this$2$withBuildListeners(Gant.groovy)
    at gant.Gant$this$2$withBuildListeners.callCurrent(Unknown Source)
    at gant.Gant.dispatch(Gant.groovy:415)
    at gant.Gant.this$2$dispatch(Gant.groovy)
    at gant.Gant.invokeMethod(Gant.groovy)
    at gant.Gant.executeTargets(Gant.groovy:590)
    at gant.Gant.executeTargets(Gant.groovy:589)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:115)
Caused by: java.lang.ClassNotFoundException: org.apache.xerces.xni.parser.XMLParseException
    at org.codehaus.groovy.tools.RootLoader.findClass(RootLoader.java:156)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at org.codehaus.groovy.tools.RootLoader.loadClass(RootLoader.java:128)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
    ... 43 more
Compilation error: java.lang.NoClassDefFoundError: org/apache/xerces/xni/parser/XMLParseException

Kind of lost what's the problem here.. Frankly speaking I'm new to this dependency management using Maven and have no clue what so ever.

Your suggestions, recommendations are welcome.


问:
How to pass values to a function which is a list item in Python
I want to pass a value as argument in a function which is a list item.

For example:

```<code>def foo(arg1, arg2):
    print(“Something is happening here”, arg1, arg2 )

l = [1,2,3, foo('want values here as arguments')]

def foo_bar():
    x = 0, y = 1
    print(“want to pass x and y inside: “ , l[3])
</code>```

Thanks ahead.

答:
In order to store the result from foo() in your list, you need to reorder the steps in your code. I recommend storing the return result from foo() as a variable:

```<code>def foo(arg1, arg2):
    print(“Something is happening here”, arg1, arg2 )

def foo_bar():
    x = 0
    y = 1
    z = foo(x, y)
    l = [1,2,3, z]
    print(l)
</code>```

Alternatively, you can create the list and then append values to it:

```<code>def foo(arg1, arg2):
    print(“Something is happening here”, arg1, arg2 )

l = [1,2,3]

def foo_bar():
    x = 0
    y = 1
    z = foo(x, y)
    l.append(z)
    print(l)
</code>```

Body:
I want to pass a value as argument in a function which is a list item.

For example:

def foo(arg1, arg2):
    print(“Something is happening here”, arg1, arg2 )

l = [1,2,3, foo('want values here as arguments')]

def foo_bar():
    x = 0, y = 1
    print(“want to pass x and y inside: “ , l[3])

Thanks ahead.

Body:
In order to store the result from foo() in your list, you need to reorder the steps in your code. I recommend storing the return result from foo() as a variable:

def foo(arg1, arg2):
    print(“Something is happening here”, arg1, arg2 )

def foo_bar():
    x = 0
    y = 1
    z = foo(x, y)
    l = [1,2,3, z]
    print(l)

Alternatively, you can create the list and then append values to it:

def foo(arg1, arg2):
    print(“Something is happening here”, arg1, arg2 )

l = [1,2,3]

def foo_bar():
    x = 0
    y = 1
    z = foo(x, y)
    l.append(z)
    print(l)


问:
Error when installing chaincode - failed to calculate dependencies: incomplete package
I am try to installing Chaincode, follow the tutorial of hyperledger. But when I try to run the command

peer chaincode install -p chaincodedev/chaincode/sacc -n mycc -v 0

The terminal gives error message

Error: error getting chaincode deployment spec for mycc: error getting chaincode package bytes: failed to calculate dependencies: incomplete package: github.com/hyperledger/fabric-chaincode-go/shim

I see some other people got similar issue, but there is no answer yet. I am new to these stuffs, so any suggestions can be helpful.

答:
Try downloading the shim package to the GOPATH

go get github.com/hyperledger/fabric-chaincode-go/shim

This downloads the shim package to /src/github.com/hyperledger/fabric-chaincode-go/shim inside your GOPATH . Then provide the path to this shim package inside import in your chaincode.

It should be like below:

import (
    "github.com/hyperledger/fabric-chaincode-go/shim"
)


问:
How to add more than one navigation bar item on the same side of the bar in swiftUI
when using UIKit we can add more than one navigation bar item on leading side or trailing side, but how to do that in swiftUI?</p>

答:
You can put them in a HStack like so:

struct ContentView: View {
    var body: some View {
        NavigationView {
            Text("My View")
                .navigationBarTitle("My View")
                .navigationBarItems(leading:
                    HStack {
                        Button("Button1") {
                            // action
                        }

                        Button("Button2") {
                            // action
                        }
                    }
            )
        }
    }
}
```


问:
Save button in table
I have an array of data that is taken from the site and output to the table, I want to add a button that will store a certain row from the table in the database how can I implement it?</p>

```<code>   let cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell", for: indexPath)
   cell.textLabel?.text = news[indexPath.row].tittle

   let tipDouble = NumberFormatter().number(from: news[indexPath.row].time!)!.doubleValue
   let date = Date(timeIntervalSince1970: tipDouble)

   let dateFormatter = DateFormatter()
   dateFormatter.timeZone = TimeZone(abbreviation: "GMT+2") //Set timezone that you want
   dateFormatter.locale = NSLocale.current
   dateFormatter.dateFormat = "MM-dd HH:mm" //Specify your format that you want

   let strDate = dateFormatter.string(from: date)

   cell.detailTextLabel?.text = strDate

   return cell
</code>```

答:
The most easy and simple workaround is to set the button tag property as the row number and in the button action get the button tag to do your stuff i.e.

In your tableView(:cellForRowAt:indexPath) add the button tag as row number:

```<code>let cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell", for: indexPath) as! YourTableViewClass
cell.[buttonName].tag = indexPath.row (In case you are just using the single section)
</code>```

And then in your button action in viewController use the tag of button to track the row i.e.

```<code>@IBAction func buttonTapped(sender: UIButton) {
    let row = sender.tag
    // Do your stuff
}
</code>```

Title: Save button in table

Body:
I have an array of data that is taken from the site and output to the table, I want to add a button that will store a certain row from the table in the database how can I implement it?

   let cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell", for: indexPath)
   cell.textLabel?.text = news[indexPath.row].tittle

   let tipDouble = NumberFormatter().number(from: news[indexPath.row].time!)!.doubleValue
   let date = Date(timeIntervalSince1970: tipDouble)

   let dateFormatter = DateFormatter()
   dateFormatter.timeZone = TimeZone(abbreviation: "GMT+2") //Set timezone that you want
   dateFormatter.locale = NSLocale.current
   dateFormatter.dateFormat = "MM-dd HH:mm" //Specify your format that you want

   let strDate = dateFormatter.string(from: date)

   cell.detailTextLabel?.text = strDate

   return cell

Body:
The most easy and simple workaround is to set the button tag property as the row number and in the button action get the button tag to do your stuff i.e.

In your tableView(:cellForRowAt:indexPath) add the button tag as row number:

let cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell", for: indexPath) as! YourTableViewClass
cell.[buttonName].tag = indexPath.row (In case you are just using the single section)

And then in your button action in viewController use the tag of button to track the row i.e.

@IBAction func buttonTapped(sender: UIButton) {
    let row = sender.tag
    // Do your stuff
}


问:
Converting a matrix into a data frame in a long format (R)
I have a matrix in this format:

```<code>Example_matrix<- structure(list(X1 = c("Species 1", "Species 2", "Species 3",
"Species 4", "Species 5", "Species 6", "Species 7", "Species 8"
), `Site 1` = c(0, 0, 0, 2, 2, 0, 0, 5), `Site 2` = c(0, 0, 0,
4, 0, 0, 0, 0), `Site 3` = c(0, 1, 0, 0, 0, 1, 0, 0), `Site 4` = c(0,
0, 0, 0, 0, 1, 0, 0)), class = c("spec_tbl_df", "tbl_df", "tbl",
"data.frame"), row.names = c(NA, -8L), spec = structure(list(
    cols = list(X1 = structure(list(), class = c("collector_character",
    "collector")), `Site 1` = structure(list(), class = c("collector_double",
    "collector")), `Site 2` = structure(list(), class = c("collector_double",
    "collector")), `Site 3` = structure(list(), class = c("collector_double",
    "collector")), `Site 4` = structure(list(), class = c("collector_double",
    "collector"))), default = structure(list(), class = c("collector_guess",
    "collector")), skip = 1), class = "col_spec"))
</code>```

(This is a simplified version of it)

Is there way of quickly converting a matrix like that into a long format df? I had a look at some of the similar questions but the options didn't work for me. All I'm wanting to do is to end up with a df that will have 3 columns: Site, Species and the Abundance (which is currently the value within each cell in the matrix).

Thanks!

答:
Maybe you can try the following base R method using reshape

```<code>dflong <- `rownames<-`(setNames(reshape(Example_matrix,
                                        direction = "long",
                                        v.names = "Site",
                                        idvar = "X1",
                                        times = names(Example_matrix[-1]),
                                        varying = list(names(Example_matrix[-1]))),
                                c("X1","Site","Abundance")),
                       NULL)
</code>```

such that

```<code>> dflong
          X1   Site Abundance
1  Species 1 Site 1         0
2  Species 2 Site 1         0
3  Species 3 Site 1         0
4  Species 4 Site 1         2
5  Species 5 Site 1         2
6  Species 6 Site 1         0
7  Species 7 Site 1         0
8  Species 8 Site 1         5
9  Species 1 Site 2         0
10 Species 2 Site 2         0
11 Species 3 Site 2         0
12 Species 4 Site 2         4
13 Species 5 Site 2         0
14 Species 6 Site 2         0
15 Species 7 Site 2         0
16 Species 8 Site 2         0
17 Species 1 Site 3         0
18 Species 2 Site 3         1
19 Species 3 Site 3         0
20 Species 4 Site 3         0
21 Species 5 Site 3         0
22 Species 6 Site 3         1
23 Species 7 Site 3         0
24 Species 8 Site 3         0
25 Species 1 Site 4         0
26 Species 2 Site 4         0
27 Species 3 Site 4         0
28 Species 4 Site 4         0
29 Species 5 Site 4         0
30 Species 6 Site 4         1
31 Species 7 Site 4         0
32 Species 8 Site 4         0
</code>```

Body:
I have a matrix in this format:

Example_matrix<- structure(list(X1 = c("Species 1", "Species 2", "Species 3",
"Species 4", "Species 5", "Species 6", "Species 7", "Species 8"
), `Site 1` = c(0, 0, 0, 2, 2, 0, 0, 5), `Site 2` = c(0, 0, 0,
4, 0, 0, 0, 0), `Site 3` = c(0, 1, 0, 0, 0, 1, 0, 0), `Site 4` = c(0,
0, 0, 0, 0, 1, 0, 0)), class = c("spec_tbl_df", "tbl_df", "tbl",
"data.frame"), row.names = c(NA, -8L), spec = structure(list(
    cols = list(X1 = structure(list(), class = c("collector_character",
    "collector")), `Site 1` = structure(list(), class = c("collector_double",
    "collector")), `Site 2` = structure(list(), class = c("collector_double",
    "collector")), `Site 3` = structure(list(), class = c("collector_double",
    "collector")), `Site 4` = structure(list(), class = c("collector_double",
    "collector"))), default = structure(list(), class = c("collector_guess",
    "collector")), skip = 1), class = "col_spec"))

(This is a simplified version of it)

Is there way of quickly converting a matrix like that into a long format df? I had a look at some of the similar questions but the options didn't work for me. All I'm wanting to do is to end up with a df that will have 3 columns: Site, Species and the Abundance (which is currently the value within each cell in the matrix).

Thanks!

Body:
Maybe you can try the following base R method using reshape

dflong <- `rownames<-`(setNames(reshape(Example_matrix,
                                        direction = "long",
                                        v.names = "Site",
                                        idvar = "X1",
                                        times = names(Example_matrix[-1]),
                                        varying = list(names(Example_matrix[-1]))),
                                c("X1","Site","Abundance")),
                       NULL)

such that

> dflong
          X1   Site Abundance
1  Species 1 Site 1         0
2  Species 2 Site 1         0
3  Species 3 Site 1         0
4  Species 4 Site 1         2
5  Species 5 Site 1         2
6  Species 6 Site 1         0
7  Species 7 Site 1         0
8  Species 8 Site 1         5
9  Species 1 Site 2         0
10 Species 2 Site 2         0
11 Species 3 Site 2         0
12 Species 4 Site 2         4
13 Species 5 Site 2         0
14 Species 6 Site 2         0
15 Species 7 Site 2         0
16 Species 8 Site 2         0
17 Species 1 Site 3         0
18 Species 2 Site 3         1
19 Species 3 Site 3         0
20 Species 4 Site 3         0
21 Species 5 Site 3         0
22 Species 6 Site 3         1
23 Species 7 Site 3         0
24 Species 8 Site 3         0
25 Species 1 Site 4         0
26 Species 2 Site 4         0
27 Species 3 Site 4         0
28 Species 4 Site 4         0
29 Species 5 Site 4         0
30 Species 6 Site 4         1
31 Species 7 Site 4         0
32 Species 8 Site 4         0


问:
Converting Date to other format in C#
Can any one suggest me the following:
 i> how to convert 3/12/2010 10:15 to the format Mar 12, 2010 10:15 in c#.
 ii> how to remove time part out of it(i.e after the conversion i want Mar 12, 2010

Thanks in advance.

答: Use DateTime.Parse(...) to parse the input string into a DateTime object, and then use Format to make the string as posted by mikey.</p>

Title: Converting Date to other format in C#


问:
Unreliable nested while loops?
Im having a logic confusion here and don't know whether a solution is possible with my setup.

I am trying to prompt the user for (in order)

user answer y/n (originally set to 'y')

a bet (based on their current money)

a guess on a number 1-6.

Until the user answers anything but y, I will loop this program.
At stage 2, I will loop asking for a bet if the bet is invalid/not in range of their current money.
At stage 3, I will loop asking for a guess if the guess is not 1-6 or invalid.

My code below works, if the user answers with a valid guess all the time:

```<code>def roll():
    return [random.randrange(1,6), random.randrange(1,6), random.randrange(1,6)]

# Returns positive [betamount] or negative [betamount] depending on if guess is in diceroll list
def computeBetResult(diceRolls, betAmount, guessed):
    return (int(betAmount) if (int(guessed) in diceRolls) else -1*int(betAmount)) if (int(betAmount) > 0) else 0

# PART 2 - prompt user input and continually ask for new bets and guesses, until user says to quit
def main():
    money = 100
    userAnswer = 'y'
    print('Welcome to Gambling.')
    while(userAnswer.strip().lower() == 'y'):
        bet = input('You have $' + str(money) + '. How much would you like to bet?')
        while(bet.strip().isnumeric() and int(bet) > 0 and int(bet) <= money):
            guess = input('What number are you betting on? (number 1-6)')
            while (int(guess) >= 1 and int(guess) <= 6):
                print("Ok. You bet $" + str(bet).strip() + ' on the number ' + str(guess))
                # Actually calculate the roll
                theRoll = roll()
                print('You rolled: ' + str(theRoll[0]) + ', ' + str(theRoll[1]) + ', ' + str(theRoll[2]))
                if (int(computeBetResult(theRoll, bet, guess)) > 0):
                    print('You won your bet!')
                    money += int(bet)
                else:
                    print('You lost your bet :(')
                    money -= int(bet)
                print('You now have $' + str(money).strip())
                # Prompt again
                userAnswer = input('Would you like to play again (y/n)?')
                break
            break
</code>```

But if I get through with a valid bet, but not a valid guess, the program will just move on back to the top of the outermost while loop and ask for a bet again (from console):

```<code>You have $100. How much would you like to bet?0
You have $100. How much would you like to bet?0
You have $100. How much would you like to bet?100
What number are you betting on? (number 1-6)0
You have $100. How much would you like to bet?
</code>```

I've tried

```<code>if (int(guess) < 1 or int(guess) > 6):
            guess = input('What number are you betting on? (number 1-6)')
</code>```

at the very end of the outer while loop, but this then results in guess being asked for unnecessarily.

Is my setup all wrong or how can I fix this?

Updated attempt:

```<code>def main():
    money = 100
    userAnswer = 'y'
    print('Welcome to Gambling.')
    while(userAnswer.strip().lower() == 'y'):
        bet = input('You have $' + str(money) + '. How much would you like to bet?')
        while(bet.strip().isnumeric() and int(bet) > 0 and int(bet) <= money):
            guess = input('What number are you betting on? (number 1-6)')
            while (int(guess) >= 1 and int(guess) <= 6):
                print("Ok. You bet $" + str(bet).strip() + ' on the number ' + str(guess))
                # Actually calculate the roll
                theRoll = roll()
                print('You rolled: ' + str(theRoll[0]) + ', ' + str(theRoll[1]) + ', ' + str(theRoll[2]))
                if (int(computeBetResult(theRoll, bet, guess)) > 0):
                    print('You won your bet!')
                    money += int(bet)
                else:
                    print('You lost your bet :(')
                    money -= int(bet)
                print('You now have $' + str(money).strip())
                # Prompt again
                userAnswer = input('Would you like to play again (y/n)?')
                break
        if(userAnswer.strip().lower() != 'y'):
            break
</code>```

答:
From a quick glance your problem seems to lie in the fact that when you enter an invalid guessing number, you never enter the third and final loop.

```<code>guess = input('What number are you betting on? (number 1-6)')
while (int(guess) >= 1 and int(guess) <= 6):
</code>```

If you enter in a number that is < 1 or > 6 then you will never enter the while loop and directly jump to the break that is in the end of the second while loop which sends you back to the very first loop and asks you how much you want to bet again.

Try removing the break in the second while loop and see what happens, the logic is currently not what you are looking for.

Title: Unreliable nested while loops?

Body:
Im having a logic confusion here and don't know whether a solution is possible with my setup.

I am trying to prompt the user for (in order)

user answer y/n (originally set to 'y')

a bet (based on their current money)

a guess on a number 1-6.

Until the user answers anything but y, I will loop this program.
At stage 2, I will loop asking for a bet if the bet is invalid/not in range of their current money.
At stage 3, I will loop asking for a guess if the guess is not 1-6 or invalid.

My code below works, if the user answers with a valid guess all the time:

def roll():
    return [random.randrange(1,6), random.randrange(1,6), random.randrange(1,6)]

# Returns positive [betamount] or negative [betamount] depending on if guess is in diceroll list
def computeBetResult(diceRolls, betAmount, guessed):
    return (int(betAmount) if (int(guessed) in diceRolls) else -1*int(betAmount)) if (int(betAmount) > 0) else 0

# PART 2 - prompt user input and continually ask for new bets and guesses, until user says to quit
def main():
    money = 100
    userAnswer = 'y'
    print('Welcome to Gambling.')
    while(userAnswer.strip().lower() == 'y'):
        bet = input('You have $' + str(money) + '. How much would you like to bet?')
        while(bet.strip().isnumeric() and int(bet) > 0 and int(bet) <= money):
            guess = input('What number are you betting on? (number 1-6)')
            while (int(guess) >= 1 and int(guess) <= 6):
                print("Ok. You bet $" + str(bet).strip() + ' on the number ' + str(guess))
                # Actually calculate the roll
                theRoll = roll()
                print('You rolled: ' + str(theRoll[0]) + ', ' + str(theRoll[1]) + ', ' + str(theRoll[2]))
                if (int(computeBetResult(theRoll, bet, guess)) > 0):
                    print('You won your bet!')
                    money += int(bet)
                else:
                    print('You lost your bet :(')
                    money -= int(bet)
                print('You now have $' + str(money).strip())
                # Prompt again
                userAnswer = input('Would you like to play again (y/n)?')
                break
            break

But if I get through with a valid bet, but not a valid guess, the program will just move on back to the top of the outermost while loop and ask for a bet again (from console):

You have $100. How much would you like to bet?0
You have $100. How much would you like to bet?0
You have $100. How much would you like to bet?100
What number are you betting on? (number 1-6)0
You have $100. How much would you like to bet?

I've tried

if (int(guess) < 1 or int(guess) > 6):
            guess = input('What number are you betting on? (number 1-6)')

at the very end of the outer while loop, but this then results in guess being asked for unnecessarily.

Is my setup all wrong or how can I fix this?

Updated attempt:

def main():
    money = 100
    userAnswer = 'y'
    print('Welcome to Gambling.')
    while(userAnswer.strip().lower() == 'y'):
        bet = input('You have $' + str(money) + '. How much would you like to bet?')
        while(bet.strip().isnumeric() and int(bet) > 0 and int(bet) <= money):
            guess = input('What number are you betting on? (number 1-6)')
            while (int(guess) >= 1 and int(guess) <= 6):
                print("Ok. You bet $" + str(bet).strip() + ' on the number ' + str(guess))
                # Actually calculate the roll
                theRoll = roll()
                print('You rolled: ' + str(theRoll[0]) + ', ' + str(theRoll[1]) + ', ' + str(theRoll[2]))
                if (int(computeBetResult(theRoll, bet, guess)) > 0):
                    print('You won your bet!')
                    money += int(bet)
                else:
                    print('You lost your bet :(')
                    money -= int(bet)
                print('You now have $' + str(money).strip())
                # Prompt again
                userAnswer = input('Would you like to play again (y/n)?')
                break
        if(userAnswer.strip().lower() != 'y'):
            break

Body:
From a quick glance your problem seems to lie in the fact that when you enter an invalid guessing number, you never enter the third and final loop.

guess = input('What number are you betting on? (number 1-6)')
while (int(guess) >= 1 and int(guess) <= 6):

If you enter in a number that is < 1 or > 6 then you will never enter the while loop and directly jump to the break that is in the end of the second while loop which sends you back to the very first loop and asks you how much you want to bet again.

Try removing the break in the second while loop and see what happens, the logic is currently not what you are looking for.


问:
Can android access a PostgreSQL database from a traditional web application?
I am fairly new to databases, and StackOverflow(so bare with my question). My friends and I are trying to create a "student" version android app of a current school website. We just want to create something that is mobile friendly and easy to use for the students. However, the current website is a traditional web application (not REST API + SPA) and uses PostgreSQL as its database. I am wondering if we can connect a mobile app to that database to access the student's data or if we have to create a separate database.</p>

答:
You can use the same database but you need to create a backend service (REST API o Web Service) to comunicate the device and the database. You can use technologies like Nodejs, Go.

Hope this help you


问:
how to clear JavaScript variable value after few minutes / seconds / times
I have set a value in JavaScript local variable which is given below:

```<code>document.getElementById("class").value = getSavedValue("class");    // set the value to this input
document.getElementById("group").value = getSavedValue("group");   // set the value to this input
document.getElementById("section").value = getSavedValue("section");   // set the value to this input
document.getElementById("session").value = getSavedValue("session");   // set the value to this input
document.getElementById("shift").value = getSavedValue("shift");   // set the value to this input
document.getElementById("version").value = getSavedValue("version");   // set the value to this input
/* Here you can add more inputs to set value. if it's saved */

//Save the value function - save it to localStorage as (ID, VALUE)
function saveValue(e){
    var id = e.id;  // get the sender's id to save it .
    var val = e.value; // get the value.
    localStorage.setItem(id, val);// Every time user writing something, the localStorage's value will override .
}

//get the saved value function - return the value of "v" from localStorage.
function getSavedValue  (v){
    if (!localStorage.getItem(v)) {
        return "";// You can change this to your defualt value.
    }
    return localStorage.getItem(v);
}
</code>```

i want to when its value is saved then a certain amount of time it only that (specific) variable will be unset / clear automatically.

Thank you

答:
When setting a value, cancel any existing deletion callback for that key, then configure a new callback using setTimeout to delete the entry, then set the item.

But remember, the timekeeping accuracy of setTimeout varies.

const timeoutIds = {}
function set({key, value, lifetime}) {
    clearTimeout(timeoutIds[key])
    timeoutIds[key] = setTimeout(() => localStorage.removeItem(key), lifetime)
    localStorage.setItem(key, value)
}

function get(key){
    return localStorage.getItem(key)
}
```

<p>Another solution might be to write a timestamp along with the value, and then check for the validity of the value only when it is next read from storage.</p>

<pre class="lang-js prettyprint-override"><code>function set({key, value}, lifetime){
    const expires = Date.now() + lifetime
    localStorage.setItem(key, JSON.stringify({value, expires}))
}

function get(key){
    const item = JSON.parse(localStorage.getItem(key))
    if (value === null) return null
    if(item.expires <= Date.now()) {
        localStorage.removeItem(item.key)
        return null
    }
    return item.value
}
</code>```

If you want to get fancy, you might be able to get something working with a Web Worker and IndexedDB.

Body:
I have set a value in JavaScript local variable which is given below:

document.getElementById("class").value = getSavedValue("class");    // set the value to this input
document.getElementById("group").value = getSavedValue("group");   // set the value to this input
document.getElementById("section").value = getSavedValue("section");   // set the value to this input
document.getElementById("session").value = getSavedValue("session");   // set the value to this input
document.getElementById("shift").value = getSavedValue("shift");   // set the value to this input
document.getElementById("version").value = getSavedValue("version");   // set the value to this input
/* Here you can add more inputs to set value. if it's saved */

//Save the value function - save it to localStorage as (ID, VALUE)
function saveValue(e){
    var id = e.id;  // get the sender's id to save it .
    var val = e.value; // get the value.
    localStorage.setItem(id, val);// Every time user writing something, the localStorage's value will override .
}

//get the saved value function - return the value of "v" from localStorage.
function getSavedValue  (v){
    if (!localStorage.getItem(v)) {
        return "";// You can change this to your defualt value.
    }
    return localStorage.getItem(v);
}

i want to when its value is saved then a certain amount of time it only that (specific) variable will be unset / clear automatically.

Thank you

Body:
When setting a value, cancel any existing deletion callback for that key, then configure a new callback using setTimeout to delete the entry, then set the item.

But remember, the timekeeping accuracy of setTimeout varies.

const timeoutIds = {}
function set({key, value, lifetime}) {
    clearTimeout(timeoutIds[key])
    timeoutIds[key] = setTimeout(() => localStorage.removeItem(key), lifetime)
    localStorage.setItem(key, value)
}

function get(key){
    return localStorage.getItem(key)
}

Another solution might be to write a timestamp along with the value, and then check for the validity of the value only when it is next read from storage.

function set({key, value}, lifetime){
    const expires = Date.now() + lifetime
    localStorage.setItem(key, JSON.stringify({value, expires}))
}

function get(key){
    const item = JSON.parse(localStorage.getItem(key))
    if (value === null) return null
    if(item.expires <= Date.now()) {
        localStorage.removeItem(item.key)
        return null
    }
    return item.value
}

If you want to get fancy, you might be able to get something working with a Web Worker and IndexedDB.


问:
update part of the key
Q:

If I have a composite key combined from 4 fields for example, can I update one of them?

I mean can I execute a statement like this:

```<code>UPDATE tb
SET firstCol = '15', secondCol = 'test2'
WHERE firstCol = '1' AND serial = '2';
</code>```

Given:

my table name is: tb

my fields are: firstCol, secondCol, serial

my keys are: firstCol , serial

Any suggestions? Did I miss some concept?

thanks.

答:
Yes you can. It may be part of the key but it's still a column.

Note: if you have FKs relying on this key then you'll need to consider CASCASE updates. Also, a key update (assuming its clustered) means more work then "normal" because of how non clustered indexes refer to the clustered key

Title: update part of the key

Body:
Q:

If I have a composite key combined from 4 fields for example, can I update one of them?

I mean can I execute a statement like this:

UPDATE tb
SET firstCol = '15', secondCol = 'test2'
WHERE firstCol = '1' AND serial = '2';

Given:

my table name is: tb

my fields are: firstCol, secondCol, serial

my keys are: firstCol , serial

Any suggestions? Did I miss some concept?

thanks.


问:
With jQuery, update the value of a data element attribute
How can I update the value of a data element attribute ?

This is my HTML:

```<code><a href="" data-action="add-to-cart">Add</a>
</code>```

This is my JS:

```<code>$('a[data-action="add-to-cart"], a[data-action="remove-from-cart"]').click(function(e) {
    e.preventDefault();

    if($(this).data('action') == 'add-to-cart') {
        $(this).data('action', 'remove-from-cart');
    }

    else {
        $(this).data('action', 'add-to-cart');
    }
});
</code>```

Thanks.

答:
So I read on SO, and I found a solution that works for my case:
https://stackoverflow.com/a/41585821/9603642

```<code>$('a[data-action="add-to-cart"], a[data-action="remove-from-cart"]').click(function(e) {
    e.preventDefault();

    if($(this).data('action') == 'add-to-cart') {
        $(this).attr('data-action', 'remove-from-cart');
        $(this).data('action', 'remove-from-cart');
    }

    else {
        $(this).attr('data-action', 'add-to-cart');
        $(this).data('action', 'add-to-cart');
    }
});
</code>```

I add to use attr and data.

Body:
How can I update the value of a data element attribute ?

This is my HTML:

Add

This is my JS:

$('a[data-action="add-to-cart"], a[data-action="remove-from-cart"]').click(function(e) {
    e.preventDefault();

    if($(this).data('action') == 'add-to-cart') {
        $(this).data('action', 'remove-from-cart');
    }

    else {
        $(this).data('action', 'add-to-cart');
    }
});

Thanks.

Body:
So I read on SO, and I found a solution that works for my case:
https://stackoverflow.com/a/41585821/9603642

$('a[data-action="add-to-cart"], a[data-action="remove-from-cart"]').click(function(e) {
    e.preventDefault();

    if($(this).data('action') == 'add-to-cart') {
        $(this).attr('data-action', 'remove-from-cart');
        $(this).data('action', 'remove-from-cart');
    }

    else {
        $(this).attr('data-action', 'add-to-cart');
        $(this).data('action', 'add-to-cart');
    }
});

I add to use attr and data.


问:
keep background div fixed while allowing another div to scroll over it as an overlay
so i have an svg morph animation using anime.js and scrollmonitor as a background div while another div which has content of the page is to scroll over the fixed background div.
but it isnt working as expected. the background div doesn't stay fixed as the background and scrolls down with the overlay div.

kindly help out with this. i am clueless so as to what i am missing out.
here is the link to the website

https://esselion.com/passapp/#/

```<code>.morph-wrap {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden;
    z-index: 1000;
}

.content-landing-wrap{
    position: relative;
    z-index: 1100;
    overflow-y: auto;
}
</code>```

答:
 is fixed relative to its parent container. If you move
 outside of
, it will remain fixed as you scroll.

```

Include your HTML next time so we don't have to inspect your website. It will help us help you. :D

Body:
so i have an svg morph animation using anime.js and scrollmonitor as a background div while another div which has content of the page is to scroll over the fixed background div.
but it isnt working as expected. the background div doesn't stay fixed as the background and scrolls down with the overlay div.

kindly help out with this. i am clueless so as to what i am missing out.
here is the link to the website

https://esselion.com/passapp/#/

.morph-wrap {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden;
    z-index: 1000;
}

.content-landing-wrap{
    position: relative;
    z-index: 1100;
    overflow-y: auto;
}

Body:
<div class="morph-wrap"> is fixed relative to its parent container. If you move <div class="morph-wrap"> outside of <div id="main">, it will remain fixed as you scroll.

<div id="content-scroll">
  <div class="morph-wrap"></div>
  <div id="main"></div>
</div>

Include your HTML next time so we don't have to inspect your website. It will help us help you. :D


问:
horizontally displayed JSON data react card
I am new to react ,I am fetching some json data and I would like to displayed them horizontally in bootstrap card,Whenever I tried ,it keeps displayed vertically .here is my code.

```<code><div className="row"  >
<div className="col-md-4" >
<div className="card" >
             <img className="card-img-top" src={user.picture.large? ( user.picture.large) : ("http://appalachiantrail.org/images/default-source/default-album/trailfocus.jpg?sfvrsn=2")} />
               <div className="card-body" >
                 <h1 className="card-title">{user.name.first}</h1>
                   <h2 className="card-text">{user.id.value} </h2>
                     <h4 className="card-text">{user.email} </h4>
                     </div>
<br>
                     </br>

   </div>
</div>
</code>```

this is what I want to achieve

See  code here of what I want to achieve,how do I replace those static column with my dynamic json response data ? Please advise

thanks

答:
This question is not about fetching the data or displaying it successfully but about aligning your "cards" horizontally which is only CSS related.

It might be because of the bootstrap styles but if have your container like this...

```<code><div className="card-container">
    <Card>...</Card>
    <Card>...</Card>
    ...
</div>
</code>```

CSS

```<code>.card-container {
    display: flex;
    ...
}

.card {
    flex: 0 0 25%; (or however you want to size)
    ...
}
</code>```

Everything should be horizontal with display: flex;

Body:
I am new to react ,I am fetching some json data and I would like to displayed them horizontally in bootstrap card,Whenever I tried ,it keeps displayed vertically .here is my code.

{user.name.first}

{user.id.value}

{user.email}

this is what I want to achieve

See  code here of what I want to achieve,how do I replace those static column with my dynamic json response data ? Please advise

thanks

Body:
This question is not about fetching the data or displaying it successfully but about aligning your "cards" horizontally which is only CSS related.

It might be because of the bootstrap styles but if have your container like this...

<div className="card-container">
    <Card>...</Card>
    <Card>...</Card>
    ...
</div>

CSS

.card-container {
    display: flex;
    ...
}

.card {
    flex: 0 0 25%; (or however you want to size)
    ...
}

Everything should be horizontal with display: flex;


问:
Multiple services with Primeng dynamic dialogs interfere with each other
I am struggling with an angular/primeng problem. I have two services in different modules each of which use DialogService to create a DynamicDialog component.

I have read that you need separate instances of the DialogService if you have multiple modals at the same time.  I tried to accomplish this by putting each service in their own module and putting DialogService in the "providers" section of each module.

Each modal works fine by itself, but I have a situation where both modals are displayed simultaneously.
In this case, after I close the second modal, I can't close the first modal, even though the close code is fired and returns result.

The stackblitz for an example of this problem is:

https://stackblitz.com/github/thomasesh/twomodalproblem

Any help would be greatly appreciated.

答:
the reason is angular DI. you importing module-a and module-b in app-module. they both provide DialogService. and because of how DI works the SINGLE instance of a service is created. it is imo primeng bug, but to workaround it you can create a token and provide(and inject also) second instance of a service with the token, rather than using the same instance of a service</p>

```<code>// token.ts
export const DialogServiceToken = new InjectionToken('DialogService');
//module-b.ts

providers: [
 { provide: DialogServiceToken, useClass: DialogService} // this will register second instance of DialogService
]

//module-b.service
constructor( @Inject(dialogServiceToken) private dialogService: DialogService) {} // here we inject the second instance of a service
</code>```

Body:
the reason is angular DI. you importing module-a and module-b in app-module. they both provide DialogService. and because of how DI works the SINGLE instance of a service is created. it is imo primeng bug, but to workaround it you can create a token and provide(and inject also) second instance of a service with the token, rather than using the same instance of a service

// token.ts
export const DialogServiceToken = new InjectionToken('DialogService');
//module-b.ts

providers: [
 { provide: DialogServiceToken, useClass: DialogService} // this will register second instance of DialogService
]

//module-b.service
constructor( @Inject(dialogServiceToken) private dialogService: DialogService) {} // here we inject the second instance of a service


问:
Ruby undefined method '**'
I'm attempting to write a function that uses array methods to do a variety of things. I need to use the each method to print the cube of each element in the array. Here's my code.

```<code>def foo(a)

    a.each { |x| puts x ** 3 }

    a.each_slice(3) { |x| puts x }
    a.select do |x|

        if x%5 == 0
            puts x
        end
    end

    a.map { |x| x ** 3 }
    aa.inject(0) { |x, y| x * y }

end

a = Array.new(50)
a.each { |x| x = rand(10..100) }

foo(a)
</code>```

I keep getting this error:

```<code>Traceback (most recent call last):
        3: from task2.rb:21:in `<main>'
        2: from task2.rb:3:in `foo'
        1: from task2.rb:3:in `each'
task2.rb:3:in `block in foo': undefined method `**' for nil:NilClass (NoMethodError)
</code>```

答:
You should use the Ruby p method to help you debug things.  (p x is a shortcut puts x.inspect.)

So try running the following program:

a = Array.new(50)
a.each { |x| x = rand(10..100) }
p a
```

<p>From the output of that program, you can see that your array just consists of 50 nils.  So then your real question is: How do I initialize an array properly?  The <code>x</code> argument to your block is not some kind of reference to a cell in the array, it is simply a copy of the value that was held in the array, so writing to <code>x</code> does not do anything to the array.</p>

<p>The simplest way that would work for your application is:</p>

<pre class="lang-rb prettyprint-override"><code>a = Array.new(50) { rand(10..100) }
</code>```

You could also write it like this:

a = 50.times.map { rand(10..100) }
```

<p>You could also initialize your array in a more manual way by appending to it 50 times:</p>

<pre class="lang-rb prettyprint-override"><code>a = []
50.times { a << rand(10..100) }
</code>```

You could also use the []= method, which is the most general way to write to an array:

a = []
50.times { |i| a[i] = rand(10..100) }
```

It's worthwhile to know about each of these different ways to make an array.

Title: Ruby undefined method '**'

Body:
I'm attempting to write a function that uses array methods to do a variety of things. I need to use the each method to print the cube of each element in the array. Here's my code.

def foo(a)

    a.each { |x| puts x ** 3 }

    a.each_slice(3) { |x| puts x }
    a.select do |x|

        if x%5 == 0
            puts x
        end
    end

    a.map { |x| x ** 3 }
    aa.inject(0) { |x, y| x * y }

end

a = Array.new(50)
a.each { |x| x = rand(10..100) }

foo(a)

I keep getting this error:

Traceback (most recent call last):
        3: from task2.rb:21:in `'
        2: from task2.rb:3:in `foo'
        1: from task2.rb:3:in `each'
task2.rb:3:in `block in foo': undefined method `**' for nil:NilClass (NoMethodError)

Body:
You should use the Ruby p method to help you debug things.  (p x is a shortcut puts x.inspect.)

So try running the following program:

a = Array.new(50)
a.each { |x| x = rand(10..100) }
p a

From the output of that program, you can see that your array just consists of 50 nils.  So then your real question is: How do I initialize an array properly?  The x argument to your block is not some kind of reference to a cell in the array, it is simply a copy of the value that was held in the array, so writing to x does not do anything to the array.

The simplest way that would work for your application is:

a = Array.new(50) { rand(10..100) }

You could also write it like this:

a = 50.times.map { rand(10..100) }

You could also initialize your array in a more manual way by appending to it 50 times:

a = []
50.times { a << rand(10..100) }

You could also use the []= method, which is the most general way to write to an array:

a = []
50.times { |i| a[i] = rand(10..100) }

It's worthwhile to know about each of these different ways to make an array.


问:
JDBC connection to SQL Server 2005 Instance running on remote machine
I am trying to connect to sql server 2005 instance running on a remote machine from my spring web application. This web application is running in tomcat server. Earlier When I connected to sql server 2000, it worked fine. I used msbase.jar, mssqlserver.jar, msutil.jar to connect to sql server 2000. My connection String was

```<code>jdbc:microsoft:sqlserver://192.168.0.38:1433;DatabaseName=AndroidPOC
</code>```

But now when I try to connect to sql server 2005. Iam getting all sorts of problems. I tried out various things but of no use.

My connection string for sql server 2005 was

```<code>jdbc:sqlserver://192.168.0.202;instanceName=INSTANCE_NAME;DatabaseName=MYDATABASE
</code>```

Please help me with the steps to connect to 2005 sql server.

What are all the jars required.

Do i need to update sql server jdbc driver, if yes how.

The driver class name to be used.

If possible please provide some sample code using spring jdbc and normal jdbc as well.

答:
It may be a driver version problem, since it has been a long time since the JDBC driver has been included in one Jar. More likely, the URL format you are using isn't recognized by your old driver.

You can get the latest JAR here.

Body:
I am trying to connect to sql server 2005 instance running on a remote machine from my spring web application. This web application is running in tomcat server. Earlier When I connected to sql server 2000, it worked fine. I used msbase.jar, mssqlserver.jar, msutil.jar to connect to sql server 2000. My connection String was

jdbc:microsoft:sqlserver://192.168.0.38:1433;DatabaseName=AndroidPOC

But now when I try to connect to sql server 2005. Iam getting all sorts of problems. I tried out various things but of no use.

My connection string for sql server 2005 was

jdbc:sqlserver://192.168.0.202;instanceName=INSTANCE_NAME;DatabaseName=MYDATABASE

Please help me with the steps to connect to 2005 sql server.

What are all the jars required.

Do i need to update sql server jdbc driver, if yes how.

The driver class name to be used.

If possible please provide some sample code using spring jdbc and normal jdbc as well.


问:
SWIFT UI add element to array
I trying to learn the new SwiftUI coding technique. I would like to click a button that will add elements to an array that is a @State variable. The button is the buttonclick function.  The array is the push_group_row / push_group_array.    I get an error in the append statement.

Eventually the buttonclick will access a database to build an array with more row, but for now I just trying to add one row.

Code:

```<code>import SwiftUI
import Combine

var gordon: String = "xxxxxx"

struct Result: Codable {
  let trackId: Int
  let trackName: String
  let collectionName: String
}
struct Response: Codable {
  var results: [Result]
}
struct Pokemon: Identifiable {
  let id: Int
  let name: String
  let type: String
  let color: Color
}
struct push_group_row {
  let id: Int
  let code: String
  let title: String
}

struct ContentView: View
    {
    @State private var results = [Result]()
    @State var pokemonList = [
       Pokemon(id: 0, name: "Charmander", type: "Fire", color: .red),
       Pokemon(id: 1, name: "Squirtle", type: "Water", color: .blue),
       Pokemon(id: 2, name: "Bulbasaur", type: "Grass", color: .green),
       Pokemon(id: 3, name: "Pikachu", type: "Electric", color: .yellow),]
    @State var push_group_array = [push_group_row(id: 0, code: "code12", title: "POAFire")]

    var body: some View
    {
    NavigationView
    {
        VStack(alignment: . leading){
        Button(action: {
            // What to perform
            self.buttonclick()
        }) {
            // How the button looks like
            Text("clickme")
            .background(Color.purple)
            .foregroundColor(.white)
        }

        List(results, id: \.trackId)
        {item in
            NavigationLink(destination: DetailView(lm: String(item.trackId)))
            {
            VStack(alignment: .leading)
            {
                Text(String(item.trackId))
                Text(item.trackName)
                    .font(.headline)
                Text(item.collectionName)
                Text(gordon)
            }
            }
            }

            List(self.pokemonList)
            { pokemon in
                HStack
                    {
                    Text(pokemon.name)
                    Text(pokemon.type).foregroundColor(pokemon.color)
                    }

            }

            List(push_group_array, id: \.id)
                 { pg_item in
                     HStack
                         {
                         Text(String(pg_item.id))
                         Text(pg_item.code)
                         }

                 }
            .onAppear(perform: self.loaddata)
            }
            .navigationBarTitle("x")
            .navigationBarItems(
                trailing: Button(action: addPokemon, label: { Text("Add") }))

            Spacer()
    }
}

    func addPokemon() {
        if let randomPokemon = pokemonList.randomElement() {
            pokemonList.append(randomPokemon)
        }
    }

    // *************************** below is the add arrat code
    func buttonclick() {
        let newCode = "First"
        let newTitle = "Second"
        push_group_array.append(id: 1, code: newCode,  title: newTitle)
    }

    func loaddata()
    {
        print("loaddata")

        guard let url = URL(string: "https://itunes.apple.com/search?term=taylor+swift&entity=song")
        else
        {
           print("Invalid URL")
           return
        }

        var urlData: NSData?
        let request = URLRequest(url: url)
        URLSession.shared.dataTask(with: request) { data, response, error in
            if let data = data
            {
                if let decodedResponse = try? JSONDecoder().decode(Response.self, from: data)
                {
                DispatchQueue.main.async
                {
                    urlData = data as NSData?
                    self.results = decodedResponse.results
                    print(self.results)
                    print(urlData ?? "urlData_Defaultvalue")
                }
                return
                }
            }
            print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")")
        }.resume()
    }
}

struct ContentView_Previews: PreviewProvider {
  static var previews: some View {
    ContentView()
  }
}
</code>```

答:
You need to push the object rather than 3 values </p>

```<code>push_group_array.append(push_group_row(id: 1, code: newCode, title: newTitle))
</code>```

Title: SWIFT UI add element to array

Body:
I trying to learn the new SwiftUI coding technique. I would like to click a button that will add elements to an array that is a @State variable. The button is the buttonclick function.  The array is the push_group_row / push_group_array.    I get an error in the append statement.

Eventually the buttonclick will access a database to build an array with more row, but for now I just trying to add one row.

Code:

import SwiftUI
import Combine

var gordon: String = "xxxxxx"

struct Result: Codable {
  let trackId: Int
  let trackName: String
  let collectionName: String
}
struct Response: Codable {
  var results: [Result]
}
struct Pokemon: Identifiable {
  let id: Int
  let name: String
  let type: String
  let color: Color
}
struct push_group_row {
  let id: Int
  let code: String
  let title: String
}

struct ContentView: View
    {
    @State private var results = [Result]()
    @State var pokemonList = [
       Pokemon(id: 0, name: "Charmander", type: "Fire", color: .red),
       Pokemon(id: 1, name: "Squirtle", type: "Water", color: .blue),
       Pokemon(id: 2, name: "Bulbasaur", type: "Grass", color: .green),
       Pokemon(id: 3, name: "Pikachu", type: "Electric", color: .yellow),]
    @State var push_group_array = [push_group_row(id: 0, code: "code12", title: "POAFire")]

    var body: some View
    {
    NavigationView
    {
        VStack(alignment: . leading){
        Button(action: {
            // What to perform
            self.buttonclick()
        }) {
            // How the button looks like
            Text("clickme")
            .background(Color.purple)
            .foregroundColor(.white)
        }

        List(results, id: \.trackId)
        {item in
            NavigationLink(destination: DetailView(lm: String(item.trackId)))
            {
            VStack(alignment: .leading)
            {
                Text(String(item.trackId))
                Text(item.trackName)
                    .font(.headline)
                Text(item.collectionName)
                Text(gordon)
            }
            }
            }

            List(self.pokemonList)
            { pokemon in
                HStack
                    {
                    Text(pokemon.name)
                    Text(pokemon.type).foregroundColor(pokemon.color)
                    }

            }

            List(push_group_array, id: \.id)
                 { pg_item in
                     HStack
                         {
                         Text(String(pg_item.id))
                         Text(pg_item.code)
                         }

                 }
            .onAppear(perform: self.loaddata)
            }
            .navigationBarTitle("x")
            .navigationBarItems(
                trailing: Button(action: addPokemon, label: { Text("Add") }))

            Spacer()
    }
}

    func addPokemon() {
        if let randomPokemon = pokemonList.randomElement() {
            pokemonList.append(randomPokemon)
        }
    }

    // *************************** below is the add arrat code
    func buttonclick() {
        let newCode = "First"
        let newTitle = "Second"
        push_group_array.append(id: 1, code: newCode,  title: newTitle)
    }

    func loaddata()
    {
        print("loaddata")

        guard let url = URL(string: "https://itunes.apple.com/search?term=taylor+swift&entity=song")
        else
        {
           print("Invalid URL")
           return
        }

        var urlData: NSData?
        let request = URLRequest(url: url)
        URLSession.shared.dataTask(with: request) { data, response, error in
            if let data = data
            {
                if let decodedResponse = try? JSONDecoder().decode(Response.self, from: data)
                {
                DispatchQueue.main.async
                {
                    urlData = data as NSData?
                    self.results = decodedResponse.results
                    print(self.results)
                    print(urlData ?? "urlData_Defaultvalue")
                }
                return
                }
            }
            print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")")
        }.resume()
    }
}

struct ContentView_Previews: PreviewProvider {
  static var previews: some View {
    ContentView()
  }
}

Body:
You need to push the object rather than 3 values

push_group_array.append(push_group_row(id: 1, code: newCode, title: newTitle))


问:
Tensorboard checkpoint : Access is denied. ; Input/output error
I am trying to create a tensor board in Jupyter anaconda the following way. The error occurs when write_images = True, otherwise, this code works fine. Any reason why this happens?

```<code>log_dir="logs\\fit\\" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S")

tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=log_dir,
                                                      histogram_freq=1,
                                                      write_graph = True,
                                                      write_images = False
                                                      update_freq = 'epoch'
                                                      profile_batch = 3,
                                                      embeddings_freq=1
                                                     )
</code>```

And I get

```<code>UnknownError: Failed to rename: logs\20200219-202538\train\checkpoint.tmp67d5ca45d1404cc584a86cf42d2761d3 to: logs\20200219-202538\train\checkpoint : Access is denied.
; Input/output error
</code>```

Seems to be random on which epoch it occurs.

答:
I had something similar, it seems like the path where you want to safe the checkpoint, which is referred to tensorbaord is not available or denied. Do you know colab ? I would suggest you copy your code and run your training up there (only if your dataset isnt too large). You can copy your dataset in your Google Drive and access with colab. If it is working in colab, than you may dont have a problem with your code, but propably with your anaconda restrictions.
Mount Google Drive (Colab), Colab basics

I know i couldnt solve your problem, but propably this can help you and boost your learning speed with a juicy free Cloud GPU.

Body:
I am trying to create a tensor board in Jupyter anaconda the following way. The error occurs when write_images = True, otherwise, this code works fine. Any reason why this happens?

log_dir="logs\\fit\\" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S")

tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=log_dir,
                                                      histogram_freq=1,
                                                      write_graph = True,
                                                      write_images = False
                                                      update_freq = 'epoch'
                                                      profile_batch = 3,
                                                      embeddings_freq=1
                                                     )

And I get

UnknownError: Failed to rename: logs\20200219-202538\train\checkpoint.tmp67d5ca45d1404cc584a86cf42d2761d3 to: logs\20200219-202538\train\checkpoint : Access is denied.
; Input/output error

Seems to be random on which epoch it occurs.


问:
Google maps marker delete function not invoked in ReactJS
I am trying to implement custom markers on google maps in my ReactJS application. Now that I got the markers, I would like to have an option to delete them.
This is the code for placing and deleting markers. However, when I click on the delete button in the info window, nothing seems to happen.

```<code>  addInfoWindow(marker, message, map) {
    var infoWindow = new google.maps.InfoWindow({
      content: message
    });

    google.maps.event.addListener(marker, "click", function() {
      infoWindow.open(map, marker);
    });
  }

  deleteMarker() {
    console.log('Delete');
  }

  placeMarker = (map, location) => {
    let marker = new google.maps.Marker({
      position: location,
      map: map,
      icon: red_flag
    });

    var contentString =
      '<button type="button" class="btn btn-danger" onClick="' +
      this.deleteMarker +
      '">Delete</button>';

    this.addInfoWindow(marker, contentString, map);
  };
</code>```

I also tried with;

```<code>deleteMarker = () => {
    console.log('Delete');
}
</code>```

When I click on the button, the method is not getting invoked and no errors on console. What could be wrong with this code?
The generated HTML code for this content string is;

```<code><button type="button" class="btn btn-danger" onclick="function () {
      console.log('Delete');
    }">Delete</button>
</code>```

To clarify further, I would like to have the string for delete button behave like this;

```<code><button type="button" class="btn btn-danger" onClick={() => this.deleteMarker("param")}>
    Delete
</button>

deleteMarker = param => {
    console.log("Delete", param);
};
</code>```

答:
You're trying to use the code as if it's going to execute using JSX in React, but Google Maps and HTML doesn't work that way.  Google Maps itself doesn't use React and as such, the Google Maps library works without any knowledge of how React works and React works independently of how Google Maps works. Because of this, every React Google Maps package has to work with the raw DOM or wrap the Google Maps library so that it can prevent memory leaks, bugs, or other breakages.  When you create an InfoWindow object with content, that content will create HTML independent of React which means that to get it working the way that you want it to, you must work with DOM listeners yourself.

What you have written will create a function when clicking it, but it doesn't execute.  Inside of the onclick attribute of HTML, it contains a JavaScript expression scoped globally.  If it's just a function expression like what you will get with either of those options, it will only create the function as an expression but not execute it.

Instead, you will have to either use a global function to delete the marker (not in any way advisable) or manually add an event listener (hacky, but may be necessary).

I'd suggest creating a unique ID for the button so that you can get it once it's been appended.  From there, you will have to get a reference to that button once it's appended and then add an event listener to it that deletes the marker.

Using your example, it might look like this:

  addInfoWindow(marker, message, map, uniqueId) {
    var infoWindow = new google.maps.InfoWindow({
      content: message
    });

    google.maps.event.addListener(marker, "click", function() {
      infoWindow.open(map, marker);
    });

    google.maps.event.addListener(infoWindow, 'domready', () => {
        document.getElementById(uniqueId)
            .addEventListener('click', this.deleteMarker.bind(this));
    });
  }

  deleteMarker() {
    console.log('Delete');
  }

  placeMarker = (map, location) => {
    let marker = new google.maps.Marker({
      position: location,
      map: map,
      icon: red_flag
    });

    var uniqueId = 'delete-marker-'+ getAUniqueId();

    var contentString =
      '<button type="button" class="btn btn-danger" id="' + uniqueId + '">Delete</button>';

    this.addInfoWindow(marker, contentString, map, uniqueId);
  };
```

And that should get you going.

But since you're dealing with the raw DOM elements, you should make sure you can clean up that event listener when you delete the marker and info window.  That would require you also capturing that function you create when binding the deleteMarker function (though you don't have to capture it extra if you use an arrow function or binding the method to your instance in your component constructor).

Some notable references:

Google Maps event documentation - https://developers.google.com/maps/documentation/javascript/reference/event

InfoWindow documentation; domready event - https://developers.google.com/maps/documentation/javascript/reference/info-window#InfoWindow.domready

MDN HTML onclick attribute (note it is "obsolete" since there are better ways of registering event handlers, though it might also be "obsolete" for that specific article, maybe there is a newer one) - https://developer.mozilla.org/en-US/docs/Archive/Mozilla/XUL/Attribute/onclick

W3 Schools onclick attribute guide - https://www.w3schools.com/TAgs/att_onclick.asp

Body:
I am trying to implement custom markers on google maps in my ReactJS application. Now that I got the markers, I would like to have an option to delete them.
This is the code for placing and deleting markers. However, when I click on the delete button in the info window, nothing seems to happen.

  addInfoWindow(marker, message, map) {
    var infoWindow = new google.maps.InfoWindow({
      content: message
    });

    google.maps.event.addListener(marker, "click", function() {
      infoWindow.open(map, marker);
    });
  }

  deleteMarker() {
    console.log('Delete');
  }

  placeMarker = (map, location) => {
    let marker = new google.maps.Marker({
      position: location,
      map: map,
      icon: red_flag
    });

    var contentString =
      '<button type="button" class="btn btn-danger" onClick="' +
      this.deleteMarker +
      '">Delete</button>';

    this.addInfoWindow(marker, contentString, map);
  };

I also tried with;

deleteMarker = () => {
    console.log('Delete');
}

When I click on the button, the method is not getting invoked and no errors on console. What could be wrong with this code?
The generated HTML code for this content string is;

<button type="button" class="btn btn-danger" onclick="function () {
      console.log('Delete');
    }">Delete</button>

To clarify further, I would like to have the string for delete button behave like this;

<button type="button" class="btn btn-danger" onClick={() => this.deleteMarker("param")}>
    Delete
</button>

deleteMarker = param => {
    console.log("Delete", param);
};

Body:
You're trying to use the code as if it's going to execute using JSX in React, but Google Maps and HTML doesn't work that way.  Google Maps itself doesn't use React and as such, the Google Maps library works without any knowledge of how React works and React works independently of how Google Maps works. Because of this, every React Google Maps package has to work with the raw DOM or wrap the Google Maps library so that it can prevent memory leaks, bugs, or other breakages.  When you create an InfoWindow object with content, that content will create HTML independent of React which means that to get it working the way that you want it to, you must work with DOM listeners yourself.

What you have written will create a function when clicking it, but it doesn't execute.  Inside of the onclick attribute of HTML, it contains a JavaScript expression scoped globally.  If it's just a function expression like what you will get with either of those options, it will only create the function as an expression but not execute it.

Instead, you will have to either use a global function to delete the marker (not in any way advisable) or manually add an event listener (hacky, but may be necessary).

I'd suggest creating a unique ID for the button so that you can get it once it's been appended.  From there, you will have to get a reference to that button once it's appended and then add an event listener to it that deletes the marker.

Using your example, it might look like this:

  addInfoWindow(marker, message, map, uniqueId) {
    var infoWindow = new google.maps.InfoWindow({
      content: message
    });

    google.maps.event.addListener(marker, "click", function() {
      infoWindow.open(map, marker);
    });

    google.maps.event.addListener(infoWindow, 'domready', () => {
        document.getElementById(uniqueId)
            .addEventListener('click', this.deleteMarker.bind(this));
    });
  }

  deleteMarker() {
    console.log('Delete');
  }

  placeMarker = (map, location) => {
    let marker = new google.maps.Marker({
      position: location,
      map: map,
      icon: red_flag
    });

    var uniqueId = 'delete-marker-'+ getAUniqueId();

    var contentString =
      '<button type="button" class="btn btn-danger" id="' + uniqueId + '">Delete</button>';

    this.addInfoWindow(marker, contentString, map, uniqueId);
  };

And that should get you going.

But since you're dealing with the raw DOM elements, you should make sure you can clean up that event listener when you delete the marker and info window.  That would require you also capturing that function you create when binding the deleteMarker function (though you don't have to capture it extra if you use an arrow function or binding the method to your instance in your component constructor).

Some notable references:

Google Maps event documentation - https://developers.google.com/maps/documentation/javascript/reference/event

InfoWindow documentation; domready event - https://developers.google.com/maps/documentation/javascript/reference/info-window#InfoWindow.domready

MDN HTML onclick attribute (note it is "obsolete" since there are better ways of registering event handlers, though it might also be "obsolete" for that specific article, maybe there is a newer one) - https://developer.mozilla.org/en-US/docs/Archive/Mozilla/XUL/Attribute/onclick

W3 Schools onclick attribute guide - https://www.w3schools.com/TAgs/att_onclick.asp