问:
Using Oracle.DataAccess.DLL already on PC, not providing it
I am looking to make my program more dynamic. I would like it to be able to support an Oracle 10g and an Oracle 11g database with the same program. If I build the program using the .DLL reference for one version then the other fails. Is there a way to use the Oracle.DataAccess.DLL that is already on the computer being installed upon, instead of providing the DLL in my installer?

Thanks in advance.

答:
SpecificVersion is an attribute that applies only during build time. It was designed to assist if there are multiple versions of an assembly in the build environment; when SpecificVersion is true, it will ensure that you build against and reference the desired version. Once the target assembly is built, however, its references contain the strong name and the version number of the referenced assembly. So, if SpecificVersion is false, it's going to be set to reference whatever was the available version of the reference in the build environment at the time.

"Note that the Specific Version property is only a build-time directive, and it has no effect on the runtime version resolution of the referenced assembly" (http://www.code-magazine.com/article.aspx?quickid=0507041&page=3).

However, you could use version redirection to explicitly annotate that you accept any version. The oldVersion field specifies anything (the version you built against), and the newVersion attribute would specify which one you want to actually link against at runtime.

```<code>  <dependentAssembly>
    <assemblyIdentity name="Oracle.DataAccess" publicKeyToken="89B483F429C47342"/>
    <bindingRedirect oldVersion="1.0.0.0-2.111.9999.9999" newVersion="2.102.2.20"/>
  </dependentAssembly>
</code>```

(See http://msdn.microsoft.com/en-us/library/7wd6ex19.aspx.)

That dependentAssembly node can be applied to different contexts. One possible context would be in a web.config or app.config as a child of the configuration/runtime/assemblyBinding node.

To answer your particular scenario of supporting both Oracle 10g and 11g? There are two options, the former of which was suggested by the user @BQ:

Deploy only one version of ODP.NET. You should be able to talk to both versions of the database server (10g and 11g) from either version of ODP.NET (10g or 11g). See @BQ's answer below.

If you really need to be able to link to two different assembly versions, you will need to have two different version redirection configurations. In other words, you'd need two app.config files, one of which contains a version redirection to the 10g ODP.NET version and the other to the 11g ODP.NET version.

A few more tips:

Make sure you remove any Oracle-provided publisher policies from the GAC. These take precedence over ones in web/app.config

By default, binding failures are cached, so if the ODP.NET assembly happened to fail binding with the version redirection, you'll need to restart IIS to purge the cached failures.

Body:
SpecificVersion is an attribute that applies only during build time. It was designed to assist if there are multiple versions of an assembly in the build environment; when SpecificVersion is true, it will ensure that you build against and reference the desired version. Once the target assembly is built, however, its references contain the strong name and the version number of the referenced assembly. So, if SpecificVersion is false, it's going to be set to reference whatever was the available version of the reference in the build environment at the time.

"Note that the Specific Version property is only a build-time directive, and it has no effect on the runtime version resolution of the referenced assembly" (http://www.code-magazine.com/article.aspx?quickid=0507041&page=3).

However, you could use version redirection to explicitly annotate that you accept any version. The oldVersion field specifies anything (the version you built against), and the newVersion attribute would specify which one you want to actually link against at runtime.

  <dependentAssembly>
    <assemblyIdentity name="Oracle.DataAccess" publicKeyToken="89B483F429C47342"/>
    <bindingRedirect oldVersion="1.0.0.0-2.111.9999.9999" newVersion="2.102.2.20"/>
  </dependentAssembly>

(See http://msdn.microsoft.com/en-us/library/7wd6ex19.aspx.)

That dependentAssembly node can be applied to different contexts. One possible context would be in a web.config or app.config as a child of the configuration/runtime/assemblyBinding node.

To answer your particular scenario of supporting both Oracle 10g and 11g? There are two options, the former of which was suggested by the user @BQ:

Deploy only one version of ODP.NET. You should be able to talk to both versions of the database server (10g and 11g) from either version of ODP.NET (10g or 11g). See @BQ's answer below.

If you really need to be able to link to two different assembly versions, you will need to have two different version redirection configurations. In other words, you'd need two app.config files, one of which contains a version redirection to the 10g ODP.NET version and the other to the 11g ODP.NET version.

A few more tips:

Make sure you remove any Oracle-provided publisher policies from the GAC. These take precedence over ones in web/app.config

By default, binding failures are cached, so if the ODP.NET assembly happened to fail binding with the version redirection, you'll need to restart IIS to purge the cached failures.


来源: stackexchange

问:
Android: Uploading image without losing Exif data
In our app users have been uploading millions of images for years using (roughly) this code:

```<code>BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(postFilePath, bmOptions);
Bitmap roughBitmap = BitmapFactory.decodeFile(postFilePath, bmOptions);

ByteArrayOutputStream stream = new ByteArrayOutputStream();

roughBitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
InputStream fis = new ByteArrayInputStream(stream.toByteArray());

int fileSize = stream.toByteArray().length;
conn.setRequestProperty("Content-Length", Integer.toString(fileSize));
conn.setFixedLengthStreamingMode(fileSize);

...

if (fis != null) {
    byte[] buf = new byte[10240];

    int read;

    while ((read = fis.read(buf)) > 0) {
        os.write(buf, 0, read);
        totalBytesRead += read;
        if (uploadProgressListener != null) {
            try {
                uploadProgressListener.onBytesUploaded(read);
            } catch (Exception e) {
                Log.e(e);
            }
        }
    }

    fis.close();
}
</code>```

Recently we saw the need to preserve the Exif data of uploaded images. The problem is that the image Exif data is lost when compressing the bitmap. I thought of using ExifInterface for extracting this data from the original file:

```<code>ExifInterface oldExif = new ExifInterface(postFilePath);
String value = oldExif.getAttribute(ExifInterface.TAG_DATETIME);
</code>```

..and then adding it to the InputStream fis and then continue uploading the file. The problem is that ExifInterface cannot save Exif data to an InputStream.

How can Exif data be retained in the images when they'er uploaded to the server?

It's not a duplicate:
Just to clarify deeper, I've tried using the suggested duplicate question by using this method:

```<code>public static void copyExif(String originalPath, InputStream newStream) throws IOException {

    String[] attributes = new String[]
            {
                    ExifInterface.TAG_DATETIME,
                    ExifInterface.TAG_DATETIME_DIGITIZED,
                    ExifInterface.TAG_EXPOSURE_TIME,
                    ExifInterface.TAG_FLASH,
                    ExifInterface.TAG_FOCAL_LENGTH,
                    ExifInterface.TAG_GPS_ALTITUDE,
                    ExifInterface.TAG_GPS_ALTITUDE_REF,
                    ExifInterface.TAG_GPS_DATESTAMP,
                    ExifInterface.TAG_GPS_LATITUDE,
                    ExifInterface.TAG_GPS_LATITUDE_REF,
                    ExifInterface.TAG_GPS_LONGITUDE,
                    ExifInterface.TAG_GPS_LONGITUDE_REF,
                    ExifInterface.TAG_GPS_PROCESSING_METHOD,
                    ExifInterface.TAG_GPS_TIMESTAMP,
                    ExifInterface.TAG_MAKE,
                    ExifInterface.TAG_MODEL,
                    ExifInterface.TAG_ORIENTATION,
                    ExifInterface.TAG_SUBSEC_TIME,
                    ExifInterface.TAG_WHITE_BALANCE
            };

    ExifInterface oldExif = new ExifInterface(originalPath);
    ExifInterface newExif = new ExifInterface(newStream);

    if (attributes.length > 0) {
        for (int i = 0; i < attributes.length; i++) {
            String value = oldExif.getAttribute(attributes[i]);
            if (value != null)
                newExif.setAttribute(attributes[i], value);
        }
        newExif.saveAttributes();
    }
}
</code>```

.. but got the exception java.io.IOException: ExifInterface does not support saving attributes for the current input. after newExif.saveAttributes(); because I'm trying to save the attributes to an InputStream. How else can I do it?

答:
Source: https://stackoverflow.com/a/11572752/8252521

Answered by: https://stackoverflow.com/users/1592398/code-jaff

Convert the file to bitmap by

```<code>Bitmap bi = BitmapFactory.decode(filepath + "DSC00021.jpg");
</code>```

You can specify options too, look at API documentation

Or if you want to exchange the meta data from one file to another,
  sanselan will probably be the best choice. This would be much
  helpful when you manipulating the image, for example re-size.

The sample code will guide you in a right direction.

ContentLicense: CC BY-SA 3.0

Body:
In our app users have been uploading millions of images for years using (roughly) this code:

BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(postFilePath, bmOptions);
Bitmap roughBitmap = BitmapFactory.decodeFile(postFilePath, bmOptions);

ByteArrayOutputStream stream = new ByteArrayOutputStream();

roughBitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
InputStream fis = new ByteArrayInputStream(stream.toByteArray());

int fileSize = stream.toByteArray().length;
conn.setRequestProperty("Content-Length", Integer.toString(fileSize));
conn.setFixedLengthStreamingMode(fileSize);

...

if (fis != null) {
    byte[] buf = new byte[10240];

    int read;

    while ((read = fis.read(buf)) > 0) {
        os.write(buf, 0, read);
        totalBytesRead += read;
        if (uploadProgressListener != null) {
            try {
                uploadProgressListener.onBytesUploaded(read);
            } catch (Exception e) {
                Log.e(e);
            }
        }
    }

    fis.close();
}

Recently we saw the need to preserve the Exif data of uploaded images. The problem is that the image Exif data is lost when compressing the bitmap. I thought of using ExifInterface for extracting this data from the original file:

ExifInterface oldExif = new ExifInterface(postFilePath);
String value = oldExif.getAttribute(ExifInterface.TAG_DATETIME);

..and then adding it to the InputStream fis and then continue uploading the file. The problem is that ExifInterface cannot save Exif data to an InputStream.

How can Exif data be retained in the images when they'er uploaded to the server?

It's not a duplicate:
Just to clarify deeper, I've tried using the suggested duplicate question by using this method:

public static void copyExif(String originalPath, InputStream newStream) throws IOException {

    String[] attributes = new String[]
            {
                    ExifInterface.TAG_DATETIME,
                    ExifInterface.TAG_DATETIME_DIGITIZED,
                    ExifInterface.TAG_EXPOSURE_TIME,
                    ExifInterface.TAG_FLASH,
                    ExifInterface.TAG_FOCAL_LENGTH,
                    ExifInterface.TAG_GPS_ALTITUDE,
                    ExifInterface.TAG_GPS_ALTITUDE_REF,
                    ExifInterface.TAG_GPS_DATESTAMP,
                    ExifInterface.TAG_GPS_LATITUDE,
                    ExifInterface.TAG_GPS_LATITUDE_REF,
                    ExifInterface.TAG_GPS_LONGITUDE,
                    ExifInterface.TAG_GPS_LONGITUDE_REF,
                    ExifInterface.TAG_GPS_PROCESSING_METHOD,
                    ExifInterface.TAG_GPS_TIMESTAMP,
                    ExifInterface.TAG_MAKE,
                    ExifInterface.TAG_MODEL,
                    ExifInterface.TAG_ORIENTATION,
                    ExifInterface.TAG_SUBSEC_TIME,
                    ExifInterface.TAG_WHITE_BALANCE
            };

    ExifInterface oldExif = new ExifInterface(originalPath);
    ExifInterface newExif = new ExifInterface(newStream);

    if (attributes.length > 0) {
        for (int i = 0; i < attributes.length; i++) {
            String value = oldExif.getAttribute(attributes[i]);
            if (value != null)
                newExif.setAttribute(attributes[i], value);
        }
        newExif.saveAttributes();
    }
}

.. but got the exception java.io.IOException: ExifInterface does not support saving attributes for the current input. after newExif.saveAttributes(); because I'm trying to save the attributes to an InputStream. How else can I do it?

Body:
Source: https://stackoverflow.com/a/11572752/8252521

Answered by: https://stackoverflow.com/users/1592398/code-jaff

Convert the file to bitmap by

Bitmap bi = BitmapFactory.decode(filepath + "DSC00021.jpg");

You can specify options too, look at API documentation

Or if you want to exchange the meta data from one file to another,
  sanselan will probably be the best choice. This would be much
  helpful when you manipulating the image, for example re-size.

The sample code will guide you in a right direction.


问:
New line in json array is getting converted to a comma | nodejs
I am relatively new to nodejs and running into an issue while parsing a Json post request.

Here is the JSON format of the post request:

```<code>{"parameters":{"issuerId":[96409],"source":["'XYZ'"]}}
</code>```

And here is my code to read it.

```<code>function getSearchData(req, res, next) {
  console.log("req is" + req.body);

  try {
JSON.parse(reqJSON);
    } catch (e) {
console.log(e);
 }

}
</code>```

This parsing works fine and I am able to parse it and do my further logic. However, if I change my format of post request(same request with additional new lines) it fails to parse as it adds additional commas in place of each new line in the request.

```<code>{
  "parameters": {
    "issuerId": [96409],
    "source":["'XYZ'"]
  }
}
</code>```

Here's the output from the code with the second request.

req is{,"parameters":{"id":[96409],,"source":["'XYZ'"]}}
[SyntaxError: Unexpected token ,]

If you notice, an extra comma gets added at each new line, which was never in the request to begin with.

What am I doing wrong here?

答:
You should never have to parse the JSON yourself, unless you're concatenating the request body stream yourself.

Hint 1: Do you use any framework like Express? Do you use body parser?

Hint 2: How do you create the JSON?

Hint 3: Do you use correct content-type?

Hint 4: How do you create req.body from the request stream?

You didn't include the entire code so it's impossible to give you a specific solution.

What am I doing wrong here?

Whatever you're doing wrong here, it's not included in the question.

However, if I change my format of post request(same request with additional new lines)

It would be useful if you included more details of how you do it.

I see two potential sources of that problem:

either the commas are introduced during the on the client side

or they are introduced during the request reading on the server side

You didn't show us any of those two parts - you didn't show the serializing code and the code that sends the data, and you didn't include the code that gets the data, possibly joins it from chunks and parses the JSON. But the problem is likely in one of those parts.

Update

Here is an example on how to do what you need using Express. You didn't answer whether you use any framework like Express or not, but I think that you should if you can't achieve that simple task without it, so here is a working example:

```<code>const express = require('express');
const bodyParser = require('body-parser');

const app = express();

function getSearchData(req, res, next) {
  console.log('req body is', req.body);
  console.log('req body JSON is', JSON.stringify(req.body));

  res.json({ ok: true });
}

app.use(bodyParser.json());
app.use(getSearchData);

app.listen(3335, () => console.log('Listening on http://localhost:3335/'));
</code>```

It shows how to correctly get a parsed JSON request body as an object req.body, how to print the data as a standard console.log representation and serialized again as JSON. See how it works and compare it to your own solution. This is all I can do because not having seen your entire solution I cannot tell you more than the hints that I've already given.

Body:
I am relatively new to nodejs and running into an issue while parsing a Json post request.

Here is the JSON format of the post request:

{"parameters":{"issuerId":[96409],"source":["'XYZ'"]}}

And here is my code to read it.

function getSearchData(req, res, next) {
  console.log("req is" + req.body);

  try {
JSON.parse(reqJSON);
    } catch (e) {
console.log(e);
 }

}

This parsing works fine and I am able to parse it and do my further logic. However, if I change my format of post request(same request with additional new lines) it fails to parse as it adds additional commas in place of each new line in the request.

{
  "parameters": {
    "issuerId": [96409],
    "source":["'XYZ'"]
  }
}

Here's the output from the code with the second request.

req is{,"parameters":{"id":[96409],,"source":["'XYZ'"]}}
[SyntaxError: Unexpected token ,]

If you notice, an extra comma gets added at each new line, which was never in the request to begin with.

What am I doing wrong here?

Body:
You should never have to parse the JSON yourself, unless you're concatenating the request body stream yourself.

Hint 1: Do you use any framework like Express? Do you use body parser?

Hint 2: How do you create the JSON?

Hint 3: Do you use correct content-type?

Hint 4: How do you create req.body from the request stream?

You didn't include the entire code so it's impossible to give you a specific solution.

What am I doing wrong here?

Whatever you're doing wrong here, it's not included in the question.

However, if I change my format of post request(same request with additional new lines)

It would be useful if you included more details of how you do it.

I see two potential sources of that problem:

either the commas are introduced during the on the client side

or they are introduced during the request reading on the server side

You didn't show us any of those two parts - you didn't show the serializing code and the code that sends the data, and you didn't include the code that gets the data, possibly joins it from chunks and parses the JSON. But the problem is likely in one of those parts.

Update

Here is an example on how to do what you need using Express. You didn't answer whether you use any framework like Express or not, but I think that you should if you can't achieve that simple task without it, so here is a working example:

const express = require('express');
const bodyParser = require('body-parser');

const app = express();

function getSearchData(req, res, next) {
  console.log('req body is', req.body);
  console.log('req body JSON is', JSON.stringify(req.body));

  res.json({ ok: true });
}

app.use(bodyParser.json());
app.use(getSearchData);

app.listen(3335, () => console.log('Listening on http://localhost:3335/'));

It shows how to correctly get a parsed JSON request body as an object req.body, how to print the data as a standard console.log representation and serialized again as JSON. See how it works and compare it to your own solution. This is all I can do because not having seen your entire solution I cannot tell you more than the hints that I've already given.


问:
Use CSS/IMG/JS with NodeJS
I create a http server with nodeJS and express.
I do the router for html pages but the css, the images and the js files are ignored.

I checked and the paths are ok.

I  tried to use static function of express but it doesn't work.

If you have an idea :)

server.js

```<code>var http = require("http");
var url = require("url");
var fs = require('fs');
//var express = require('express');
//var app = express();

//app.use(express.static( __dirname + "/views/web/assets/img"));

var server = http.createServer(function(req, res)
{
    var pathName = url.parse(req.url).pathname;
    console.log(__dirname + "/views/web" + pathName);
    fs.readFile( __dirname + "/views/web" + pathName , "utf8" , function(error , file){
     if(error) {
          res.writeHead(404 , {"Content-Type" : "text/html" });
          res.end();
     }else{
          res.writeHead(200 , {"Content-Type" : "text/html" });
          res.write(file);
          res.end();
     }
    });
});

server.listen(1337);
console.log("Serveur web lancé sur localhost:1337 ...");
</code>```

An extract of login.html :

```<code><!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Profile - Login</title>
    <link rel="icon" type="image/png" href="assets/img/logo.png" />
    <!-- BOOTSTRAP STYLES-->
    <link href="assets/css/bootstrap.css" rel="stylesheet" />
     <!-- FONTAWESOME STYLES-->
    <link href="assets/css/font-awesome.css" rel="stylesheet" />
        <!-- CUSTOM STYLES-->
    <link href="assets/css/custom.css" rel="stylesheet" />
     <!-- GOOGLE FONTS-->
   <link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css' />

</head>
</code>```

The verification of paths :

```<code>proux@DESKTOP-VDRS1QF:/mnt/d/Users/Elodie/Desktop/server$ node server.js
Serveur web lancé sur localhost:1337 ...
/mnt/d/Users/Elodie/Desktop/server/views/web/
/mnt/d/Users/Elodie/Desktop/server/views/web/
/mnt/d/Users/Elodie/Desktop/server/views/web/login.html
/mnt/d/Users/Elodie/Desktop/server/views/web/assets/css/bootstrap.css
/mnt/d/Users/Elodie/Desktop/server/views/web/assets/css/font-awesome.css
/mnt/d/Users/Elodie/Desktop/server/views/web/assets/css/custom.css
/mnt/d/Users/Elodie/Desktop/server/views/web/assets/js/jquery-1.10.2.js
/mnt/d/Users/Elodie/Desktop/server/views/web/assets/js/bootstrap.min.js
/mnt/d/Users/Elodie/Desktop/server/views/web/assets/js/jquery.metisMenu.js
/mnt/d/Users/Elodie/Desktop/server/views/web/assets/js/custom.js
/mnt/d/Users/Elodie/Desktop/server/views/web/assets/img/nom_blanc.png
/mnt/d/Users/Elodie/Desktop/server/views/web/assets/img/logo.png
</code>```

Elodie

答: You need to change the content type for the files.</p>

Title: Use CSS/IMG/JS with NodeJS

Body:
I create a http server with nodeJS and express.
I do the router for html pages but the css, the images and the js files are ignored.

I checked and the paths are ok.

I  tried to use static function of express but it doesn't work.

If you have an idea :)

server.js

var http = require("http");
var url = require("url");
var fs = require('fs');
//var express = require('express');
//var app = express();

//app.use(express.static( __dirname + "/views/web/assets/img"));

var server = http.createServer(function(req, res)
{
    var pathName = url.parse(req.url).pathname;
    console.log(__dirname + "/views/web" + pathName);
    fs.readFile( __dirname + "/views/web" + pathName , "utf8" , function(error , file){
     if(error) {
          res.writeHead(404 , {"Content-Type" : "text/html" });
          res.end();
     }else{
          res.writeHead(200 , {"Content-Type" : "text/html" });
          res.write(file);
          res.end();
     }
    });
});

server.listen(1337);
console.log("Serveur web lancé sur localhost:1337 ...");

An extract of login.html :

<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Profile - Login</title>
    <link rel="icon" type="image/png" href="assets/img/logo.png" />

    <link href="assets/css/bootstrap.css" rel="stylesheet" />

    <link href="assets/css/font-awesome.css" rel="stylesheet" />

    <link href="assets/css/custom.css" rel="stylesheet" />

   <link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css' />

The verification of paths :

proux@DESKTOP-VDRS1QF:/mnt/d/Users/Elodie/Desktop/server$ node server.js
Serveur web lancé sur localhost:1337 ...
/mnt/d/Users/Elodie/Desktop/server/views/web/
/mnt/d/Users/Elodie/Desktop/server/views/web/
/mnt/d/Users/Elodie/Desktop/server/views/web/login.html
/mnt/d/Users/Elodie/Desktop/server/views/web/assets/css/bootstrap.css
/mnt/d/Users/Elodie/Desktop/server/views/web/assets/css/font-awesome.css
/mnt/d/Users/Elodie/Desktop/server/views/web/assets/css/custom.css
/mnt/d/Users/Elodie/Desktop/server/views/web/assets/js/jquery-1.10.2.js
/mnt/d/Users/Elodie/Desktop/server/views/web/assets/js/bootstrap.min.js
/mnt/d/Users/Elodie/Desktop/server/views/web/assets/js/jquery.metisMenu.js
/mnt/d/Users/Elodie/Desktop/server/views/web/assets/js/custom.js
/mnt/d/Users/Elodie/Desktop/server/views/web/assets/img/nom_blanc.png
/mnt/d/Users/Elodie/Desktop/server/views/web/assets/img/logo.png

Elodie


问:
Spellchecker in eclipse doesn't recognize certain strings
Spellchecker in eclipse doesn't recognize certain strings like <code>'finalize', 'randomize'</code> even though they are correct. Is there a setting which needs to be enabled so that these don't show up as issues in the Eclipse java file editor? </p>

答: Add the strings to a user defined dictionary. Check out the General > Editors > Text Editors > Spelling page on the Preferences dialog (found under Window > Preferences).</p>

ContentLicense: CC BY-SA 2.5

Body: Spellchecker in eclipse doesn't recognize certain strings like 'finalize', 'randomize' even though they are correct. Is there a setting which needs to be enabled so that these don't show up as issues in the Eclipse java file editor?


问:
TestMain not run
I have a test package in go which tests some stuff that depend on reading a configuration. I want to read that configuration once before running all tests so I'm trying to use TestMain(m *testing.M):

main.go:

```<code>package tests

import (
    ...
)

var logger = logging.MustGetLogger("tests")

func TestMain(m *testing.M) {
    logger.Info("Initializing test suite")

    viper.SetConfigName("config")
    viper.AddConfigPath("..\\..\\")
    err := viper.ReadInConfig()
    if err == nil {
        os.Exit(m.Run())
    } else {
        logger.Fatal("Could not read configuration")
    }
}
</code>```

And I have another file in the same directory (and package) with a test.

repository_test.go:

```<code>package tests

import (
    ...
)

func TestCreation(t *testing.T) {
    aa := myModule.CreateRepository()
    assert.NotNil(t, aa)
}
</code>```

My problem is that the test fails because the configuration is not read from the file. When I try to debug the test in Gogland a breakpoint inside TestMain is not hit. When I run the tests from command line I don't see any printouts from TestMain.

Is there something special I should do to make it work? From what I read online I understood that if I define TestMain(m *testing.M) then it's going to run just once for the package and that's where I'm supposed to write any setup or teardown code.

答: Make sure that the run configuration is set to Package not File in Run | Edit Configurations... | Go Test | Name of your configuration and this should work. If it doesn't, please post the commands the IDE runs to execute the tests.</p>

Title: TestMain not run

Body:
I have a test package in go which tests some stuff that depend on reading a configuration. I want to read that configuration once before running all tests so I'm trying to use TestMain(m *testing.M):

main.go:

package tests

import (
    ...
)

var logger = logging.MustGetLogger("tests")

func TestMain(m *testing.M) {
    logger.Info("Initializing test suite")

    viper.SetConfigName("config")
    viper.AddConfigPath("..\\..\\")
    err := viper.ReadInConfig()
    if err == nil {
        os.Exit(m.Run())
    } else {
        logger.Fatal("Could not read configuration")
    }
}

And I have another file in the same directory (and package) with a test.

repository_test.go:

package tests

import (
    ...
)

func TestCreation(t *testing.T) {
    aa := myModule.CreateRepository()
    assert.NotNil(t, aa)
}

My problem is that the test fails because the configuration is not read from the file. When I try to debug the test in Gogland a breakpoint inside TestMain is not hit. When I run the tests from command line I don't see any printouts from TestMain.

Is there something special I should do to make it work? From what I read online I understood that if I define TestMain(m *testing.M) then it's going to run just once for the package and that's where I'm supposed to write any setup or teardown code.


问:
Remember cell selected before double click
I have an Excel sheet that has a doubleclick event in cell "P1" (runs a macro).

I may have cell "J30" (or any other cell) selected before I doubleclick "P1"
How can I remember, and return to the cell "J30" after the "P1" doubleclick?

Storing the active cell doesn't work because the first click in the doubleclick sequence, selects "P1".

I also tried rightclick on "P1", but it also selects "P1" before running the event.

答:
Using the method here you can do as follows</p>

```<code>Public PreviousActiveCell As Range

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)

    MsgBox ("Previous selection: " & PreviousActiveCell.Value & vbNewLine & _
    "Double clicked selection: " & Target.Value)

End Sub

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    Static pPrevious As Range
    Set PreviousActiveCell = pPrevious
    Set pPrevious = ActiveCell

End Sub
</code>```

Body:
Using the method here you can do as follows

Public PreviousActiveCell As Range

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)

    MsgBox ("Previous selection: " & PreviousActiveCell.Value & vbNewLine & _
    "Double clicked selection: " & Target.Value)

End Sub

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    Static pPrevious As Range
    Set PreviousActiveCell = pPrevious
    Set pPrevious = ActiveCell

End Sub


问:
Number comparision in java
This might be a very dumb question. I tried to reverse the input number and compare it.If they are same then, the output should be "the number entered is a palindrome" But, I'm getting out for every number like it is a palindrome. </p>

```<code>package com.practise.examples;

import java.util.Scanner;

public class Practise
{
    public static void main(String[] args) {

        Scanner s=new Scanner(System.in);
        System.out.println("enter the number to reverse it:\n");
        int num=s.nextInt();
        int revNum=0;

        while(num!=0)
        {
            revNum=revNum *10;
            revNum= revNum+ num%10;
            num=num/10;
        }
        System.out.println("the reverse of the number is: " +revNum);

            if(revNum==num)
            {
                System.out.println("the number is a palindrome" );

            }
            else
            {
                System.out.println("the number entered is not a palindrome");

            }

        }
    }
</code>```

答:
Easier way:

```<code>String num=Integer.toString(s.nextInt());
String revNum = new StringBuffer(num).reverse().toString();
System.out.println("the reverse of the number is: " +revNum);

if(revNum.equals(num))
    System.out.println("the number is a palindrome" );
else
    System.out.println("the number entered is not a palindrome");
</code>```

If you're insisting on your method:

```<code>    Scanner s=new Scanner(System.in);
    System.out.println("enter the number to reverse it:\n");
    int num=s.nextInt();
    int original = num;
    int revNum=0;

    while(num!=0)
    {
        revNum=revNum *10;
        revNum= revNum+ num%10;
        num=num/10;
    }
    System.out.println("the reverse of the number is: " +revNum);

        if(revNum==original)
        {
            System.out.println("the number is a palindrome" );

        }
        else
        {
            System.out.println("the number entered is not a palindrome");

        }

    }
</code>```

Title: Number comparision in java

Body:
This might be a very dumb question. I tried to reverse the input number and compare it.If they are same then, the output should be "the number entered is a palindrome" But, I'm getting out for every number like it is a palindrome.

package com.practise.examples;

import java.util.Scanner;

public class Practise
{
    public static void main(String[] args) {

        Scanner s=new Scanner(System.in);
        System.out.println("enter the number to reverse it:\n");
        int num=s.nextInt();
        int revNum=0;

        while(num!=0)
        {
            revNum=revNum *10;
            revNum= revNum+ num%10;
            num=num/10;
        }
        System.out.println("the reverse of the number is: " +revNum);

            if(revNum==num)
            {
                System.out.println("the number is a palindrome" );

            }
            else
            {
                System.out.println("the number entered is not a palindrome");

            }

        }
    }

Body:
Easier way:

String num=Integer.toString(s.nextInt());
String revNum = new StringBuffer(num).reverse().toString();
System.out.println("the reverse of the number is: " +revNum);

if(revNum.equals(num))
    System.out.println("the number is a palindrome" );
else
    System.out.println("the number entered is not a palindrome");

If you're insisting on your method:

    Scanner s=new Scanner(System.in);
    System.out.println("enter the number to reverse it:\n");
    int num=s.nextInt();
    int original = num;
    int revNum=0;

    while(num!=0)
    {
        revNum=revNum *10;
        revNum= revNum+ num%10;
        num=num/10;
    }
    System.out.println("the reverse of the number is: " +revNum);

        if(revNum==original)
        {
            System.out.println("the number is a palindrome" );

        }
        else
        {
            System.out.println("the number entered is not a palindrome");

        }

    }


问:
Get property with highest value from key value pair
In MongoDB, I have documents with a structure like this:

```<code>{
    _id: "123456...", // an ObjectId
    name: "foobar",
    classification: {
        class_1: 0.45,
        class_2: 0.11,
        class_3: 0.44
    }
}
</code>```

Using the aggregation pipeline, is it possible to give me an object that contains the highest classification? So, given the above, I would like something like this as result:

```<code>{
    _id: "123456...", // an ObjectId
    name: "foobar",
    classification: "class_1"
}
</code>```

I thought I could use $unwind but the classification property is not an array.

For what it's worth: I know there will always be three properties in classification, so it's ok to hard-code the keys in the query.

答:
You can use $indexOfArray operator to find the $max value in classification followed by projecting the key. $objectToArray to convert classification embedded doc into array of key value pairs in 3.4.4 version.

```<code>db.collection.aggregate([
    {
      "$addFields": {
        "classification": {
          "$let": {
            "vars": {
              "classificationkv": {
                "$objectToArray": "$classification"
              }
            },
            "in": {
              "$let": {
                "vars": {
                  "classificationmax": {
                    "$arrayElemAt": [
                      "$$classificationkv",
                      {
                        "$indexOfArray": [
                          "$$classificationkv.v",
                          {
                            "$max": "$$classificationkv.v"
                          }
                        ]
                      }
                    ]
                  }
                },
                "in": "$$classificationmax.k"
              }
            }
          }
        }
      }
    }
])
</code>```

Body:
In MongoDB, I have documents with a structure like this:

{
    _id: "123456...", // an ObjectId
    name: "foobar",
    classification: {
        class_1: 0.45,
        class_2: 0.11,
        class_3: 0.44
    }
}

Using the aggregation pipeline, is it possible to give me an object that contains the highest classification? So, given the above, I would like something like this as result:

{
    _id: "123456...", // an ObjectId
    name: "foobar",
    classification: "class_1"
}

I thought I could use $unwind but the classification property is not an array.

For what it's worth: I know there will always be three properties in classification, so it's ok to hard-code the keys in the query.

Body:
You can use $indexOfArray operator to find the $max value in classification followed by projecting the key. $objectToArray to convert classification embedded doc into array of key value pairs in 3.4.4 version.

db.collection.aggregate([
    {
      "$addFields": {
        "classification": {
          "$let": {
            "vars": {
              "classificationkv": {
                "$objectToArray": "$classification"
              }
            },
            "in": {
              "$let": {
                "vars": {
                  "classificationmax": {
                    "$arrayElemAt": [
                      "$$classificationkv",
                      {
                        "$indexOfArray": [
                          "$$classificationkv.v",
                          {
                            "$max": "$$classificationkv.v"
                          }
                        ]
                      }
                    ]
                  }
                },
                "in": "$$classificationmax.k"
              }
            }
          }
        }
      }
    }
])


问:
Where can I write Parse Cloud Code functions for android?
Is it possible to write a cloud code function directly into android studio? If not where could I write one? I can't find it on my parse dashboard

thanks

答:
Cloud code is only written in the express module of your app inside cloud/main.js file, you can create cloud functions there and call them from your android app.
Example:

```<code>Parse.Cloud.define("getPosts", function(request, response){
  var query = new Parse.Query("Posts");
  //TODO: query constraints here
  query.equalTo("key",request.params.text);
  query.find().then(function(results){
    response.success(results);
  });
});
</code>```

and you can call this function from android as below:

```<code>public static void getPosts(String text, final onSearch onSearch) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("text", text);
        ParseCloud.callFunctionInBackground("getPosts", hashMap, new
        FunctionCallback<List<Post>>() {
            @Override
            public void done(List<Post> object, ParseException e) {
                //TODO: use search results...
            }
        });
    }
</code>```

you can see other cloud functions and parameters in the docs: Cloud Code Guide

Body:
Cloud code is only written in the express module of your app inside cloud/main.js file, you can create cloud functions there and call them from your android app.
Example:

Parse.Cloud.define("getPosts", function(request, response){
  var query = new Parse.Query("Posts");
  //TODO: query constraints here
  query.equalTo("key",request.params.text);
  query.find().then(function(results){
    response.success(results);
  });
});

and you can call this function from android as below:

public static void getPosts(String text, final onSearch onSearch) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("text", text);
        ParseCloud.callFunctionInBackground("getPosts", hashMap, new
        FunctionCallback<List<Post>>() {
            @Override
            public void done(List<Post> object, ParseException e) {
                //TODO: use search results...
            }
        });
    }

you can see other cloud functions and parameters in the docs: Cloud Code Guide


问:
How to change an angular2 html dynamically?
Im trying to find a way to change some html lines of a component dynamically.

```<code><li *ngFor="p in persons" [attr.id]="p.id">
   <span> {{ p.name }} </span>
   <a (click)="getAge(p.id)">Get Age<a/>
</li>
</code>```

If the user clicks on the Get Age link i would like to replace the content inside of the corresponding li tag to something like:

```<code><span> {{ p.OtherProperty }} </span>
<a (click)="OtherMethod(p)">Call OtherMethod<a/>
</code>```

I found that ComponentFactoryResolver to create dynamic components, but i found it too overwhelming for just 2 lines of html. And i tried to change it by hand using jquery but it does not work to create the event bindings:

```<code>getAge(id) {
    //some work
    //remove the corresponding <li> content
    $('#' + id).append('<a (click)="getAnotherValue(p.name)">GetAnotherValue<a/>');
    $('#' + id).append('<span> {{ p.age}} </span>'); //this obviously doesnt work. But thats the ideia.
 }
</code>```

So how can i replace some html tags with angular attributes dynamically?

答:
Use ngIf to activate the code as shown:

```<code>     <li *ngFor="p in persons" [attr.id]="p.id">

        <div *ngIf=!p?.touched>

             <span> {{ p.name }} </span>
             <a (click)="getAge(p)">Get Age<a/>
        </div>

        <div *ngIf=p?.touched>
            <span> {{ p.age}} </span>
            <a (click)="getAnotherValue(p.name)">GetAnotherValue<a/>
       </div>

     </li>

    isGetAgeClicked=false;

        getAge(person) {
            //some work
            //remove the corresponding <li> content
         person.touched=true
         }
</code>```

Body:
Im trying to find a way to change some html lines of a component dynamically.

    {{ p.name }}
   Get Age

If the user clicks on the Get Age link i would like to replace the content inside of the corresponding li tag to something like:

 {{ p.OtherProperty }}
Call OtherMethod

I found that ComponentFactoryResolver to create dynamic components, but i found it too overwhelming for just 2 lines of html. And i tried to change it by hand using jquery but it does not work to create the event bindings:

getAge(id) {
    //some work
    //remove the corresponding
 content
    $('#' + id).append('GetAnotherValue');
    $('#' + id).append(' {{ p.age}} '); //this obviously doesnt work. But thats the ideia.
 }

So how can i replace some html tags with angular attributes dynamically?

Body:
Use ngIf to activate the code as shown:

     <li *ngFor="p in persons" [attr.id]="p.id">

        <div *ngIf=!p?.touched>

             <span> {{ p.name }} </span>
             <a (click)="getAge(p)">Get Age<a/>
        </div>

        <div *ngIf=p?.touched>
            <span> {{ p.age}} </span>
            <a (click)="getAnotherValue(p.name)">GetAnotherValue<a/>
       </div>

     </li>

    isGetAgeClicked=false;

        getAge(person) {
            //some work
            //remove the corresponding <li> content
         person.touched=true
         }


问:
Simplifiying JQuery
I'm running a blog on wordpress. I wish to make #first to disappear when #span1 is clicked but reappear when #second clicked. And #second, #third appear when #span1 clicked but disappear when #second clicked. It works but my questions is it possible to simplify this JQuery to make more simpler and neat. Because probably in future I will have to add more DIVs similar to #third. Other question is how do I control duration of fadeIn and fadeOut?

HTML

    $("#span1").on('click', function() {
       $("#second, #third").fadeIn();
       $("#first").hide();
    });

    $("#second").on('click', function() {
       $("#first").fadeIn();
       $("#second, #third").hide();

    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <span id="first">Blah blah blah, please <span id="span1">click here</span>.</span>
    <span id="second" style="display:none;">Cancel</span>
    <div id="third" style="display:none;">Test</div></code>```

This code is taken from accepted answer from original post.

答:
To accommodate for any future divs you could apply a class to all items that should not be visible when #first is visible. This way your JS code will not become any longer if you add more divs.

HTML

```<code><span id="first">Blah blah blah, please <span id="span1">click here</span>.</span>
<span id="second" class="notFirst">Cancel</span>
<div id="third" class="notFirst">Test</div>
<div id="fourth" class="notFirst">Test</div>
<div id="fifth" class="notFirst">Test</div>
<div id="sixth" class="notFirst">Test</div>
<div id="seventh" class="notFirst">Test</div>
</code>```

CSS

```<code>.notFirst {
  display: none;
}
</code>```

JS

```<code>$("#span1").on('click', function() {
  $(".notFirst").fadeIn(500);
  $("#first").hide();
});

$("#second").on('click', function() {
  $("#first").fadeIn(500);
  $(".notFirst").hide();
});
</code>```

For the duration of the fade effect you can simply add the number of milliseconds, as you can tell from the code.

Title: Simplifiying JQuery

Body:
I'm running a blog on wordpress. I wish to make #first to disappear when #span1 is clicked but reappear when #second clicked. And #second, #third appear when #span1 clicked but disappear when #second clicked. It works but my questions is it possible to simplify this JQuery to make more simpler and neat. Because probably in future I will have to add more DIVs similar to #third. Other question is how do I control duration of fadeIn and fadeOut?

HTML

    $("#span1").on('click', function() {
       $("#second, #third").fadeIn();
       $("#first").hide();
    });

    $("#second").on('click', function() {
       $("#first").fadeIn();
       $("#second, #third").hide();

    });

    Blah blah blah, please click here.
    Cancel

Test

This code is taken from accepted answer from original post.

Body:
To accommodate for any future divs you could apply a class to all items that should not be visible when #first is visible. This way your JS code will not become any longer if you add more divs.

HTML

<span id="first">Blah blah blah, please <span id="span1">click here</span>.</span>
<span id="second" class="notFirst">Cancel</span>
<div id="third" class="notFirst">Test</div>
<div id="fourth" class="notFirst">Test</div>
<div id="fifth" class="notFirst">Test</div>
<div id="sixth" class="notFirst">Test</div>
<div id="seventh" class="notFirst">Test</div>

CSS

.notFirst {
  display: none;
}

JS

$("#span1").on('click', function() {
  $(".notFirst").fadeIn(500);
  $("#first").hide();
});

$("#second").on('click', function() {
  $("#first").fadeIn(500);
  $(".notFirst").hide();
});

For the duration of the fade effect you can simply add the number of milliseconds, as you can tell from the code.


问:
Update text box value only on button click
I How can I display the text box value only on the click of a button? Below in the code snippet..

HTML:

```<code><input type="text" [(ngModel)]="serverName">
<button class="btn btn-primary" (click)="onAddClk">Add</button>
</code>```

TS File:

```<code>onAddClk(){

}
</code>```

How do I access my ngModel from TS file, so that on button click i can see the content of my text box?

答:
You can add a flag with *ngIf and set it to true when button is clicked.

```<code><div>
      <input type="text" [(ngModel)]="serverName">
      <button class="btn btn-primary" (click)="onAddClk()">Add</button>
      <div *ngIf="showServerName">{{serverName}}</div>
</div>
</code>```

component.ts:

```<code>serverName;
showServerName = false;

onAddClk(){
  alert("Server Name: " + this.serverName);
  this.showServerName = true;
}
</code>```

demo

Body:
I How can I display the text box value only on the click of a button? Below in the code snippet..

HTML:

<input type="text" [(ngModel)]="serverName">
<button class="btn btn-primary" (click)="onAddClk">Add</button>

TS File:

onAddClk(){

}

How do I access my ngModel from TS file, so that on button click i can see the content of my text box?

Body:
You can add a flag with *ngIf and set it to true when button is clicked.

<div>
      <input type="text" [(ngModel)]="serverName">
      <button class="btn btn-primary" (click)="onAddClk()">Add</button>
      <div *ngIf="showServerName">{{serverName}}</div>
</div>

component.ts:

serverName;
showServerName = false;

onAddClk(){
  alert("Server Name: " + this.serverName);
  this.showServerName = true;
}

demo


问:
MSBuild 15 - The type or namespace 'Fakes' does not exist in the namespace
I'm trying to set up automated builds and unit testing for a project which uses the Fakes library for it's unit tests. The project builds and tests fine on my Windows 10 PC (VS 2017 Enterprise installed), however using the same command to compile the project on the build server (also windows 10 with VS 2017 Enterprise) gives several errors about the Fakes not existing. The exact errors look like this:

XControllerTests.cs(10,20): error CS0234: The type or namespace 'Fakes' does not exist in the namespace 'System.Data.Common' (are you missing an assembly reference?) [C:\Runner\builds\xxx\XTests.csproj]

From my research, this is caused by using an old version of MSBuild, however I have checked the server, and confirmed it has the latest version & updates for visual studio installed. I also confirmed that the build script is using the correct version of MSBuild.exe, which is c:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\MSBuild.exe. Using this version on my desktop correctly compiles the project.

Why does the build not work on the (identical setup) build server?

答:
To extend @McMlok's answer above, i'll include what i did.

Source: My local VS2017 Premium Update 1 dev machine.

Target: The VS2017 Build Tools VM.

Copy Fakes folder:

From Source: c:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\Microsoft\VisualStudio\v15.0\

To Target: c:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\MSBuild\Microsoft\VisualStudio\v15.0\

Copy Microsoft.QualityTools.Testing.Fakes.ImportAfter.targets file:

From Source: c:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Microsoft.Common.targets\ImportAfter\

To Target: c:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\MSBuild\15.0\Microsoft.Common.Targets\ImportAfter\

Copy Microsoft.QualityTools.Testing.Fakes.dll file:

From Source: c:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\PublicAssemblies\

To Target: GAC / %windir%\Microsoft.NET\assembly

Builds fine now. Thanks McMlok.


问:
Exporting/Importing a WordPress database to reproduce a site on another machine
I am using WP 4.8 and using MAMP server.
Exporting Database:

I exported the database using the following steps:
-Select folder
-Select export tab
-After Clicking the radio button for 'Custom', I select 'Save output to file'(I leave the defaults)

Importing the DB (on the other machine):
(after decompressing a new wp site-naming it -and saving the wp-config.php)

-Open MAMP and choose the 'Import' Tab and select the backed up SQL file and press 'GO'

The following error:

```<code>Error

SQL query:

--
-- Database: `MyAceEL_db`
--

-- --------------------------------------------------------

--
-- Table structure for table `wp_commentmeta`
--

CREATE TABLE `wp_commentmeta` (
  `meta_id` bigint(20) UNSIGNED NOT NULL,
  `comment_id` bigint(20) UNSIGNED NOT NULL DEFAULT '0',
  `meta_key` varchar(255) COLLATE utf8mb4_unicode_520_ci DEFAULT NULL,
  `meta_value` longtext COLLATE utf8mb4_unicode_520_ci
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci;

MySQL said: Documentation
#1046 - No database selected
</code>```

So, either the problem might be either my export options or possibly an older version of MAMP on the laptop I'm trying to duplicate the site onto.

Any help would be greatly appreciated.

答:
You need to tell MySQL which of your possibly many databases it should apply this import (restore) to. So edit the file and add

```<code>USE `databasename`;
</code>```

on the first line, and then import the file using phpMyAdmin or whatever you are using

Body:
I am using WP 4.8 and using MAMP server.
Exporting Database:

I exported the database using the following steps:
-Select folder
-Select export tab
-After Clicking the radio button for 'Custom', I select 'Save output to file'(I leave the defaults)

Importing the DB (on the other machine):
(after decompressing a new wp site-naming it -and saving the wp-config.php)

-Open MAMP and choose the 'Import' Tab and select the backed up SQL file and press 'GO'

The following error:

Error

SQL query:

--
-- Database: `MyAceEL_db`
--

-- --------------------------------------------------------

--
-- Table structure for table `wp_commentmeta`
--

CREATE TABLE `wp_commentmeta` (
  `meta_id` bigint(20) UNSIGNED NOT NULL,
  `comment_id` bigint(20) UNSIGNED NOT NULL DEFAULT '0',
  `meta_key` varchar(255) COLLATE utf8mb4_unicode_520_ci DEFAULT NULL,
  `meta_value` longtext COLLATE utf8mb4_unicode_520_ci
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci;

MySQL said: Documentation
#1046 - No database selected

So, either the problem might be either my export options or possibly an older version of MAMP on the laptop I'm trying to duplicate the site onto.

Any help would be greatly appreciated.

Body:
You need to tell MySQL which of your possibly many databases it should apply this import (restore) to. So edit the file and add

USE `databasename`;

on the first line, and then import the file using phpMyAdmin or whatever you are using


问:
How to convert a Class Library project to a Web Application project?
Long story short, because of some issues with architecture and the fact that someone already put a few .aspx files in a class library, I'd like to just finish off the change and convert a class library to a web application.  This is using Visual Studio 2010 and .NET 4.0.  Is there an easy way of doing this?  Thanks!

EDIT: I was hoping for a better method than recreating the project, I had too many issues with broken references when I tried just creating a new project, including one I could never seem to fix.

答: Would it be easiest to just create a new web project, then copy over the class files and *.aspx files into the new web project?  </p>


问:
Add trailing slash to single directory in htaccess
Im currently trying to redirect a directory so that it adds a trailing slash at the end of the URL. I have tried

```<code>Redirect 301 /category/blog http://www.example/category/blog/
</code>```

and

```<code>Redirect 301 http://www.example.co.uk/category/blog http://www.example.co.uk/category/blog/
</code>```

However this causes an infinite loop whereby a trailing slash keeps getting appended to the end of the URL so it eventually becomes http://www.example.co.uk/category/blog/////////

Please note I only want to target this URL and no other URLs.

How can I get this to work?

答:
You can limit to an exact match, rather than a prefix match, with RedirectMatch: </p>

```<code>   RedirectMatch ^/category/blog$ http://www.example/category/blog/
</code>```

Body:
Im currently trying to redirect a directory so that it adds a trailing slash at the end of the URL. I have tried

Redirect 301 /category/blog http://www.example/category/blog/

and

Redirect 301 http://www.example.co.uk/category/blog http://www.example.co.uk/category/blog/

However this causes an infinite loop whereby a trailing slash keeps getting appended to the end of the URL so it eventually becomes http://www.example.co.uk/category/blog/////////

Please note I only want to target this URL and no other URLs.

How can I get this to work?

Body:
You can limit to an exact match, rather than a prefix match, with RedirectMatch:

   RedirectMatch ^/category/blog$ http://www.example/category/blog/


问:
How do I add a new value to a dictionary's key on top of the old one, to create a sum?
I'm trying to continously add a value to a dictionary's key's value, to form a sum of an old and new value.

My code checks if one string [str_1] from now is the same as a string from 1 second ago, [str_2] if it isn't, it should create a key with the key from 1 second ago, store for how long it's been on that string and move on to the next [str_?], repeating the process for a new string (creating a new key), then, if it meets any of the strings stored [str_?], it should take that key's value and add the new value on top of it, to create a sum.

```<code>seconds = 0
my_dict = {}
stop = 0

while stop != 1:

    then_string = getStringValue() #Copies a string from somewhere.
    sleep(1)
    now_string = getStringValue() #Copies a string from somewhere, note, we waited 1 sec.

    if then_string == now_string:
        seconds += 1
    elif then_string != now_string:
        my_dict[then_string] = seconds
        """This is where I'm stuck."""
        seconds = 0 #Resets the seconds.
    else:
        pass
</code>```

My problem is that once I get to the elif (strings changed, alarm for adding new value), it breaks.

It only adds the value of seconds, even if I were to do something like

```<code>my_dict[then_string] = my_dict.get(then_string) + seconds
</code>```

The value is a seemingly doubled number of seconds and it yields improper results.

My goal is to properly get the seconds spent on a string.

答:
I would utilize pythons object powers. Maybe consider code like this which is a lot simpler. </p>

```<code># Extend dict with a new increment method.
class increment_dict(dict):
    def increment(self, key):
        # increment increases key by one.
        # self.get(key,0) will return 0 if key not in self.
        self[key] = self.get(key, 0) + 1

running = True
i_dict = increment_dict()

# I dont need to remember what I saw last just increase the count of
# seconds by on every time I see a string. Both are constant runtime
# and without string equality this I suspect will be faster.
while running:
    sleep(1)
    i_dict.increment(getStringValue())
</code>```

Body:
I'm trying to continously add a value to a dictionary's key's value, to form a sum of an old and new value.

My code checks if one string [str_1] from now is the same as a string from 1 second ago, [str_2] if it isn't, it should create a key with the key from 1 second ago, store for how long it's been on that string and move on to the next [str_?], repeating the process for a new string (creating a new key), then, if it meets any of the strings stored [str_?], it should take that key's value and add the new value on top of it, to create a sum.

seconds = 0
my_dict = {}
stop = 0

while stop != 1:

    then_string = getStringValue() #Copies a string from somewhere.
    sleep(1)
    now_string = getStringValue() #Copies a string from somewhere, note, we waited 1 sec.

    if then_string == now_string:
        seconds += 1
    elif then_string != now_string:
        my_dict[then_string] = seconds
        """This is where I'm stuck."""
        seconds = 0 #Resets the seconds.
    else:
        pass

My problem is that once I get to the elif (strings changed, alarm for adding new value), it breaks.

It only adds the value of seconds, even if I were to do something like

my_dict[then_string] = my_dict.get(then_string) + seconds

The value is a seemingly doubled number of seconds and it yields improper results.

My goal is to properly get the seconds spent on a string.

Body:
I would utilize pythons object powers. Maybe consider code like this which is a lot simpler.

# Extend dict with a new increment method.
class increment_dict(dict):
    def increment(self, key):
        # increment increases key by one.
        # self.get(key,0) will return 0 if key not in self.
        self[key] = self.get(key, 0) + 1

running = True
i_dict = increment_dict()

# I dont need to remember what I saw last just increase the count of
# seconds by on every time I see a string. Both are constant runtime
# and without string equality this I suspect will be faster.
while running:
    sleep(1)
    i_dict.increment(getStringValue())


问:
Div leak parent container max width
I need to make a child div leak the parent container max width.
Now, i can only leak parent padding (knowing it).

I need this to wrap all the page on a container and make some sections leak.

Without this, i will need to set the container on every section.

Here is some snippets

Better snippet on codepen

.container {
  max-width: 500px;
  margin: 0 auto;
  padding: 0 30px;
  background: lightblue;
}

.child {
  background: lightcoral;
  height: 200px;
}

.child.cancel-padding {
  margin: 0 -30px;
}

.child.leaked {
}

html,
body {
  margin: 0;
  padding: 0;
}

* {
  text-align: center;
  font-family: sans-serif;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><small>note: see in fullscreen or on codepen</small>
<h1>what i have</h1>
<div class="container">
  <div class="child">A element inside a container</div>
</div>

<h1>what i need</h1>
<div class="container-leaked">
  <div class="child leaked">
    a element inside the container, but leaking all view width (100vw)
  </div>
</div>

<h1>what i can do now</h1>
<div class="container">
  <div class="child cancel-padding">Make the element cancel the parent padding, that's all</div>
</div>

<h1>Why i need</h1>
<p>
  i will wrap all the page in the container, but sometimes i need sections to leak the container with full view width.
</p></code>```

Note: on the demo, i've set the child height, but i will not have control of it. it's a dynamic content div, so height is dynamic.

答:
You can do it by using relative positioning. Indeed, you need position: relative on your container and your child -leak. Then, to center your child, you use

```<code>left: 50%;
transform: translateX(-50%);
</code>```

This works because your container is centered. So left: 50% will move the child left edge to 50% of its parent width from its initial position (which mean the center of its parent). Then, transform: translateX(-50%) will move the left edge of your child 50% of its width on the left. You then just need to add width: 100vw to make your child full width. Here is the snippet:

.page {
  position: relative;
}

.container {
  max-width: 100px;
  margin: 0 auto;
  padding: 0 30px;
  background: lightblue;
  position: relative;
}

.child-leak {
  height: 200px;
  background: lightcoral;
  position: relative;
  left: 50%;
  transform: translateX(-50%);
  padding: 10px;
  width: 100vw;
}

html, body{
  margin: 0;
  padding: 0;
  text-align: center;
  font-family: sans-serif;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="page">
  <h1>My title</h1>
  <div class="container">
    <div class="child-leak">
      My full width child
    </div>
  </div>
  <div>Below content</div>
</div></code>```

This technique for horizontally center an element works also for vertical centering. This works because a value in % for top, left, right and bottom refers to the first non static parent width and height. On the other hand, translate with a value in % use the element width and height.

Title: Div leak parent container max width

Body:
I need to make a child div leak the parent container max width.
Now, i can only leak parent padding (knowing it).

I need this to wrap all the page on a container and make some sections leak.

Without this, i will need to set the container on every section.

Here is some snippets

Better snippet on codepen

.container {
  max-width: 500px;
  margin: 0 auto;
  padding: 0 30px;
  background: lightblue;
}

.child {
  background: lightcoral;
  height: 200px;
}

.child.cancel-padding {
  margin: 0 -30px;
}

.child.leaked {
}

html,
body {
  margin: 0;
  padding: 0;
}

* {
  text-align: center;
  font-family: sans-serif;
}

note: see in fullscreen or on codepen

what i have

A element inside a container

what i need

    a element inside the container, but leaking all view width (100vw)

what i can do now

Make the element cancel the parent padding, that's all

Why i need

  i will wrap all the page in the container, but sometimes i need sections to leak the container with full view width.

Note: on the demo, i've set the child height, but i will not have control of it. it's a dynamic content div, so height is dynamic.

Body:
You can do it by using relative positioning. Indeed, you need position: relative on your container and your child -leak. Then, to center your child, you use

left: 50%;
transform: translateX(-50%);

This works because your container is centered. So left: 50% will move the child left edge to 50% of its parent width from its initial position (which mean the center of its parent). Then, transform: translateX(-50%) will move the left edge of your child 50% of its width on the left. You then just need to add width: 100vw to make your child full width. Here is the snippet:

.page {
  position: relative;
}

.container {
  max-width: 100px;
  margin: 0 auto;
  padding: 0 30px;
  background: lightblue;
  position: relative;
}

.child-leak {
  height: 200px;
  background: lightcoral;
  position: relative;
  left: 50%;
  transform: translateX(-50%);
  padding: 10px;
  width: 100vw;
}

html, body{
  margin: 0;
  padding: 0;
  text-align: center;
  font-family: sans-serif;
}

<div class="page">
  <h1>My title</h1>
  <div class="container">
    <div class="child-leak">
      My full width child
    </div>
  </div>
  <div>Below content</div>
</div>

This technique for horizontally center an element works also for vertical centering. This works because a value in % for top, left, right and bottom refers to the first non static parent width and height. On the other hand, translate with a value in % use the element width and height.


问:
Phoenix started throwing (UndefinedFunctionError) function :crypto.rand_bytes/1 is undefined or private
After and update to my system - MAC, my phoenix app compile just fine but throw this error any time I hit any route.

Server: localhost:4000 (http) Request: GET /
  ** (exit) an exception was raised:
      ** (UndefinedFunctionError) function :crypto.rand_bytes/1 is undefined or private. Did you mean one of:

```<code>  * rand_seed/0
  * rand_seed/1

    (crypto) :crypto.rand_bytes(20)
    (plug) lib/plug/request_id.ex:59: Plug.RequestId.generate_request_id/0
    (plug) lib/plug/request_id.ex:48: Plug.RequestId.get_request_id/2
    (plug) lib/plug/request_id.ex:42: Plug.RequestId.call/2
    (olars) lib/olars/endpoint.ex:1: Olars.Endpoint.phoenix_pipeline/1
    (olars) lib/plug/debugger.ex:93: Olars.Endpoint."call (overridable 3)"/2
    (olars) lib/olars/endpoint.ex:1: Olars.Endpoint.call/2
    (plug) lib/plug/adapters/cowboy/handler.ex:15: Plug.Adapters.Cowboy.Handler.upgrade/4
    (cowboy) src/cowboy_protocol.erl:442: :cowboy_protocol.execute/4
</code>```

My mix.exs

```<code>{:phoenix, "~> 1.2.0"},
      {:phoenix_pubsub, "~> 1.0"},
      {:phoenix_ecto, "~> 3.0"},
      {:phoenix_haml, github: "chrismccord/phoenix_haml"},
      {:mariaex, ">= 0.0.0"},
      {:phoenix_html, "~> 2.6"},
      {:phoenix_live_reload, "~> 1.0", only: :dev},
      {:gettext, "~> 0.11"},
      {:cowboy, "~> 1.0"},
      {:arc,  "~> 0.5.2"},
      {:arc_ecto, "~> 0.3.2"},
      {:ex_aws, "~> 0.4.10"},
      {:httpoison, "~> 0.9"},
      {:poison, "~> 2.0"},
      {:ecto, "~> 2.0.2", override: true},
      {:plug_auth, github: "smpallen99/plug_auth"},
      {:comeonin, "~> 2.1.0"},
      {:phoenix_calendar, "~> 0.1.2"},
      {:httpotion, "~> 3.0.0", override: true},
      {:timex, "~> 3.0"},
      {:quantum,github: "c-rack/quantum-elixir"},
      {:calendar, "~> 0.16.1"},
      {:uri_query, "~> 0.1.1"},
      {:scrivener, "~> 2.0"},
      {:scrivener_list, "~> 1.0"},
      {:number, "~> 0.5.0"},
      {:xlsxir, "~> 1.4.1"},
      {:new_relic, "~> 0.1.1"},
      {:retry, "~> 0.7"},
      {:credo, "~> 0.8", only: [:dev, :test], runtime: false}
</code>```

Elixr version: Elixir 1.4.5
Erlang Version: 20

Let me know if you guys need any other info.

答:
As mentioned in comments by @mudasobwa

put an explicit {:plug, "~> 1.3"} in your mix.ex file.

Fixed this issue.

Thanks everyone who tried to help.

Body:
After and update to my system - MAC, my phoenix app compile just fine but throw this error any time I hit any route.

Server: localhost:4000 (http) Request: GET /
  ** (exit) an exception was raised:
      ** (UndefinedFunctionError) function :crypto.rand_bytes/1 is undefined or private. Did you mean one of:

  * rand_seed/0
  * rand_seed/1

    (crypto) :crypto.rand_bytes(20)
    (plug) lib/plug/request_id.ex:59: Plug.RequestId.generate_request_id/0
    (plug) lib/plug/request_id.ex:48: Plug.RequestId.get_request_id/2
    (plug) lib/plug/request_id.ex:42: Plug.RequestId.call/2
    (olars) lib/olars/endpoint.ex:1: Olars.Endpoint.phoenix_pipeline/1
    (olars) lib/plug/debugger.ex:93: Olars.Endpoint."call (overridable 3)"/2
    (olars) lib/olars/endpoint.ex:1: Olars.Endpoint.call/2
    (plug) lib/plug/adapters/cowboy/handler.ex:15: Plug.Adapters.Cowboy.Handler.upgrade/4
    (cowboy) src/cowboy_protocol.erl:442: :cowboy_protocol.execute/4

My mix.exs

{:phoenix, "~> 1.2.0"},
      {:phoenix_pubsub, "~> 1.0"},
      {:phoenix_ecto, "~> 3.0"},
      {:phoenix_haml, github: "chrismccord/phoenix_haml"},
      {:mariaex, ">= 0.0.0"},
      {:phoenix_html, "~> 2.6"},
      {:phoenix_live_reload, "~> 1.0", only: :dev},
      {:gettext, "~> 0.11"},
      {:cowboy, "~> 1.0"},
      {:arc,  "~> 0.5.2"},
      {:arc_ecto, "~> 0.3.2"},
      {:ex_aws, "~> 0.4.10"},
      {:httpoison, "~> 0.9"},
      {:poison, "~> 2.0"},
      {:ecto, "~> 2.0.2", override: true},
      {:plug_auth, github: "smpallen99/plug_auth"},
      {:comeonin, "~> 2.1.0"},
      {:phoenix_calendar, "~> 0.1.2"},
      {:httpotion, "~> 3.0.0", override: true},
      {:timex, "~> 3.0"},
      {:quantum,github: "c-rack/quantum-elixir"},
      {:calendar, "~> 0.16.1"},
      {:uri_query, "~> 0.1.1"},
      {:scrivener, "~> 2.0"},
      {:scrivener_list, "~> 1.0"},
      {:number, "~> 0.5.0"},
      {:xlsxir, "~> 1.4.1"},
      {:new_relic, "~> 0.1.1"},
      {:retry, "~> 0.7"},
      {:credo, "~> 0.8", only: [:dev, :test], runtime: false}

Elixr version: Elixir 1.4.5
Erlang Version: 20

Let me know if you guys need any other info.


答: Create a new web application project in your solution and drag and drop all files from class library  to the new web application project.</p>

Title: How to convert a Class Library project to a Web Application project?

Body:
Long story short, because of some issues with architecture and the fact that someone already put a few .aspx files in a class library, I'd like to just finish off the change and convert a class library to a web application.  This is using Visual Studio 2010 and .NET 4.0.  Is there an easy way of doing this?  Thanks!

EDIT: I was hoping for a better method than recreating the project, I had too many issues with broken references when I tried just creating a new project, including one I could never seem to fix.


问:
Testing vi Editor Functionality with Python?
How do I write an automated test that can check the vi editor is properly working programmed using Python?</p>

答:
Save your script containing vi command as follows.

```<code>           cat script.sh
           vi abc.txt <<INPUT
           i
           Line 1
           Line 2
           ^[
           ZZ
           INPUT
</code>```

Use the python subprocess.check_call to check the status of execution

```<code>subprocess.check_call(["script.sh" , "arg1"])
</code>```

This will Run the command(script.sh) with arguments(if needed). Waits for command to complete. If the return code was zero then returns,
 otherwise raises CalledProcessError Exception.

Body:
Save your script containing vi command as follows.

           cat script.sh
           vi abc.txt <<INPUT
           i
           Line 1
           Line 2
           ^[
           ZZ
           INPUT

Use the python subprocess.check_call to check the status of execution

subprocess.check_call(["script.sh" , "arg1"])

This will Run the command(script.sh) with arguments(if needed). Waits for command to complete. If the return code was zero then returns,
 otherwise raises CalledProcessError Exception.


问:
BigQuery Bytes field individual field
I have a table in BigQuery with a BYTES field. In every row this field contains 6 bytes. How can I query the table so only rows are returned where the second byte is A, E, 2 or 6?

Thanks in advance,

Evert

答:
You can use the SUBSTR function to extract the byte at that position. Here is an example that you can run:

```<code>#standardSQL
WITH T AS (
  SELECT b'abcdef' AS s UNION ALL
  SELECT b'ABCDEF' UNION ALL
  SELECT b'123456' UNION ALL
  SELECT b'765432'
)
SELECT s
FROM T
WHERE SUBSTR(s, 2, 1) IN UNNEST(SPLIT(b'AE26', b''));
</code>```

To use your own table, just remove the WITH T AS (... part. If you want to match more characters, add them to the list that is passed to SPLIT.

Title: BigQuery Bytes field individual field

Body:
You can use the SUBSTR function to extract the byte at that position. Here is an example that you can run:

#standardSQL
WITH T AS (
  SELECT b'abcdef' AS s UNION ALL
  SELECT b'ABCDEF' UNION ALL
  SELECT b'123456' UNION ALL
  SELECT b'765432'
)
SELECT s
FROM T
WHERE SUBSTR(s, 2, 1) IN UNNEST(SPLIT(b'AE26', b''));

To use your own table, just remove the WITH T AS (... part. If you want to match more characters, add them to the list that is passed to SPLIT.


问:
Declaring variables for multiple scripts and best practices
What is the best way to put  variables in python for multiple scripts?

I have the following scripts:

main.py: This script to declare  common variables for one.py, two.py, and three.py. Also takes input from the user in interactive way and from the defined input file.

config.py: This script has all three scripts configurations inputs like ip-adress, ports details. etc.

one.py: I have written this script with class and it take inputs from main.py and config.py.

two.py: I have written this script with class and it take inputs from main.py and config.py.

three.py: I have written this script with class and it take inputs from main.py and config.py.

run.py: This script loads class objects for the one.py, two.py, and three.py and calls the functions defined in them.

main.py

```<code>list1 = []
a = "common for one.py,two.py and three.py"
</code>```

one.py

```<code>import main
main.list1.append("1")
</code>```

two.py

```<code>import main
main.list1.append("2")
</code>```

three.py

```<code>import main
main.list1.append("3")
</code>```

Running script:

run.py

```<code>import main
import one
import two
import three
# start performing
#call  one script functions
#call  two script functions
#call  three script functions
</code>```

I need some suggestions from you.

Am I am doing it in right way?

Will my scripts be easy for future maintenance?

Since I am putting variable list1 in main.py. It will first
appending some value in one.py and then two.py is going to access it.
My doubt is two.py is importing main.py in this case it does not
overwrite with empty list value? I have tested it, and it  works fine.
But I still want to take your suggestions for best practices.

答:
This doesn't look easy to maintain, since the values appended to the list only happen upon calling the import in main. Import them in the wrong order, or forget to import one of them, and you will get unexpected results.

In general, it is fine to share variables between scripts, but the various modules should not edit the values of the shared variables, rather, each module should be solely responsible for the values of its variables.

Body:
What is the best way to put  variables in python for multiple scripts?

I have the following scripts:

main.py: This script to declare  common variables for one.py, two.py, and three.py. Also takes input from the user in interactive way and from the defined input file.

config.py: This script has all three scripts configurations inputs like ip-adress, ports details. etc.

one.py: I have written this script with class and it take inputs from main.py and config.py.

two.py: I have written this script with class and it take inputs from main.py and config.py.

three.py: I have written this script with class and it take inputs from main.py and config.py.

run.py: This script loads class objects for the one.py, two.py, and three.py and calls the functions defined in them.

main.py

list1 = []
a = "common for one.py,two.py and three.py"

one.py

import main
main.list1.append("1")

two.py

import main
main.list1.append("2")

three.py

import main
main.list1.append("3")

Running script:

run.py

import main
import one
import two
import three
# start performing
#call  one script functions
#call  two script functions
#call  three script functions

I need some suggestions from you.

Am I am doing it in right way?

Will my scripts be easy for future maintenance?

Since I am putting variable list1 in main.py. It will first
appending some value in one.py and then two.py is going to access it.
My doubt is two.py is importing main.py in this case it does not
overwrite with empty list value? I have tested it, and it  works fine.
But I still want to take your suggestions for best practices.


问:
Does an additional "AND `columnname` LIKE '%'" hurt performance?

simple question: Does adding something like this to a query hurt performance in mysql or does it quickly get optimized away?

```<code>AND `name` LIKE '%'
</code>```

I've got no big database here that I could test it on.

By the way, I want this because I want users to be able to send some parameters to my server-side script that then grabs the prepared statement specified by the user and inserts the parameters. I want users to be able to omit parameters when searching without hurting the performance, and LIKE normally is relatively slow, right?

答:
Just tested with MySQL 5 using MyISAM tables.

```<code>SELECT * FROM tablename

17596 rows in set (0.28 sec)

SELECT * FROM tablename WHERE columnname LIKE '%'

17596 rows in set (0.20 sec)
</code>```

Seems that MySQL query engine optimizes things like '0'='0' and LIKE '%' away.

Body:
simple question: Does adding something like this to a query hurt performance in mysql or does it quickly get optimized away?

AND `name` LIKE '%'

I've got no big database here that I could test it on.

By the way, I want this because I want users to be able to send some parameters to my server-side script that then grabs the prepared statement specified by the user and inserts the parameters. I want users to be able to omit parameters when searching without hurting the performance, and LIKE normally is relatively slow, right?

Body:
Just tested with MySQL 5 using MyISAM tables.

SELECT * FROM tablename

17596 rows in set (0.28 sec)

SELECT * FROM tablename WHERE columnname LIKE '%'

17596 rows in set (0.20 sec)

Seems that MySQL query engine optimizes things like '0'='0' and LIKE '%' away.


问:
MySQL keeps closing connections
After every 8 hours of an idle_connection MySQL keeps closing the connection. I want to make it so MySQL will never close an idle_connection how would I do this?</p>

答:
You must access the my.cnf file. It should be in your etc directory.

Find where it says

wait_timeout = 28800
interactive_timeout = 28800

This says that MySQL will timeout after 28800 seconds (8 hours). Change it to whatever you want.

However, like is said in the comments, you probably should not do this.....

Title: MySQL keeps closing connections


问:
Number comparision in java
This might be a very dumb question. I tried to reverse the input number and compare it.If they are same then, the output should be "the number entered is a palindrome" But, I'm getting out for every number like it is a palindrome. </p>

```<code>package com.practise.examples;

import java.util.Scanner;

public class Practise
{
    public static void main(String[] args) {

        Scanner s=new Scanner(System.in);
        System.out.println("enter the number to reverse it:\n");
        int num=s.nextInt();
        int revNum=0;

        while(num!=0)
        {
            revNum=revNum *10;
            revNum= revNum+ num%10;
            num=num/10;
        }
        System.out.println("the reverse of the number is: " +revNum);

            if(revNum==num)
            {
                System.out.println("the number is a palindrome" );

            }
            else
            {
                System.out.println("the number entered is not a palindrome");

            }

        }
    }
</code>```

答: You have modified num for getting the reverse, and then using the same num for comparison. Use temporary variables.</p>

Title: Number comparision in java

Body:
This might be a very dumb question. I tried to reverse the input number and compare it.If they are same then, the output should be "the number entered is a palindrome" But, I'm getting out for every number like it is a palindrome.

package com.practise.examples;

import java.util.Scanner;

public class Practise
{
    public static void main(String[] args) {

        Scanner s=new Scanner(System.in);
        System.out.println("enter the number to reverse it:\n");
        int num=s.nextInt();
        int revNum=0;

        while(num!=0)
        {
            revNum=revNum *10;
            revNum= revNum+ num%10;
            num=num/10;
        }
        System.out.println("the reverse of the number is: " +revNum);

            if(revNum==num)
            {
                System.out.println("the number is a palindrome" );

            }
            else
            {
                System.out.println("the number entered is not a palindrome");

            }

        }
    }


问:
Java: Extract json values as individuals
I have this json in java:

```<code>jsonObj = {"ps":["2.16.840.1.113883.6.1","LOINC","2.34"]}
</code>```

jsonObj is response from an API, so I have it as jsonObject and I don't read it from any file.

Is there an easy way to extract all the values as individuals like jsonObj [1]?

答:
You should use a library to deserialize your JSON in a Java Object.
Libraries like GSON, Genson or Jackson.
Once you transform the json in a object, it will have a property called "ps" that will be an array (or a List)</p>

Body:
I have this json in java:

jsonObj = {"ps":["2.16.840.1.113883.6.1","LOINC","2.34"]}

jsonObj is response from an API, so I have it as jsonObject and I don't read it from any file.

Is there an easy way to extract all the values as individuals like jsonObj [1]?


答:
Try something like this:</p>

```<code>public static int reverse(int num)
{
  try
  {
    return Integer.parseInt(new StringBuilder(String.valueOf(num)).reverse().toString());
  }
  catch (Exception ex)
  {
    // Should not happen...
  }
}
</code>```

Title: Number comparision in java

Body:
Try something like this:

public static int reverse(int num)
{
  try
  {
    return Integer.parseInt(new StringBuilder(String.valueOf(num)).reverse().toString());
  }
  catch (Exception ex)
  {
    // Should not happen...
  }
}


问:
Next Button in Keyboard is not showing
I want when user type then instead of arrow key it should show the next button in keyboard.
So user not need to press the back to input next edittext.

Added the Layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:background="#D5D5D5"
    android:orientation="vertical" >

    <FrameLayout
        android:id="@+id/topLinearLayout"
        android:layout_width="fill_parent"
        android:layout_height="45dip"
        android:background="@drawable/bar" >

        <ImageView
            android:id="@+id/new_quote_imageView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:src="@drawable/new_quote_bar" />

        <TextView
            android:id="@+id/contactUs"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="center"
            android:gravity="center"
            android:text="@string/contact_us"
            android:textColor="@android:color/white"
            android:textSize="15sp" />
    </FrameLayout>

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

        <ScrollView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" >

            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:padding="10dip" >

                <LinearLayout
                    android:layout_width="fill_parent"
                    android:layout_height="0dip"
                    android:layout_weight=".7"
                    android:background="#EEEBE6"
                    android:orientation="vertical"
                    android:padding="15dip" >

                    <TextView
                        android:id="@+id/nameTextView"
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content"
                        android:paddingLeft="5dip"
                        android:text="@string/name"
                        android:textColor="@android:color/black"
                        android:textSize="16sp" />

                    <EditText
                        android:id="@+id/nameEditText"
                        android:layout_width="fill_parent"
                        android:layout_height="40dip"
                        android:layout_marginTop="10dip" />

                    <TextView
                        android:id="@+id/emailTextView"
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content"
                        android:paddingLeft="5dip"
                        android:text="@string/email"
                        android:textColor="@android:color/black"
                        android:textSize="16sp" />

                    <EditText
                        android:id="@+id/emailEditText"
                        android:layout_width="fill_parent"
                        android:layout_height="40dip"
                        android:layout_marginTop="10dip"
                        android:inputType="textEmailAddress" />

                    <TextView
                        android:id="@+id/commentsTextView"
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content"
                        android:paddingLeft="5dip"
                        android:text="@string/comments"
                        android:textColor="@android:color/black"
                        android:textSize="16sp" />

                    <EditText
                        android:id="@+id/commentsEditText"
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="10dip"
                        android:lines="5" />

                    <View
                        android:layout_width="fill_parent"
                        android:layout_height="1dp"
                        android:layout_marginTop="5dip"
                        android:background="@android:color/darker_gray" />

                    <LinearLayout
                        android:layout_width="fill_parent"
                        android:layout_height="match_parent"
                        android:layout_marginBottom="10dip"
                        android:layout_marginTop="10dip"
                        android:gravity="right|center_vertical"
                        android:weightSum="1" >

                        <Button
                            android:id="@+id/submitButton"
                            android:layout_width="0dip"
                            android:layout_height="35dip"
                            android:layout_weight=".3"
                            android:background="@drawable/button_background"
                            android:text="@string/submit"
                            android:textColor="@android:color/white"
                            android:textSize="16sp" />
                    </LinearLayout>
                </LinearLayout>
            </LinearLayout>
        </ScrollView>
    </LinearLayout>

</LinearLayout>
</code>```

Please help me for this.

Thanks in advance.

答:
```<code>Simply use
android:inputType="textNoSuggestions"
android:maxLines="1"

and remove if you have used digits.

android:digits
</code>```

Title: Next Button in Keyboard is not showing

Body:
I want when user type then instead of arrow key it should show the next button in keyboard.
So user not need to press the back to input next edittext.

Added the Layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:background="#D5D5D5"
    android:orientation="vertical" >

    <FrameLayout
        android:id="@+id/topLinearLayout"
        android:layout_width="fill_parent"
        android:layout_height="45dip"
        android:background="@drawable/bar" >

        <ImageView
            android:id="@+id/new_quote_imageView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:src="@drawable/new_quote_bar" />

        <TextView
            android:id="@+id/contactUs"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="center"
            android:gravity="center"
            android:text="@string/contact_us"
            android:textColor="@android:color/white"
            android:textSize="15sp" />
    </FrameLayout>

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

        <ScrollView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" >

            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:padding="10dip" >

                <LinearLayout
                    android:layout_width="fill_parent"
                    android:layout_height="0dip"
                    android:layout_weight=".7"
                    android:background="#EEEBE6"
                    android:orientation="vertical"
                    android:padding="15dip" >

                    <TextView
                        android:id="@+id/nameTextView"
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content"
                        android:paddingLeft="5dip"
                        android:text="@string/name"
                        android:textColor="@android:color/black"
                        android:textSize="16sp" />

                    <EditText
                        android:id="@+id/nameEditText"
                        android:layout_width="fill_parent"
                        android:layout_height="40dip"
                        android:layout_marginTop="10dip" />

                    <TextView
                        android:id="@+id/emailTextView"
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content"
                        android:paddingLeft="5dip"
                        android:text="@string/email"
                        android:textColor="@android:color/black"
                        android:textSize="16sp" />

                    <EditText
                        android:id="@+id/emailEditText"
                        android:layout_width="fill_parent"
                        android:layout_height="40dip"
                        android:layout_marginTop="10dip"
                        android:inputType="textEmailAddress" />

                    <TextView
                        android:id="@+id/commentsTextView"
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content"
                        android:paddingLeft="5dip"
                        android:text="@string/comments"
                        android:textColor="@android:color/black"
                        android:textSize="16sp" />

                    <EditText
                        android:id="@+id/commentsEditText"
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="10dip"
                        android:lines="5" />

                    <View
                        android:layout_width="fill_parent"
                        android:layout_height="1dp"
                        android:layout_marginTop="5dip"
                        android:background="@android:color/darker_gray" />

                    <LinearLayout
                        android:layout_width="fill_parent"
                        android:layout_height="match_parent"
                        android:layout_marginBottom="10dip"
                        android:layout_marginTop="10dip"
                        android:gravity="right|center_vertical"
                        android:weightSum="1" >

                        <Button
                            android:id="@+id/submitButton"
                            android:layout_width="0dip"
                            android:layout_height="35dip"
                            android:layout_weight=".3"
                            android:background="@drawable/button_background"
                            android:text="@string/submit"
                            android:textColor="@android:color/white"
                            android:textSize="16sp" />
                    </LinearLayout>
                </LinearLayout>
            </LinearLayout>
        </ScrollView>
    </LinearLayout>

</LinearLayout>

Please help me for this.

Thanks in advance.


答:
LIKE's can be expensive indeed, depending on the indexes you have on the name field. Have you tried to measure your query?

```<code>EXPLAIN [EXTENDED] SELECT [...] AND `name` LIKE '%'
</code>```

See also http://dev.mysql.com/doc/refman/5.0/en/explain.html

Then MySQL will give you indications whether it has optimised the unnecessary LIKE clause away or not.

Title: Does an additional "AND `columnname` LIKE '%'" hurt performance?

Body:
LIKE's can be expensive indeed, depending on the indexes you have on the name field. Have you tried to measure your query?

EXPLAIN [EXTENDED] SELECT [...] AND `name` LIKE '%'

See also http://dev.mysql.com/doc/refman/5.0/en/explain.html

Then MySQL will give you indications whether it has optimised the unnecessary LIKE clause away or not.


问:
isPrime Function for Python Language
So I was able to solve this problem with a little bit of help from the internet and this is what I got:

```<code>def isPrime(n):
    for i in range(2,int(n**0.5)+1):
        if n%i==0:
            return False

    return True
</code>```

But my question really is how to do it, but WHY. I understand that 1 is not considered a "prime" number even though it is, and I understand that if it divides by ANYTHING within the range it is automatically not a prime thus the return False statement. but my question is what role does the squar-rooting the "n" play here?

P.s. I am very inexperienced and have just been introduced to programming a month ago.

答:
I have a new solution which I think might be faster than any of the mentioned
Function in Python

It's based on the idea that:
N/D = R
for any arbitrary number N, the least possible number to divide N (if not prime) is D=2 and the corresponding result R is (N/2) (highest).

As D goes bigger the result R gets smaller ex: divide by D = 3 results R = (N/3)
so when we are checking if N is divisible by D we are also checking if it's divisible by R

so as D goes bigger and R goes smaller till (D == R == square root(N))

then we only need to check numbers from 2 to sqrt(N)
another tip to save time, we only need to check the odd numbers as it the number is divisible by any even number it will also be divisible by 2.

so the sequence will be 3,5,7,9,......,sqrt(N).

```<code>import math
def IsPrime (n):
    if (n <= 1 or n % 2 == 0):return False
    if n == 2:return True
    for i in range(3,int(math.sqrt(n))+1,2):
        if (n % i) == 0:
            return False
    return True
</code>```

ContentLicense: CC BY-SA 4.0

Title: isPrime Function for Python Language

Body:
So I was able to solve this problem with a little bit of help from the internet and this is what I got:

def isPrime(n):
    for i in range(2,int(n**0.5)+1):
        if n%i==0:
            return False

    return True

But my question really is how to do it, but WHY. I understand that 1 is not considered a "prime" number even though it is, and I understand that if it divides by ANYTHING within the range it is automatically not a prime thus the return False statement. but my question is what role does the squar-rooting the "n" play here?

P.s. I am very inexperienced and have just been introduced to programming a month ago.

Body:
I have a new solution which I think might be faster than any of the mentioned
Function in Python

It's based on the idea that:
N/D = R
for any arbitrary number N, the least possible number to divide N (if not prime) is D=2 and the corresponding result R is (N/2) (highest).

As D goes bigger the result R gets smaller ex: divide by D = 3 results R = (N/3)
so when we are checking if N is divisible by D we are also checking if it's divisible by R

so as D goes bigger and R goes smaller till (D == R == square root(N))

then we only need to check numbers from 2 to sqrt(N)
another tip to save time, we only need to check the odd numbers as it the number is divisible by any even number it will also be divisible by 2.

so the sequence will be 3,5,7,9,......,sqrt(N).

import math
def IsPrime (n):
    if (n <= 1 or n % 2 == 0):return False
    if n == 2:return True
    for i in range(3,int(math.sqrt(n))+1,2):
        if (n % i) == 0:
            return False
    return True