问:
Node Async with functions
I'm trying to use Async module with 2 functions, here is the code. There's something wrong, the  console.dir are working, but the last one in function(err, results) doesn't work. Can any one help me?

The last step that I want to do is render the oftArrayFullInfo and oftNextInfo

```<code>async.parallel({
        one: function(callback){
            auxFunctions.foofunc1(foo1, foo1, function(oftArrayFullInfo){
                console.log("****** ASYNC 1 ARRAY");
                console.dir(oftArrayFullInfo);
                callback(oftArrayFullInfo);
            });
        },
        two: function(callback){
            auxFunctions.foofunc2(foo1, foo1, function(oftNextInfo){
                console.log("****** ASYNC 2 ARRAY");
                console.dir(oftNextInfo);
                callback(oftNextInfo);
            });
        }
    },
    function(err, results){
        console.log("****** RENDER 1");
        console.dir(results.one);
        console.log("****** RENDER 2")
        console.dir(results.two);
        //res.render('myView', {title: 'Job Info', oftArrayFullInfo}, {title: 'Next Jobs Info', oftNextInfo});
    });
</code>```

答:
ok you did everything right except when u send data from re.render() to your templates you have to send in key,value pairs.so intead

```<code>res.render('myView', {title: 'Job Info', oftArrayFullInfo}, {title: 'Next Jobs Info', oftNextInfo});
</code>```

you should use

```<code>res.render('myView', {title: 'Job Info', arrayFullInfo : oftArrayFullInfo}, {title: 'Next Jobs Info', nextInfo : oftNextInfo});
</code>```

now you can access these values with the key names  arrayFullInfo and nextInfo in your template

Title: Node Async with functions

Body:
I'm trying to use Async module with 2 functions, here is the code. There's something wrong, the  console.dir are working, but the last one in function(err, results) doesn't work. Can any one help me?

The last step that I want to do is render the oftArrayFullInfo and oftNextInfo

async.parallel({
        one: function(callback){
            auxFunctions.foofunc1(foo1, foo1, function(oftArrayFullInfo){
                console.log("****** ASYNC 1 ARRAY");
                console.dir(oftArrayFullInfo);
                callback(oftArrayFullInfo);
            });
        },
        two: function(callback){
            auxFunctions.foofunc2(foo1, foo1, function(oftNextInfo){
                console.log("****** ASYNC 2 ARRAY");
                console.dir(oftNextInfo);
                callback(oftNextInfo);
            });
        }
    },
    function(err, results){
        console.log("****** RENDER 1");
        console.dir(results.one);
        console.log("****** RENDER 2")
        console.dir(results.two);
        //res.render('myView', {title: 'Job Info', oftArrayFullInfo}, {title: 'Next Jobs Info', oftNextInfo});
    });

Body:
ok you did everything right except when u send data from re.render() to your templates you have to send in key,value pairs.so intead

res.render('myView', {title: 'Job Info', oftArrayFullInfo}, {title: 'Next Jobs Info', oftNextInfo});

you should use

res.render('myView', {title: 'Job Info', arrayFullInfo : oftArrayFullInfo}, {title: 'Next Jobs Info', nextInfo : oftNextInfo});

now you can access these values with the key names  arrayFullInfo and nextInfo in your template


来源: stackexchange

问:
WPF DrawingContext DrawGlyphRun blur text
I'm using the DrawingContext DrawGlyphRun(GlyphRun) function to draw text in the Canvas using the solution from https://smellegantcode.wordpress.com/2008/07/03/glyphrun-and-so-forth/.

I'm using this over the FormattedText because it's faster and it's also used for calculating text width.

This works well except for 2 problems:

Text is blurred (see below the image). Text at the top is displayed using GlyphRun. The bottom text is displayed using FormattedText which has better quality.

Cannot display Japanese or Chinese characters.

Problem with characters seems to be that GlyphTypeface.CharacterToGlyphMap cannot find the jp or cn character, so I'm not sure how exactly to deal with these characters.

答:
I just found your question after some research that I made.

GlyphRun created using public constructors creates object with TextFormattingMode = Ideal

All WPF contols for their rendring use methods/constructors that accepts TextFormattingMode as parameter.

You can call GlyphRun.TryCreate() static method via reflection:

```<code>internal static GlyphRun TryCreate(
        GlyphTypeface           glyphTypeface,
        int                     bidiLevel,
        bool                    isSideways,
        double                  renderingEmSize,
        IList<ushort>           glyphIndices,
        Point                   baselineOrigin,
        IList<double>           advanceWidths,
        IList<Point>            glyphOffsets,
        IList<char>             characters,
        string                  deviceFontName,
        IList<ushort>           clusterMap,
        IList<bool>             caretStops,
        XmlLanguage             language,
        TextFormattingMode      textLayout
        )
</code>```

but the problem that you need to get advanceWidths with TextFormattingMode = Ideal. For this you need access via reflection to internal methods provided by GlyphTypeface class.

GlyphTypeface.AdvanceWidths property that returns dictionary with these widths internally calls to

```<code>internal double GetAdvanceWidth(ushort glyph, TextFormattingMode textFormattingMode, bool isSideways)
</code>```

when you access dictionary by index with textFormattingMode = TextFormattingMode.Ideal

You can download .Net source code and check it yourself.

As for your second question I think that you use chars instead of unicode code points to get glyph index.

ContentLicense: CC BY-SA 3.0

Body:
I just found your question after some research that I made.

GlyphRun created using public constructors creates object with TextFormattingMode = Ideal

All WPF contols for their rendring use methods/constructors that accepts TextFormattingMode as parameter.

You can call GlyphRun.TryCreate() static method via reflection:

internal static GlyphRun TryCreate(
        GlyphTypeface           glyphTypeface,
        int                     bidiLevel,
        bool                    isSideways,
        double                  renderingEmSize,
        IList<ushort>           glyphIndices,
        Point                   baselineOrigin,
        IList<double>           advanceWidths,
        IList<Point>            glyphOffsets,
        IList<char>             characters,
        string                  deviceFontName,
        IList<ushort>           clusterMap,
        IList<bool>             caretStops,
        XmlLanguage             language,
        TextFormattingMode      textLayout
        )

but the problem that you need to get advanceWidths with TextFormattingMode = Ideal. For this you need access via reflection to internal methods provided by GlyphTypeface class.

GlyphTypeface.AdvanceWidths property that returns dictionary with these widths internally calls to

internal double GetAdvanceWidth(ushort glyph, TextFormattingMode textFormattingMode, bool isSideways)

when you access dictionary by index with textFormattingMode = TextFormattingMode.Ideal

You can download .Net source code and check it yourself.

As for your second question I think that you use chars instead of unicode code points to get glyph index.


问:
Is it reasonable to synchronize on a local variable?
From the Java memory model, we know that every thread has its own thread stack, and that local variables are placed in each thread's own thread stack.

And that other threads can't access these local variables.

So in which case should we synchronize on local variables?

答: Yes, it does make sense when the local variable is used to synchronize access to a block of code from threads that are defined and created in the same method as the local variable.</p>

ContentLicense: CC BY-SA 4.0


问:
Add data to retrained Inception net
I did few experiments with Google's Inception-v3 net from the tutorial (https://www.tensorflow.org/versions/r0.9/how_tos/image_retraining/index.html)

If I have a large enough data set, then it's fine. But what about when a data set is relatively small and is growing on the go (roughly 10% a day)?

Is there a way to add more data points to the retrained net?
I don't think that retraining a whole model each time we get a new data point doesn't seem efficient.

答: There are checkpoints in TensorFlow if you want to pause and resume. Another option is to train different categories on different layers. It's possible to use your outputs from image retraining as inputs. Better hardware should also be considered.</p>

Title: Add data to retrained Inception net


问:
Regex. Find paragraph containing some word
In text like this:

1 bla bla bla bla bla

2 bla bla bla bla TEXT bla

3 bla bla bla bla bla

4 bla bla bla bla TEXT bla

5 bla bla bla bla bla

I have to find paragraphs (between p tags) that contain string "TEXT".

I tried
.*?(TEXT).*?<\/p>

and I tried
(?!
).*?(TEXT).*?<\/p>

But it doesnt solve the problem.

答:
((?!<\/p>).)*(TEXT) to make sure 'Text' in one

See demo

var regex = /
((?!<\/p>).)*?(TEXT).*?<\/p>/g;
var text = '
1 bla bla bla bla bla

2 bla bla bla bla TEXT bla

3 bla bla bla bla bla

4 bla bla bla bla TEXT bla

5 bla bla bla bla bla
';
console.log(text.match(regex));```

Body:
((?!<\/p>).)*(TEXT) to make sure 'Text' in one <p></p>

See demo

var regex = /<p>((?!<\/p>).)*?(TEXT).*?<\/p>/g;
var text = '<p>1 bla bla <em>bla</em> bla bla</p><p>2 bla bla <em>bla</em> bla TEXT bla</p><p>3 bla bla <em>bla</em> bla bla</p><p>4 bla bla <em>bla</em> bla TEXT bla</p><p>5 bla bla <em>bla</em> bla bla</p>';
console.log(text.match(regex));


问:
Establish FtpWebRequest through a HTTP proxy using the CONNECT method
I try to establish a FTP connection using the FtpWebRequest. I need to establish the connection through a squid proxy server, that requires me to send a CONNECT command first.

I have tried the code below, but this results in a GET request to the proxy server, which it refuses.

```<code>FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://" +server);
request.Credentials = new NetworkCredential(user, pwd);
var webproxy = new WebProxy(new Uri("http://" + proxy+ ":" + proxyPort));
webproxy.UseDefaultCredentials = true;
request.Proxy = webproxy;
request.UsePassive = true;
request.Method = WebRequestMethods.Ftp.ListDirectory;

FtpWebResponse response = (FtpWebResponse)request.GetResponse();
</code>```

Is there any way that I can use the FtpWebRequest to establish my connection through the proxy?

If not, do you know a good and hopefully free .NET FTP client that I can use?
Thank you very much for your help.

答:
FtpWebRequest supports HTTP proxy (and CONNECT command is mandatory part of that support). Your code is correct.

Though the HTTP proxy is not supported uploads (it is for all other operations). So maybe your actual problem is the upload, while you do not mention it.

For FTP uploads through HTTP proxy you have to use a 3rd party FTP client.

For example with WinSCP .NET assembly, you can use:

```<code>// Setup session options
SessionOptions sessionOptions = new SessionOptions
{
    Protocol = Protocol.Ftp,
    HostName = "example.com",
    UserName = "user",
    Password = "mypassword",
};

// Configure proxy
sessionOptions.AddRawSettings("ProxyMethod", "3"); // HTTP proxy
sessionOptions.AddRawSettings("ProxyHost", "proxy");

using (Session session = new Session())
{
    // Connect
    session.Open(sessionOptions);

    // Upload file
    string localFilePath = @"C:\path\file.txt";
    string pathUpload = "/file.txt";
    session.PutFiles(localFilePath, pathUpload).Check();
}
</code>```

For the options for the SessionOptions.AddRawSettings, see raw settings.

Easier is to have WinSCP GUI generate C# FTP code template for you.

Note that WinSCP .NET assembly is not a native .NET library. It's rather a thin .NET wrapper over a console application.

(I'm the author of WinSCP)

Body:
I try to establish a FTP connection using the FtpWebRequest. I need to establish the connection through a squid proxy server, that requires me to send a CONNECT command first.

I have tried the code below, but this results in a GET request to the proxy server, which it refuses.

FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://" +server);
request.Credentials = new NetworkCredential(user, pwd);
var webproxy = new WebProxy(new Uri("http://" + proxy+ ":" + proxyPort));
webproxy.UseDefaultCredentials = true;
request.Proxy = webproxy;
request.UsePassive = true;
request.Method = WebRequestMethods.Ftp.ListDirectory;

FtpWebResponse response = (FtpWebResponse)request.GetResponse();

Is there any way that I can use the FtpWebRequest to establish my connection through the proxy?

If not, do you know a good and hopefully free .NET FTP client that I can use?
Thank you very much for your help.

Body:
FtpWebRequest supports HTTP proxy (and CONNECT command is mandatory part of that support). Your code is correct.

Though the HTTP proxy is not supported uploads (it is for all other operations). So maybe your actual problem is the upload, while you do not mention it.

For FTP uploads through HTTP proxy you have to use a 3rd party FTP client.

For example with WinSCP .NET assembly, you can use:

// Setup session options
SessionOptions sessionOptions = new SessionOptions
{
    Protocol = Protocol.Ftp,
    HostName = "example.com",
    UserName = "user",
    Password = "mypassword",
};

// Configure proxy
sessionOptions.AddRawSettings("ProxyMethod", "3"); // HTTP proxy
sessionOptions.AddRawSettings("ProxyHost", "proxy");

using (Session session = new Session())
{
    // Connect
    session.Open(sessionOptions);

    // Upload file
    string localFilePath = @"C:\path\file.txt";
    string pathUpload = "/file.txt";
    session.PutFiles(localFilePath, pathUpload).Check();
}

For the options for the SessionOptions.AddRawSettings, see raw settings.

Easier is to have WinSCP GUI generate C# FTP code template for you.

Note that WinSCP .NET assembly is not a native .NET library. It's rather a thin .NET wrapper over a console application.

(I'm the author of WinSCP)


问:
Add a dtd using nokogiri builder
I am using nokogiri to generate svg pictures. I would like to add the correct xml preamble and svg DTD declaration to get something like:

```<code><?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg>
...
</code>```

With builder I could use instruct! and declare! but I want to stick with nokogiri because I use it for other purpose in my project and I want to stay low on requirements. Do you have some ideas ?

Thanks

答:
For those working with HTML, Eric Walkers' example doesn't quite work since a doctype is automatically added. You need to remove it first:

```<code>builder = Nokogiri::HTML::Builder.new do |html|
  html.doc.internal_subset.remove
  html.doc.create_internal_subset('html', nil, nil)
end
</code>```

This will add the HTML5 doctype a.k.a. <!DOCTYPE html>

ContentLicense: CC BY-SA 2.5

Title: Add a dtd using nokogiri builder

Body:
I am using nokogiri to generate svg pictures. I would like to add the correct xml preamble and svg DTD declaration to get something like:

<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg>
...

With builder I could use instruct! and declare! but I want to stick with nokogiri because I use it for other purpose in my project and I want to stay low on requirements. Do you have some ideas ?

Thanks

Body:
For those working with HTML, Eric Walkers' example doesn't quite work since a doctype is automatically added. You need to remove it first:

builder = Nokogiri::HTML::Builder.new do |html|
  html.doc.internal_subset.remove
  html.doc.create_internal_subset('html', nil, nil)
end

This will add the HTML5 doctype a.k.a. <!DOCTYPE html>


问:
CNTK: Workaround for loading pretrained word embeddings from file
It seems like it is not possible to load pretrained embeddings to a layer. See here

What I did as a workaround is the following:

```<code>    model = create_model()

    E = [p for p in model.parameters if p.name == 'E'][0]
    emb = np.asarray(np.loadtxt('embeddings.txt', delimiter=' '), dtype='float32')
    model = model.clone(CloneMethod.clone, { E: constant(emb) })
</code>```

with embeddings.txt having the following format where the number of rows is the number of words in the vocabulary I use and the number of columns is the dimensions I have chosen for my embeddings:
-0.05952413007617 0.12596195936203 -0.189506858587265 ...
-0.0871662572026253 -0.0454806201159954 -0.126074999570847 ...
...

Does the above seem like a correct workaround?
I kicked off a training session and the number of parameters is reduced compared to what I had when training the embeddings layer which could be a good indication.

答:
This has been fixed. For example:</p>

```<code># embedding, initialized from a user-supplied constant weight table
e = Embedding(weights=[[1, 3, 2], [3, 4, 1]])

# (you would get the weights from a file instead)

# test it:
y = Input(2)

dat = np.array([[-1., 1.]], dtype=np.float32)
res = e(y).eval({y: dat})

npout = np.matrix(dat[0]) * e.E.value
np.testing.assert_array_equal(res[0], npout, err_msg='Error in constant embedding layer')
</code>```

Body:
It seems like it is not possible to load pretrained embeddings to a layer. See here

What I did as a workaround is the following:

    model = create_model()

    E = [p for p in model.parameters if p.name == 'E'][0]
    emb = np.asarray(np.loadtxt('embeddings.txt', delimiter=' '), dtype='float32')
    model = model.clone(CloneMethod.clone, { E: constant(emb) })

with embeddings.txt having the following format where the number of rows is the number of words in the vocabulary I use and the number of columns is the dimensions I have chosen for my embeddings:
-0.05952413007617 0.12596195936203 -0.189506858587265 ...
-0.0871662572026253 -0.0454806201159954 -0.126074999570847 ...
...

Does the above seem like a correct workaround?
I kicked off a training session and the number of parameters is reduced compared to what I had when training the embeddings layer which could be a good indication.

Body:
This has been fixed. For example:

# embedding, initialized from a user-supplied constant weight table
e = Embedding(weights=[[1, 3, 2], [3, 4, 1]])

# (you would get the weights from a file instead)

# test it:
y = Input(2)

dat = np.array([[-1., 1.]], dtype=np.float32)
res = e(y).eval({y: dat})

npout = np.matrix(dat[0]) * e.E.value
np.testing.assert_array_equal(res[0], npout, err_msg='Error in constant embedding layer')


问:
EOFException when reading a custom class with ObjectOutputStream
I'm encountering the following EOFException:

```<code>java.io.EOFException
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2903)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1502)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:422)
at Practica.Animalario.Poblacion.abrirPoblacion(Poblacion.java:37)
at InterfazGrafica.Ventana.actionPerformed(Ventana.java:122)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6533)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
at java.awt.Component.processEvent(Component.java:6298)
at java.awt.Container.processEvent(Container.java:2236)
at java.awt.Component.dispatchEventImpl(Component.java:4889)
at java.awt.Container.dispatchEventImpl(Container.java:2294)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
at java.awt.Container.dispatchEventImpl(Container.java:2280)
at java.awt.Window.dispatchEventImpl(Window.java:2746)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:90)
at java.awt.EventQueue$4.run(EventQueue.java:731)
at java.awt.EventQueue$4.run(EventQueue.java:729)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
</code>```

While executing this code that I've written. The purpose of this code is to read / write the objects into a file:

```<code>public class Poblacion implements Serializable{
    public Raton poblacion [];
    public String nombrePoblacion;
    public String responsable;
    public int dias;

    public Poblacion (){
        poblacion = null;
        nombrePoblacion = "";
        responsable = "";
        dias = 0;
    }

    public Poblacion (String nombre, String cientifico, int _dias){
        poblacion = null;
        nombrePoblacion = nombre;
        responsable = cientifico;
        dias = _dias;
    }

public class Raton {
    String codigoReferencia;
    Date fechaDeNacimiento;
    int peso;
    String sexo;
    float temperatura;
    String observaciones;
    char X1;
    char X2;
    char Y1;

    public void Raton(String _codigo, Date _fecha, int _peso, String _sexo, float _temp, String _obs, char _x1, char _x2){
        codigoReferencia = _codigo;
        fechaDeNacimiento = _fecha;
        peso = _peso;
        sexo = _sexo;

        if (sexo.equals("Macho")) {
            X1=_x1;
            Y1=_x2;
        } else {
            X1=_x1;
            X2=_x2;
        }

        temperatura=_temp;
        observaciones=_obs;
    }

    public String toString(){
        return codigoReferencia+fechaDeNacimiento+peso+sexo+temperatura+X1+X2+Y1+observaciones;
    }
}

    public static Poblacion abrirPoblacion (File file) throws ClassNotFoundException, IOException {
        File archivo = file;
        FileInputStream fileInputStream = null;
        ObjectInputStream objectInputStream = null;
        Poblacion poblacion=new Poblacion();

        try {
            fileInputStream = new FileInputStream(archivo);
            objectInputStream = new ObjectInputStream(fileInputStream);
            System.out.println(objectInputStream.readObject());
            poblacion = (Poblacion) objectInputStream.readObject();
        } catch(IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                if (objectInputStream!=null) {
                    objectInputStream.close();
                }
            } catch(IOException ex) {
                ex.printStackTrace();
            }
            try {
                if (fileInputStream!=null) {
                    fileInputStream.close();
                }
            } catch(IOException ex) {
                ex.printStackTrace();
            }
            return poblacion;
        }
    }

    public static void crearPoblacion (String _nombre,String _responsable, int _dias) {
        File archivo = new File("C:\\Users\\rober\\OneDrive - Fundación Universitaria San Pablo CEU\\Java\\Práctica 1"+"\\"+_nombre+".dat");
        FileOutputStream fileOutputStream = null;
        ObjectOutputStream objectOutputStream = null;
        Poblacion nuevaPoblacion = new Poblacion(_nombre,_responsable,_dias);

        try {
            fileOutputStream = new FileOutputStream(archivo);
            objectOutputStream = new ObjectOutputStream(fileOutputStream);
            objectOutputStream.writeObject(nuevaPoblacion);
        } catch(IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                if (objectOutputStream != null) {
                    objectOutputStream.close();
                }
            } catch(IOException ex) {
                ex.printStackTrace();
            }

            try {
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch(IOException ex) {
                ex.printStackTrace();
            }
        }
    }
</code>```

答:
You are calling readObject() twice when only one object is in the file.

```<code>System.out.println(objectInputStream.readObject());
poblacion=(Poblacion) objectInputStream.readObject();
</code>```

Obviously, it reaches the end of the file and can no longer read the second one. Simply change this so that you don't try to read it twice:

```<code>poblacion=(Poblacion) objectInputStream.readObject();
System.out.println(poblacion);
</code>```

Body:
I'm encountering the following EOFException:

java.io.EOFException
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2903)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1502)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:422)
at Practica.Animalario.Poblacion.abrirPoblacion(Poblacion.java:37)
at InterfazGrafica.Ventana.actionPerformed(Ventana.java:122)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6533)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
at java.awt.Component.processEvent(Component.java:6298)
at java.awt.Container.processEvent(Container.java:2236)
at java.awt.Component.dispatchEventImpl(Component.java:4889)
at java.awt.Container.dispatchEventImpl(Container.java:2294)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
at java.awt.Container.dispatchEventImpl(Container.java:2280)
at java.awt.Window.dispatchEventImpl(Window.java:2746)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:90)
at java.awt.EventQueue$4.run(EventQueue.java:731)
at java.awt.EventQueue$4.run(EventQueue.java:729)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

While executing this code that I've written. The purpose of this code is to read / write the objects into a file:

public class Poblacion implements Serializable{
    public Raton poblacion [];
    public String nombrePoblacion;
    public String responsable;
    public int dias;

    public Poblacion (){
        poblacion = null;
        nombrePoblacion = "";
        responsable = "";
        dias = 0;
    }

    public Poblacion (String nombre, String cientifico, int _dias){
        poblacion = null;
        nombrePoblacion = nombre;
        responsable = cientifico;
        dias = _dias;
    }

public class Raton {
    String codigoReferencia;
    Date fechaDeNacimiento;
    int peso;
    String sexo;
    float temperatura;
    String observaciones;
    char X1;
    char X2;
    char Y1;

    public void Raton(String _codigo, Date _fecha, int _peso, String _sexo, float _temp, String _obs, char _x1, char _x2){
        codigoReferencia = _codigo;
        fechaDeNacimiento = _fecha;
        peso = _peso;
        sexo = _sexo;

        if (sexo.equals("Macho")) {
            X1=_x1;
            Y1=_x2;
        } else {
            X1=_x1;
            X2=_x2;
        }

        temperatura=_temp;
        observaciones=_obs;
    }

    public String toString(){
        return codigoReferencia+fechaDeNacimiento+peso+sexo+temperatura+X1+X2+Y1+observaciones;
    }
}

    public static Poblacion abrirPoblacion (File file) throws ClassNotFoundException, IOException {
        File archivo = file;
        FileInputStream fileInputStream = null;
        ObjectInputStream objectInputStream = null;
        Poblacion poblacion=new Poblacion();

        try {
            fileInputStream = new FileInputStream(archivo);
            objectInputStream = new ObjectInputStream(fileInputStream);
            System.out.println(objectInputStream.readObject());
            poblacion = (Poblacion) objectInputStream.readObject();
        } catch(IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                if (objectInputStream!=null) {
                    objectInputStream.close();
                }
            } catch(IOException ex) {
                ex.printStackTrace();
            }
            try {
                if (fileInputStream!=null) {
                    fileInputStream.close();
                }
            } catch(IOException ex) {
                ex.printStackTrace();
            }
            return poblacion;
        }
    }

    public static void crearPoblacion (String _nombre,String _responsable, int _dias) {
        File archivo = new File("C:\\Users\\rober\\OneDrive - Fundación Universitaria San Pablo CEU\\Java\\Práctica 1"+"\\"+_nombre+".dat");
        FileOutputStream fileOutputStream = null;
        ObjectOutputStream objectOutputStream = null;
        Poblacion nuevaPoblacion = new Poblacion(_nombre,_responsable,_dias);

        try {
            fileOutputStream = new FileOutputStream(archivo);
            objectOutputStream = new ObjectOutputStream(fileOutputStream);
            objectOutputStream.writeObject(nuevaPoblacion);
        } catch(IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                if (objectOutputStream != null) {
                    objectOutputStream.close();
                }
            } catch(IOException ex) {
                ex.printStackTrace();
            }

            try {
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch(IOException ex) {
                ex.printStackTrace();
            }
        }
    }

Body:
You are calling readObject() twice when only one object is in the file.

System.out.println(objectInputStream.readObject());
poblacion=(Poblacion) objectInputStream.readObject();

Obviously, it reaches the end of the file and can no longer read the second one. Simply change this so that you don't try to read it twice:

poblacion=(Poblacion) objectInputStream.readObject();
System.out.println(poblacion);


问:
Cool Alternatives to HTML Checkbox
ok not just checkbox, but also radio button. The thing is I have a zillion check-boxes & radio-buttons on my form & it looks ugly as hell.

This is not a functionality issue but a purely UI issue. I am looking for some cooler looking ways to implement the same task.

Oh I am using jQuery 1.4.3

UPDATE: I got this jQuery Plugin for the same. It's awesome!! Thanks all... Attached the screenshot of the one I am using now. This one I liked because, it kinda looks like a iPhone style but is not an exact clone.

答:
This is a slightly more advanced task than changing the border of edit-fields. The best method would be to hide the checkbox/radiobutton and replacing it with a dummy element. The problem with this approach is to keep both elements synced. The radiobutton-image needs to know when another radiobutton has been checked, etc. This requires some advanced event-ping-pong. You could do it like this for checkboxes (untested):</p>

```<code>$(':checkbox').each(function () {
   var checkbox = $(this),
      fakebox = $(document.createElement('span')).addClass('custom-checkbox');

   // toggle and trigger update of the real checkbox
   fakebox.click(function () {
      checkbox.attr('checked', !checkbox.attr('checked')).change();
   });

   // changes to the real checkbox causes the fake checkbox to update its status
   checkbox.change(function () {
      if (checkbox.attr('checked')) {
         fakebox.addClass('custom-checkbox-checked');
      } else {
         fakebox.removeClass('custom-checkbox-checked');
      }
   });

   // initialize
   checkbox.change().hide();
   fakebox.insertAfter(checkbox);
});
</code>```

Title: Cool Alternatives to HTML Checkbox

Body:
This is a slightly more advanced task than changing the border of edit-fields. The best method would be to hide the checkbox/radiobutton and replacing it with a dummy element. The problem with this approach is to keep both elements synced. The radiobutton-image needs to know when another radiobutton has been checked, etc. This requires some advanced event-ping-pong. You could do it like this for checkboxes (untested):

$(':checkbox').each(function () {
   var checkbox = $(this),
      fakebox = $(document.createElement('span')).addClass('custom-checkbox');

   // toggle and trigger update of the real checkbox
   fakebox.click(function () {
      checkbox.attr('checked', !checkbox.attr('checked')).change();
   });

   // changes to the real checkbox causes the fake checkbox to update its status
   checkbox.change(function () {
      if (checkbox.attr('checked')) {
         fakebox.addClass('custom-checkbox-checked');
      } else {
         fakebox.removeClass('custom-checkbox-checked');
      }
   });

   // initialize
   checkbox.change().hide();
   fakebox.insertAfter(checkbox);
});


问:
Hostname was NOT found in DNS cache for port 8080 but fine on port 80?
I am testing an API I have made using Springboot from my laptop (192.168.1.217:8080) and I am trying to get a cURL request via SSH from my Raspberry Pi.

Here is the error I am receiving when I try to send the request via port 8080 which it seems to not like:

```<code>pi@raspberrypi:~ $ curl -v 192.168.1.217:8080/api
* Hostname was NOT found in DNS cache
*   Trying 192.168.1.217...
</code>```

However cURL does work for the same IP but with port 80:

```<code>pi@raspberrypi:~ $ curl -v 192.168.1.217
* Rebuilt URL to: 192.168.1.217/
* Hostname was NOT found in DNS cache
*   Trying 192.168.1.217...
* Connected to 192.168.1.217 (192.168.1.217) port 80 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.38.0
> Host: 192.168.1.217
> Accept: */*
>
< HTTP/1.1 302 Found
< Date: Thu, 30 Mar 2017 17:20:43 GMT
* Server Apache/2.4.23 (Win32) OpenSSL/1.0.2h PHP/5.5.38 is not blacklisted
< Server: Apache/2.4.23 (Win32) OpenSSL/1.0.2h PHP/5.5.38
< X-Powered-By: PHP/5.5.38
< Location: http://192.168.1.217/dashboard/
< Content-Length: 0
< Content-Type: text/html
<
* Connection #0 to host 192.168.1.217 left intact
pi@raspberrypi:~ $
</code>```

I've tried looking around but to no avail... anybody have any suggestions as to why I cannot find my own hostname in the DNS cache?

Cheers

答:
No, Hostname was NOT found in DNS cache is not the problem. You can clearly see on the next line, in both examples, that after saying that curl is trying to connect to 192.168.1.217. Your problem is that nothing is answering on port 8080 on that IP address (while an Apache server is answering on port 80 there).

If you're getting a long pause and then a timeout rather than a quick "Connection refused", you almost certainly need to open port 8080 in the local firewall on your server machine.

Body:
I am testing an API I have made using Springboot from my laptop (192.168.1.217:8080) and I am trying to get a cURL request via SSH from my Raspberry Pi.

Here is the error I am receiving when I try to send the request via port 8080 which it seems to not like:

pi@raspberrypi:~ $ curl -v 192.168.1.217:8080/api
* Hostname was NOT found in DNS cache
*   Trying 192.168.1.217...

However cURL does work for the same IP but with port 80:

pi@raspberrypi:~ $ curl -v 192.168.1.217
* Rebuilt URL to: 192.168.1.217/
* Hostname was NOT found in DNS cache
*   Trying 192.168.1.217...
* Connected to 192.168.1.217 (192.168.1.217) port 80 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.38.0
> Host: 192.168.1.217
> Accept: */*
>
< HTTP/1.1 302 Found
< Date: Thu, 30 Mar 2017 17:20:43 GMT
* Server Apache/2.4.23 (Win32) OpenSSL/1.0.2h PHP/5.5.38 is not blacklisted
< Server: Apache/2.4.23 (Win32) OpenSSL/1.0.2h PHP/5.5.38
< X-Powered-By: PHP/5.5.38
< Location: http://192.168.1.217/dashboard/
< Content-Length: 0
< Content-Type: text/html
<
* Connection #0 to host 192.168.1.217 left intact
pi@raspberrypi:~ $

I've tried looking around but to no avail... anybody have any suggestions as to why I cannot find my own hostname in the DNS cache?

Cheers


问:
Hibernate mapping for varchar primary key
I have set primary key as varchar in table. But when I am trying to map this in hibernate I get error as below:

```<code>Could not resolve matching constructor (hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)
</code>```

Hibernate mapping :

```<code>@Id
@Column(name="LOGIN_ID",columnDefinition="VARCHAR")
private String id;
</code>```

How can I map varchar primary key in hibernate?

答:
You can use uuid strategy, it will generate uuid as string id in your database, you don't need to set id, hibernate will take care of it.</p>

```<code>@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid" )
private String id;
</code>```

Body:
I have set primary key as varchar in table. But when I am trying to map this in hibernate I get error as below:

Could not resolve matching constructor (hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)

Hibernate mapping :

@Id
@Column(name="LOGIN_ID",columnDefinition="VARCHAR")
private String id;

How can I map varchar primary key in hibernate?

Body:
You can use uuid strategy, it will generate uuid as string id in your database, you don't need to set id, hibernate will take care of it.

@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid" )
private String id;


问:
NativeBase: override style on single element
I have a Text component that I need to modify for one screen only (not restyling the entire theme). I tried to follow the NativeBase 2.0 documentation but found it very confusing. Is there a simple way to just change the style of that one element without having to copy the entire theme into project?

```<code>import React, { Component } from 'react';
import { StyleSheet } from 'react-native';
import { ListItem, Grid, Col, Text } from 'native-base';

export default class JobListDetail extends Component {
  render() {
    return (
      <ListItem>
        <Grid>
          <Col>
            <Text style={styles.redText}>Some Text</Text>
            <Text>Another text</Text>
          </Col>
        </Grid>
      </ListItem>
    );
  }
}

const styles = StyleSheet.create({
  redText: {
    color: 'red'
  },
});
</code>```

答:
NativeBase Text overrides the style's StyleSheetPropType to become PropTypes.object.

Remove the StyleSheet.create to apply the new style:

```<code>const styles = {
  redText: {
    color: 'red'
  },
};
</code>```

Body:
I have a Text component that I need to modify for one screen only (not restyling the entire theme). I tried to follow the NativeBase 2.0 documentation but found it very confusing. Is there a simple way to just change the style of that one element without having to copy the entire theme into project?

import React, { Component } from 'react';
import { StyleSheet } from 'react-native';
import { ListItem, Grid, Col, Text } from 'native-base';

export default class JobListDetail extends Component {
  render() {
    return (
      <ListItem>
        <Grid>
          <Col>
            <Text style={styles.redText}>Some Text</Text>
            <Text>Another text</Text>
          </Col>
        </Grid>
      </ListItem>
    );
  }
}

const styles = StyleSheet.create({
  redText: {
    color: 'red'
  },
});

Body:
NativeBase Text overrides the style's StyleSheetPropType to become PropTypes.object.

Remove the StyleSheet.create to apply the new style:

const styles = {
  redText: {
    color: 'red'
  },
};


问:
Error with nucleusexception and jdofatalexception when starting hive
I am installing hive for the first time on my system with embedded derby metastore but it is not working. It is showing the below mentioned error.

```<code>Caused by: javax.jdo.JDOFatalInternalException: The java type java.lang.Long (jdbc-type="",sql-type="") cant be mapped for this metastore.No mapping is available.
NestedThrowables
org.datanucleus.exceptions.NucleusException: The java type java.lang.Long (jdbc-type="",sql-type="") cant be mapped for this metastore.No mapping is available
</code>```

Please help

答:
Java 9 is not yet supported by Hive. Install either Java 7 or 8 and set the JDK directory as JAVA_HOME in the environment where Hive is installed.

PS: Prefer MySQL for metastore rather than derby.

An embedded metastore database is mainly used for unit tests. Only one process can connect to the metastore database at a time, so it is not really a practical solution but works well for unit tests.

Body:
I am installing hive for the first time on my system with embedded derby metastore but it is not working. It is showing the below mentioned error.

Caused by: javax.jdo.JDOFatalInternalException: The java type java.lang.Long (jdbc-type="",sql-type="") cant be mapped for this metastore.No mapping is available.
NestedThrowables
org.datanucleus.exceptions.NucleusException: The java type java.lang.Long (jdbc-type="",sql-type="") cant be mapped for this metastore.No mapping is available

Please help


问:
In React, is it a good practise to return null if props is empty
Given my code:

```<code>class Example extends Components {
  constructor(props) {
     super(props)
  }

  componentDidMount() {
     //fetch data
  }

  render() {
     const {obj} = this.props;
     if(R.isEmpty(obj)) {
        return null;
     }

     return (<div>{obj.name}</div>)
  }
}
</code>```

the obj is retrieved from server. so for the initial render, obj is empty. If I don't return null, obj.name would report error

so is it a good practise to return null before I get response from server? thanks

答:
so is it a good practice to return null before I get a response from
  the server?

It is ok to do it but also depends on a situation.
For example in some case, you can avoid rendering the component at all like this:

```<code>class ParentComp extends Component {
  render() {
    return (
      <div>
        {!R.isEmpty(obj) && <Example obj={obj}/>}
      </div>
    );
  }
}
</code>```

Body:
Given my code:

class Example extends Components {
  constructor(props) {
     super(props)
  }

  componentDidMount() {
     //fetch data
  }

  render() {
     const {obj} = this.props;
     if(R.isEmpty(obj)) {
        return null;
     }

     return (
{obj.name}
)
  }
}

the obj is retrieved from server. so for the initial render, obj is empty. If I don't return null, obj.name would report error

so is it a good practise to return null before I get response from server? thanks

Body:
so is it a good practice to return null before I get a response from
  the server?

It is ok to do it but also depends on a situation.
For example in some case, you can avoid rendering the component at all like this:

class ParentComp extends Component {
  render() {
    return (
      <div>
        {!R.isEmpty(obj) && <Example obj={obj}/>}
      </div>
    );
  }
}


答:
There are two situations:

The local variable is of a primitive type like int or double.

The local variable is of a reference type like ArrayList.

In the first situation, you can't synchronize, as you can only synchronize on Objects (which are pointed to by reference-type variables).

In the second situation, it all depends on what the local variable points to. If it points to an object that other threads (can) also point to, then you need to make sure that your code is properly synchronized.

Examples: you assigned the local variable from a static or instance field, or you got the object from a shared collection.

If, however, the object was created in your thread and only assigned to that local variable, and you never give out a reference to it from your thread to another thread, and the objects implementation itself also doesn't give out references, then you don't need to worry about synchronization.

Title: Is it reasonable to synchronize on a local variable?

Body:
From the Java memory model, we know that every thread has its own thread stack, and that local variables are placed in each thread's own thread stack.

And that other threads can't access these local variables.

So in which case should we synchronize on local variables?


问:
CastError mongoose
I am using mongodb in an express/nodejs project. I have a nested schema such that Themes have categories

Given this schema:

```<code>var ControlCategorySchema = new Schema({
    name: {
        type: String,
        Required: 'Please enter the category name'
    }
});
ControlCategorySchema.plugin(autoIncrement.plugin, 'ControlCategorySchemaCounter');

var ThemeSchema = new Schema({
    name : String,
    category : {type: Schema.Types.ObjectId, ref: 'ControlCategorySchema'}
});
ThemeSchema.plugin(autoIncrement.plugin, 'ThemeCounter');
</code>```

And the following controller code:

```<code>exports.create_a_theme = function(req, res) {
    console.log(req.body.category);
    if (req.body.category != undefined) {
        addTheme(req,res,req.body.category);
    }

};

function addTheme(req,res,category_id) {
    console.log("category id " + category_id);
    ControlCategory.findById(category_id, function (err, category_found) {
        if (err)
            res.send(err)

        req.body.category = category_found;
        console.log("body is " + req.body.category);
        var new_theme = new Theme();
        new_theme.name = req.body.name;
        new_theme.category = req.body.category;
        new_theme.save(function (err, theme) {
            if (err)
                res.send(err);
            console.log(theme);
            res.json(theme);
        });
    });
}
</code>```

Can anyone help solve why posting this json

```<code>{
    "name": "Application Security",
    "category": 0
}
</code>```

Results in the error below:

```<code>{
  "errors": {
    "category": {
      "message": "Cast to ObjectID failed for value \"{ _id: 0, name: 'Application Security', __v: 0 }\" at path \"category\"",
      "name": "CastError",
      "stringValue": "\"{ _id: 0, name: 'Application Security', __v: 0 }\"",
      "kind": "ObjectID",
      "value": {
        "_id": 0,
        "name": "Application Security",
        "__v": 0
      },
      "path": "category",
      "reason": {
        "message": "Cast to ObjectId failed for value \"{ _id: 0, name: 'Application Security', __v: 0 }\" at path \"category\"",
        "name": "CastError",
        "stringValue": "\"{ _id: 0, name: 'Application Security', __v: 0 }\"",
        "kind": "ObjectId",
        "value": {
          "_id": 0,
          "name": "Application Security",
          "__v": 0
        },
        "path": "category"
      }
    }
  },
  "message": "Theme validation failed",
  "name": "ValidationError"
}
</code>```

One thing that is very strange is that I do virtually the same thing on another schema and controller code and it works!

```<code>var AssessmentSchema = new Schema({
    name: {
        type: String,
        Required: 'Kindly enter the name of the assessment'
    },
    Created_date: {
        type: Date,
        default: Date.now
    },
    status: { type: Schema.ObjectId, ref: 'AssessmentStatus' },
});

var AssessmentStatusSchema = new Schema({
    name: {
        type: String,
        Required: 'Please enter the name of the assessment status'
    }

});

exports.create_an_assessment = function(req, res) {
    console.log(req.body.status);
    if (req.body.status == undefined) {
        AssessmentStatus.findOne({"name": "Due For Assessment"}, function (err, assessment_status) {
            if (err)
                res.send(err)
            addAssessment(req,res,assessment_status._id);
        });
    }
    else {

        addAssessment(req,res,req.body.status);
    }

};

function addAssessment(req,res,status_id) {
    console.log("status id " + status_id);
    AssessmentStatus.findById(status_id, function (err, assessment_status) {
        if (err)
            res.send(err)
        req.body.status = assessment_status;
        console.log("body is " + req.body.status);
        var new_assessment = new Assessment();
        new_assessment.name = req.body.name;
        new_assessment.status = assessment_status;
        new_assessment.save(function (err, assessment) {
            if (err)
                res.send(err);
            console.log(assessment);
            res.json(assessment);
        });
    });
}
</code>```

And there I post same kind of data

```<code>{
    "name": "Assessment 10",
    "status": 6
}
</code>```

and get the desired result

```<code>{
  "__v": 0,
  "_id": 28,
  "status": {
    "_id": 6,
    "name": "Due For Assessment",
    "__v": 0
  },
  "name": "Assessment 10",
  "Created_date": "2017-03-31T06:48:21.999Z"
}
</code>```

I cant tell what is different?

答:
Looks like https://stackoverflow.com/users/5127888/p0k8 gave a working answer, thank you!

Instead of category : {type: Schema.Types.ObjectId, ref: 'ControlCategorySchema'} do category : {type: Number, ref: 'ControlCategorySchema'}

That worked. Although still puzzles me why the Assessment one worked out

Title: CastError mongoose

Body:
I am using mongodb in an express/nodejs project. I have a nested schema such that Themes have categories

Given this schema:

var ControlCategorySchema = new Schema({
    name: {
        type: String,
        Required: 'Please enter the category name'
    }
});
ControlCategorySchema.plugin(autoIncrement.plugin, 'ControlCategorySchemaCounter');

var ThemeSchema = new Schema({
    name : String,
    category : {type: Schema.Types.ObjectId, ref: 'ControlCategorySchema'}
});
ThemeSchema.plugin(autoIncrement.plugin, 'ThemeCounter');

And the following controller code:

exports.create_a_theme = function(req, res) {
    console.log(req.body.category);
    if (req.body.category != undefined) {
        addTheme(req,res,req.body.category);
    }

};

function addTheme(req,res,category_id) {
    console.log("category id " + category_id);
    ControlCategory.findById(category_id, function (err, category_found) {
        if (err)
            res.send(err)

        req.body.category = category_found;
        console.log("body is " + req.body.category);
        var new_theme = new Theme();
        new_theme.name = req.body.name;
        new_theme.category = req.body.category;
        new_theme.save(function (err, theme) {
            if (err)
                res.send(err);
            console.log(theme);
            res.json(theme);
        });
    });
}

Can anyone help solve why posting this json

{
    "name": "Application Security",
    "category": 0
}

Results in the error below:

{
  "errors": {
    "category": {
      "message": "Cast to ObjectID failed for value \"{ _id: 0, name: 'Application Security', __v: 0 }\" at path \"category\"",
      "name": "CastError",
      "stringValue": "\"{ _id: 0, name: 'Application Security', __v: 0 }\"",
      "kind": "ObjectID",
      "value": {
        "_id": 0,
        "name": "Application Security",
        "__v": 0
      },
      "path": "category",
      "reason": {
        "message": "Cast to ObjectId failed for value \"{ _id: 0, name: 'Application Security', __v: 0 }\" at path \"category\"",
        "name": "CastError",
        "stringValue": "\"{ _id: 0, name: 'Application Security', __v: 0 }\"",
        "kind": "ObjectId",
        "value": {
          "_id": 0,
          "name": "Application Security",
          "__v": 0
        },
        "path": "category"
      }
    }
  },
  "message": "Theme validation failed",
  "name": "ValidationError"
}

One thing that is very strange is that I do virtually the same thing on another schema and controller code and it works!

var AssessmentSchema = new Schema({
    name: {
        type: String,
        Required: 'Kindly enter the name of the assessment'
    },
    Created_date: {
        type: Date,
        default: Date.now
    },
    status: { type: Schema.ObjectId, ref: 'AssessmentStatus' },
});

var AssessmentStatusSchema = new Schema({
    name: {
        type: String,
        Required: 'Please enter the name of the assessment status'
    }

});

exports.create_an_assessment = function(req, res) {
    console.log(req.body.status);
    if (req.body.status == undefined) {
        AssessmentStatus.findOne({"name": "Due For Assessment"}, function (err, assessment_status) {
            if (err)
                res.send(err)
            addAssessment(req,res,assessment_status._id);
        });
    }
    else {

        addAssessment(req,res,req.body.status);
    }

};

function addAssessment(req,res,status_id) {
    console.log("status id " + status_id);
    AssessmentStatus.findById(status_id, function (err, assessment_status) {
        if (err)
            res.send(err)
        req.body.status = assessment_status;
        console.log("body is " + req.body.status);
        var new_assessment = new Assessment();
        new_assessment.name = req.body.name;
        new_assessment.status = assessment_status;
        new_assessment.save(function (err, assessment) {
            if (err)
                res.send(err);
            console.log(assessment);
            res.json(assessment);
        });
    });
}

And there I post same kind of data

{
    "name": "Assessment 10",
    "status": 6
}

and get the desired result

{
  "__v": 0,
  "_id": 28,
  "status": {
    "_id": 6,
    "name": "Due For Assessment",
    "__v": 0
  },
  "name": "Assessment 10",
  "Created_date": "2017-03-31T06:48:21.999Z"
}

I cant tell what is different?


问:
Spark Installation Problems
I am following instructions from here:

https://www.datacamp.com/community/tutorials/apache-spark-python#gs.WEktovg

I downloaded and prebuilt version of Spark , untarred it and mv it to /usr/local/spark.

According to this, this is all I should have to do.

Unfortunately, I can run the interactive shell as it cant find the file.

When i run :

```<code>./bin/pyspark
</code>```

I get

```<code>-bash: ./bin/pyspark: No such file or directory.
</code>```

I also notice that installing it this way does not add it to the bin directory.

Is this tutorial wrong or am I missing a trick?

答:
You need to change your working directory to /usr/local/spark. Then this command will work.

And also, when you untar it, it usually will not add it to bin folder. You need to add it manually by adding the path to environment variables.

Title: Spark Installation Problems

Body:
I am following instructions from here:

https://www.datacamp.com/community/tutorials/apache-spark-python#gs.WEktovg

I downloaded and prebuilt version of Spark , untarred it and mv it to /usr/local/spark.

According to this, this is all I should have to do.

Unfortunately, I can run the interactive shell as it cant find the file.

When i run :

./bin/pyspark

I get

-bash: ./bin/pyspark: No such file or directory.

I also notice that installing it this way does not add it to the bin directory.

Is this tutorial wrong or am I missing a trick?


问:
JavaScript JSON response - formatting dates and times
When I trigger my JavaScript code to open up a modal, an AJAX call is sent to retrieve data in JSON format. I then use the JSON response to populate my modal.

The link that triggers the JavaScript is this:

```<code><?= $this->Html->link(__('View'), ['action' => 'popup', $session->id], ['class' => 'view', 'data-id' => $session->id]) ?>
</code>```

This is an action from a table on a CakePHP 3 View. $session->id is decided based on which row of data the link is clicked. Popup is an empty CakePHP 3 function that just facilitates the JavaScript working and the modal opening up.

The JavaScript which triggers the modal is as follows:

```<code><script type="text/javascript">
    $(function () {
        $('.view').click(function (ev) {
            ev.preventDefault();
            var sessionId = $(this).attr('data-id');
            $('#viewModal').modal('show');
            $.ajax({
                url:"localhost/project/sessions/details/"+sessionId+".json",
                type:'POST',
                success:function(res) {
                    if(res) {
                        document.getElementById("prdatestart").innerHTML = res.date_start;
                        document.getElementById("prstarttime").innerHTML = res.starttime;
                    }
                }
            });
        });
    });
</script>
</code>```

The details function from my CakePHP 3 SessionsController is this, which retrieves the relevant data for the $session->id that was obtained earlier:

```<code>public function details($id = null)
    {
        $details = $this->Sessions->get($id);
        $this->set(array(
            'output' => $details,
            '_serialize' => 'output',
            '_jsonp' => true
        ));
    }
</code>```

This is my modal in full that then opens up:

```<code><!-- Modal -->
<div class="modal fade" id="viewModal" tabindex="-1" role="dialog" aria-labelledby="viewModalLabel"
     aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
                <h3 class="modal-title" id="viewModalLabel">Session Details</h3>
                <br>
                <table class="vertical table col-sm-2">
                    <tr>
                        <th>Starting Date:</th>
                        <td id="prdatestart"></td>
                    </tr>
                    <tr">
                        <th>Starting Time:</th>
                        <td id="prstarttime"></td>
                    </tr>
                </table>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close
                </button>
            </div>
        </div>
    </div>
</div>
</code>```

However, my dates and times are in this format:

Date: 2017-05-12T00:00:00+00:00

Time: 2017-03-31T00:14:00+11:00

For the date response, I only need the date, and formatted in D/M/Y format. For the time response, I only need the time, formatted in 12 hour hh:mm AM/PM format. (I don't need the timezone stuff at the end as that was taken into account when the data was first submitted).

答:
simply use with normal javascript new Date() .post like simple js function cal(yourdatevarible ,whichtype) type=date|time

var date = '2017-05-12T00:00:00+00:00';
var time = '2017-03-31T00:14:00+11:00';

console.log(cal(date, 'date'))
console.log(cal(time, 'time'))

function cal(date, type) {

  var m = ['Jan', 'Feb', 'Mar', 'Aprl', 'May', 'Jun', 'July', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
  //var w =['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
  var x = new Date(date)
  var h = x.getHours() > 12 ? x.getHours() - 12 : x.getHours();
  var format = x.getHours() > 12 ? 'PM' : 'AM';
  if (type == 'date') {
    return x.getDate() + ' ' + m[x.getMonth()] + ' ' + x.getFullYear();
  } else {
    var min = x.getMinutes().toString().length > 1 ? x.getMinutes() : '0' + x.getMinutes();
     h =h.toString().length > 1 ? h : '0' + h;
    return h + ':' + min + ' ' + format;
  }
}```

Body:
When I trigger my JavaScript code to open up a modal, an AJAX call is sent to retrieve data in JSON format. I then use the JSON response to populate my modal.

The link that triggers the JavaScript is this:

<?= $this->Html->link(__('View'), ['action' => 'popup', $session->id], ['class' => 'view', 'data-id' => $session->id]) ?>

This is an action from a table on a CakePHP 3 View. $session->id is decided based on which row of data the link is clicked. Popup is an empty CakePHP 3 function that just facilitates the JavaScript working and the modal opening up.

The JavaScript which triggers the modal is as follows:

The details function from my CakePHP 3 SessionsController is this, which retrieves the relevant data for the $session->id that was obtained earlier:

public function details($id = null)
    {
        $details = $this->Sessions->get($id);
        $this->set(array(
            'output' => $details,
            '_serialize' => 'output',
            '_jsonp' => true
        ));
    }

This is my modal in full that then opens up:

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    ×
                </button>

Session Details

                        Starting Date:

                        Starting Time:

                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close
                </button>

However, my dates and times are in this format:

Date: 2017-05-12T00:00:00+00:00

Time: 2017-03-31T00:14:00+11:00

For the date response, I only need the date, and formatted in D/M/Y format. For the time response, I only need the time, formatted in 12 hour hh:mm AM/PM format. (I don't need the timezone stuff at the end as that was taken into account when the data was first submitted).


问:
ASP.NET Development with a Design Team
I am looking for some good information on the best way for a design and development team to work together. I am a WinForms developer and I have very little experience in .NET web development and I have been asked to take over responsibility for the website development.

Currently they are using Visual Sourcesafe, the websites are not in a solution and the whole thing is just a complete mess of thousands of random webpages created by the designers and cobbled together code put together by the developers. The different pages are released whenever they are ready - which means dependant code may not get released at the same time. At times designers are using code the developers have created but they use it in a way which will either slow down the site or cause it to crash completely - for example calling Functions.GetAddress().PhoneNumber and then Functions.GetAddress().Address1 where the GetAddress method is calling a webservice each time, if the GetAddress call fails and returns null they are not checking for null references etc and there is no error handling.

Basically the entire thing is a complete unmanaged mess which scares me to death considering I am soon going to be completely responsible for it. This is also across 3 or 4 large business critical websites. I am trying to figure out the best way going forward so that the designers can continue to create pages and design assets they need while also accessing certain exposed properties as required.

Currently on the Windows development side of things we are using Team System 2010 but this won't be appropriate for the designers as they need source control integrated into the shell where they can edit images and flash which SourceSafe currently lets them do (badly).

I think the first step is to split up the code development / data access side of things into a completely seperate project which can be referenced as a dll from different web projects which I will get created for each site under a single solution. I then need to sort out a way that we are publishing the complete site everytime an update is made - so obviously it is important that only completed / tested work is checked in - I think this is going to be incredibly tough to sort out with the design team as they are unused to source control and just upload pages one by one as they complete work / fix bugs on them. Basically I need help/ideas/pointers for the right way to go about this!

答:
Wiredness - your 1st task is to create your 'insurance' document which is delivered to management outlining your concerns, findings and your plan for your plan of attack. that plan of attack would be outlined in a risk document well ahead of implementing any strategies.

honestly, it's worth it if you are going to become the project owner.

Title: ASP.NET Development with a Design Team


问:
JS turn string into variable
I have a json feed that returns an array of google map points.  The issue is that it returns everything as a string.   I send icon to a google map script. In the example below you will see SQUARE_PIN.  This is a variable not a string and it adds the quotes around it preventing it from rendering the variable.  Is there a easy way of fixing this.</p>

```<code>{
    "title":false,
    "lat":"44.7930232",
    "lng":"-89.7031784",
    "icon":{
        "path":"SQUARE_PIN",
        "fillColor":"#FF0000",
        "fillOpacity":1,
        "strokeColor":"",
        "strokeWeight":0,
        "micon":"<\/span>"
    }
}
</code>```

答:
Let's suppose you have your JSON stored in an object called obj. Also, let's suppose that the variable you intend to use is inside another object, called obj2 (could be window if the variable is global). In this case you can do this:

```<code>obj.icon.path = obj2[obj.icon.path];
</code>```

and then use obj.

Title: JS turn string into variable

Body:
I have a json feed that returns an array of google map points.  The issue is that it returns everything as a string.   I send icon to a google map script. In the example below you will see SQUARE_PIN.  This is a variable not a string and it adds the quotes around it preventing it from rendering the variable.  Is there a easy way of fixing this.

{
    "title":false,
    "lat":"44.7930232",
    "lng":"-89.7031784",
    "icon":{
        "path":"SQUARE_PIN",
        "fillColor":"#FF0000",
        "fillOpacity":1,
        "strokeColor":"",
        "strokeWeight":0,
        "micon":"<\/span>"
    }
}

Body:
Let's suppose you have your JSON stored in an object called obj. Also, let's suppose that the variable you intend to use is inside another object, called obj2 (could be window if the variable is global). In this case you can do this:

obj.icon.path = obj2[obj.icon.path];

and then use obj.


问:
TensorFlow wasn't compiled to use SSE (etc.) instructions, but these are available
I am running TensorFlow for the first time using some example code. I got the following warnings when running my code. Does anybody know why this happened, and how to fix it?</p>
```<code>2017-03-31 02:12:59.346109: W c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE instructions, but these are available on your machine and could speed up CPU computations.
2017-03-31 02:12:59.346968: W c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE2 instructions, but these are available on your machine and could speed up CPU computations.
2017-03-31 02:12:59.346975: W c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow libbrary wasn't compiled to use SSE3 instructions, but these are available on your machine and could speed up CPU computations.
2017-03-31 02:12:59.346979: W c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.1 instructions, but these are available on your machine and could speed up CPU computations.
2017-03-31 02:12:59.346983: W c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available on your machine and could speed up CPU computations.
2017-03-31 02:12:59.346987: W c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations.
2017-03-31 02:12:59.346991: W c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX2 instructions, but these are available on your machine and could speed up CPU computations.
2017-03-31 02:12:59.346995: W c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use FMA instructions, but these are available on your machine and could speed up CPU computations.
</code>```

答:
Those are warnings (as indicated by the W after the colon. Errors have an E there).

The warnings refer to the fact that your CPU supports SSE Instructions, which allow some fast in-hardware-parallel operations. Enabling these operations is a compile-time operation (i.e. to use SSE you need to build the library from the source enabling the specific SSE version you're targeting), in which case you might take a look at this question.

Note, however, that SSE support influences only the computation speed. Tensorflow will work with or without SSE, but it might take longer for your code to run.
Note, also, that this influences only the CPU. If you're using the GPU build of Tensorflow, all the operations run on the GPU will not benefit of SSE instructions.

Body:
I am running TensorFlow for the first time using some example code. I got the following warnings when running my code. Does anybody know why this happened, and how to fix it?

2017-03-31 02:12:59.346109: W c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE instructions, but these are available on your machine and could speed up CPU computations.
2017-03-31 02:12:59.346968: W c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE2 instructions, but these are available on your machine and could speed up CPU computations.
2017-03-31 02:12:59.346975: W c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow libbrary wasn't compiled to use SSE3 instructions, but these are available on your machine and could speed up CPU computations.
2017-03-31 02:12:59.346979: W c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.1 instructions, but these are available on your machine and could speed up CPU computations.
2017-03-31 02:12:59.346983: W c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available on your machine and could speed up CPU computations.
2017-03-31 02:12:59.346987: W c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations.
2017-03-31 02:12:59.346991: W c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX2 instructions, but these are available on your machine and could speed up CPU computations.
2017-03-31 02:12:59.346995: W c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use FMA instructions, but these are available on your machine and could speed up CPU computations.


问:
Pimps are not working when used with generics
Consider following code (script) in which the SeqPimps can't be changed:

```<code>import scala.reflect.ClassTag

implicit class SeqPimps[T: ClassTag](s: Seq[T]) {
  def indexOfOpt(e: T): Option[Int] = s.indexOf(e) match {
    case -1 => None
    case idx => Some(idx)
  }
}

class A[T] {
  val fn = (y: T) => List[T]().indexOfOpt(y)
}

object Main extends App {
  val fn = (y: Int) => List[Int]().indexOfOpt(y)

  println(fn(0))
  println((new A[String]).fn(""))
}
Main.main(args)
</code>```

It crashes with:

```<code>xxx/test.scala:11: error: value indexOfOpt is not a member of List[T]
  val fn = (y: T) => List[T]().indexOfOpt(y)
                               ^
one error found
</code>```

My questions:

Why is it working when type is explicitly specified (in Main, after commenting out A and the one println it works fine) and complaining about non-existing member when generic type is used? The call looks same.

How to fix the snippet without modifying SeqPimps (e.g. removing of ClassTag - it is required by other methods in real project)?

答:
Oh, it turns out I was missing a ClassTag in class definition:

```<code>class A[T: ClassTag] {
</code>```

Body:
Consider following code (script) in which the SeqPimps can't be changed:

import scala.reflect.ClassTag

implicit class SeqPimps[T: ClassTag](s: Seq[T]) {
  def indexOfOpt(e: T): Option[Int] = s.indexOf(e) match {
    case -1 => None
    case idx => Some(idx)
  }
}

class A[T] {
  val fn = (y: T) => List[T]().indexOfOpt(y)
}

object Main extends App {
  val fn = (y: Int) => List[Int]().indexOfOpt(y)

  println(fn(0))
  println((new A[String]).fn(""))
}
Main.main(args)

It crashes with:

xxx/test.scala:11: error: value indexOfOpt is not a member of List[T]
  val fn = (y: T) => List[T]().indexOfOpt(y)
                               ^
one error found

My questions:

Why is it working when type is explicitly specified (in Main, after commenting out A and the one println it works fine) and complaining about non-existing member when generic type is used? The call looks same.

How to fix the snippet without modifying SeqPimps (e.g. removing of ClassTag - it is required by other methods in real project)?

Body:
Oh, it turns out I was missing a ClassTag in class definition:

class A[T: ClassTag] {


问:
Auto Kill Shell Command & get output
Hi I am running an shell command & auto killing it after 10 seconds using an shell script having content :

( cmdpid=$BASHPID; (sleep 10; kill $cmdpid) & exec redis-cli --latency )

This is working & killing. How do I change the shell script to actually get the o/p of command after the command is killed.

答:
If I understand you correctly, you can simply capture the output of your program with redirecting stdout and stderr to a file and later kill the programm after the sleep, like this:

```<code>ping stackoverflow.com >/tmp/ping.log 2>&1 & sleep 10 && kill $!
</code>```

$! is the PID of the most recent background command.

This way you don't need to kill the whole bash process like I understand you're doing in your script.

Title: Auto Kill Shell Command & get output

Body:
If I understand you correctly, you can simply capture the output of your program with redirecting stdout and stderr to a file and later kill the programm after the sleep, like this:

ping stackoverflow.com >/tmp/ping.log 2>&1 & sleep 10 && kill $!

$! is the PID of the most recent background command.

This way you don't need to kill the whole bash process like I understand you're doing in your script.


问:
Spring context files organization and best practices
We have started using Spring framework in my project. After becoming acquainted with the basic features (IoC) we have started using spring aop and spring security as well.

The problem is that we now have more than 8 different context files and I feel we didn't give enough thought for the organization of those files and their roles. New files were introduced as the project evolved.
We have different context files for: metadata, aop, authorization, services, web resources (it's a RESTful application). So when a developer wants to add a new bean it's not always clear in which file he should add it. We need methodology.

The question:

Is there a best practice for spring files organization?

Should the context files encapsulate layers (DAL , Business Logic, Web) or use cases ? or Flows?

答:
If you're still reasonably early in the project I'd advice you strongly to look at annotation-driven configuration. After converting to annotations we only have 1 xml file with definitions and it's really quite small, and this is a large project. Annotation driven configuration puts focus on your implementation instead of the xml. It also more or less removes the fairly redundant abstraction layer which is the spring "bean name". It turns out the bean name exists mostly because of xml (The bean name still exists in annotation config but is irrelevant in most cases). After doing this switch on a large project everyone's 100% in agreement that it's a lot better and we also have fairly decent evidence that it's a more productive environment.

I'd really recommend anyone who's using spring to switch to annotations. It's possible to mix them as well. If you need transitional advice I suppose it's easy to ask on SO ;)

OwnerDisplayName: LiorH

OwnerDisplayName: krosenvold

LastEditorDisplayName: krosenvold


问:
Is it reasonable to synchronize on a local variable?
From the Java memory model, we know that every thread has its own thread stack, and that local variables are placed in each thread's own thread stack.

And that other threads can't access these local variables.

So in which case should we synchronize on local variables?

答:
You are talking about the below case:

```<code>public class MyClass {
    public void myMethod() {
        //Assume Customer is a Class
        Customer customer = getMyCustomer();
        synchronized(customer) {
            //only one thread at a time can access customer object
              which ever holds the lock
        }
    }
}
</code>```

In the above code, customer is a local reference variable, but you are still using a synchronized block to restrict access  to the object customer is pointing to (by a single thread at a time).

In Java memory model, objects live in heap (even though references are local to a Thread which live in a stack) and synchronization is all about restricting access to an object on the heap by exactly one thread at a time.

In short, when you say local variable (non-primitive), only reference is local, but not the actual object itself i.e., it is actually referring to an object on the heap which can be accessed by many other threads. Because of this, you need synchronization on the object so that single thread can only access that object at a time.

Body:
You are talking about the below case:

public class MyClass {
    public void myMethod() {
        //Assume Customer is a Class
        Customer customer = getMyCustomer();
        synchronized(customer) {
            //only one thread at a time can access customer object
              which ever holds the lock
        }
    }
}

In the above code, customer is a local reference variable, but you are still using a synchronized block to restrict access  to the object customer is pointing to (by a single thread at a time).

In Java memory model, objects live in heap (even though references are local to a Thread which live in a stack) and synchronization is all about restricting access to an object on the heap by exactly one thread at a time.

In short, when you say local variable (non-primitive), only reference is local, but not the actual object itself i.e., it is actually referring to an object on the heap which can be accessed by many other threads. Because of this, you need synchronization on the object so that single thread can only access that object at a time.


问:
NUnit Unit tests not showing in Test Explorer with Test Adapter installed
I've installed NUnit Test Adapter for VS2012 + 2013.  When I first installed the Adapter tests were showing up, but they stopped showing up for some reason today.  After building, rebuilding, cleaning, restarting, nothing shows up in Test Explorer.  Why would this be happening?  I'm using VS2013 Ultimate.</p>

答:
I had a working setup (for NUnit2 and NUnit3 depending on the solution, and multiple versions of Visual Studio between 2012 and 2017), and it suddenly stopped working one day: no tests detected in any solution or version of VS.

In my case, it helped to delete %localappdata%\Temp\VisualStudioTestExplorerExtensions. After a restart of VS, everything worked as before.


问:
Unity alternative for Autofac TypedParameter
Short question: how can I achieve the same functionality of TypedParameter as described in the Autofac documentation section Passing Parameters to Resolve in Unity?

Some background: we need to resolve inherited classes that rename the constructor parameter of the base class. This parameter can't be resolved and must be passed in. We know that the inherited classes will only have types that can be resolved and the one base class constructor parameter.

kind regards,
Jef

答:
You can create your own TypedParameter like this:

```<code>internal class Program
{
    static void Main( string[] args )
    {
        var container = new UnityContainer();
        container.RegisterType<IInterface, Implementation>();

                    // this will be created with this MyLogger instance
        var instance = container.Resolve<IInterface>( new TypedParameter( typeof(ILogger), new MyLogger() ) );
    }
}

internal class TypedParameter : ResolverOverride
{
    private readonly Type _type;
    private readonly InjectionParameterValue _value;

    public TypedParameter( Type type, object value )
    {
        _type = type;
        _value = InjectionParameterValue.ToParameter( value );
    }

    public override IDependencyResolverPolicy GetResolver( IBuilderContext context, Type dependencyType )
    {
        ConstructorArgumentResolveOperation currentOperation = context.CurrentOperation as ConstructorArgumentResolveOperation;
        if ( currentOperation != null )
        {
            var parameter = currentOperation.TypeBeingConstructed.GetConstructors().Single().GetParameters().Single( x => x.Name == currentOperation.ParameterName );
            if (parameter.ParameterType == _type)
                return _value.GetResolverPolicy( dependencyType );
        }

        return null;
    }
}

// note that this is not registered with unity, is has to come from TypedParameter
internal class MyLogger : ILogger
{
}

internal interface ILogger
{
}

internal interface IInterface
{
}

internal class Implementation : IInterface
{
    public Implementation( ILogger logger )
    {
    }
}
</code>```

Not production ready, but it works if the type constructed only has one constructor. But you have to be careful because these overrides act on all dependencies created in one Resolve call.

Body:
You can create your own TypedParameter like this:

internal class Program
{
    static void Main( string[] args )
    {
        var container = new UnityContainer();
        container.RegisterType<IInterface, Implementation>();

                    // this will be created with this MyLogger instance
        var instance = container.Resolve<IInterface>( new TypedParameter( typeof(ILogger), new MyLogger() ) );
    }
}

internal class TypedParameter : ResolverOverride
{
    private readonly Type _type;
    private readonly InjectionParameterValue _value;

    public TypedParameter( Type type, object value )
    {
        _type = type;
        _value = InjectionParameterValue.ToParameter( value );
    }

    public override IDependencyResolverPolicy GetResolver( IBuilderContext context, Type dependencyType )
    {
        ConstructorArgumentResolveOperation currentOperation = context.CurrentOperation as ConstructorArgumentResolveOperation;
        if ( currentOperation != null )
        {
            var parameter = currentOperation.TypeBeingConstructed.GetConstructors().Single().GetParameters().Single( x => x.Name == currentOperation.ParameterName );
            if (parameter.ParameterType == _type)
                return _value.GetResolverPolicy( dependencyType );
        }

        return null;
    }
}

// note that this is not registered with unity, is has to come from TypedParameter
internal class MyLogger : ILogger
{
}

internal interface ILogger
{
}

internal interface IInterface
{
}

internal class Implementation : IInterface
{
    public Implementation( ILogger logger )
    {
    }
}

Not production ready, but it works if the type constructed only has one constructor. But you have to be careful because these overrides act on all dependencies created in one Resolve call.


问:
Aligning text and edit uicontrols
I am creating GUI and I want to have inputs and results there.

I have text fields as labels and edit or popup for inputs. When I have

```<code>uicontrol('style','text','string','foo','units','centimeters','position',[1 1 1 0.5]);
uicontrol('style','edit','string','foo','units','centimeters','position',[2 1 1 0.5]);
</code>```

I get the foo strings slightly misaligned, baseline of the text field is slightly above the baseline of edit/pop field.

How can I align those fields?

答:
Another option is to use the Jlabel, which is a Javacomponent. I have found the uicomponent from undocumentedMatlab helpful. You can download it from Mathworks File Exchange using this link:https://uk.mathworks.com/matlabcentral/fileexchange/14583-uicomponent-expands-uicontrol-to-all-java-classes

See this example:

```<code>figure(1);clf;

[txt1, txt2] = uicomponent(gcf, 'style','JLabel'); % simple spinner with initial value
set(txt1, 'Text', 'Test', 'units','centimeters','position',[1 1 1 1]);
set(txt2, 'horizontalAlignment', javax.swing.SwingConstants.LEFT);
set(txt2, 'VerticalAlignment', javax.swing.SwingConstants.CENTER);

uicontrol('style','edit','string','foo','units','centimeters','position',[2 1 1 1]);
</code>```

It can create a UI like below:

Title: Aligning text and edit uicontrols

Body:
I am creating GUI and I want to have inputs and results there.

I have text fields as labels and edit or popup for inputs. When I have

uicontrol('style','text','string','foo','units','centimeters','position',[1 1 1 0.5]);
uicontrol('style','edit','string','foo','units','centimeters','position',[2 1 1 0.5]);

I get the foo strings slightly misaligned, baseline of the text field is slightly above the baseline of edit/pop field.

How can I align those fields?

Body:
Another option is to use the Jlabel, which is a Javacomponent. I have found the uicomponent from undocumentedMatlab helpful. You can download it from Mathworks File Exchange using this link:https://uk.mathworks.com/matlabcentral/fileexchange/14583-uicomponent-expands-uicontrol-to-all-java-classes

See this example:

figure(1);clf;

[txt1, txt2] = uicomponent(gcf, 'style','JLabel'); % simple spinner with initial value
set(txt1, 'Text', 'Test', 'units','centimeters','position',[1 1 1 1]);
set(txt2, 'horizontalAlignment', javax.swing.SwingConstants.LEFT);
set(txt2, 'VerticalAlignment', javax.swing.SwingConstants.CENTER);

uicontrol('style','edit','string','foo','units','centimeters','position',[2 1 1 1]);

It can create a UI like below:


问:
sensu mailer and pipe
i'm switching over from nagios to sensu.  i'm using chef to automated the process.  everything is working great except the mailer or actually, i narrowed it down to the "pipe" that is suppose to redirect the json output from the check to the handler.  it doesn't.  when i use

```<code>{
  "handlers": {
    "email": {
      "type": "pipe",
      "command": "mail -s \"sensu alert\" alert@example.com",
      "severities": [
        "ok",
        "critical"
      ]
    }
  }
}
</code>```

i get a blank email.  when i use the mailer.rb handler, i get no email whatsoever. i made sure to include mail to and mail from in the mailer.json.  i see the logs have the correct information for the handler and email parameters.

so i've concluded the "pipe" isn't working.  can anybody help with that?  i would greatly appreciate it.  i wish there was a sensu community, but it may be too new to have one.

答:
You can use sensu mailer handler. Please find below steps to setup:-

sensu-install -p sensu-plugins-mailer

apt-get install postifx

/etc/init.d/postfix start

cd /etc/sensu/conf.d/

when we install this plugin will get 3 ruby files.

This time we are using this file:- handler-mailer.rb

First we need to creat handler file in this location /etc/sensu/conf.d/ :-

vim handler-mailer.json

{
     "mailer": {
         "admin_gui": "http://127.0.0.1:3000/",
         "mail_from": "localhost",
         "mail_to": ["yourmailid-1","yourmailid-2"],
         "smtp_address": "localhost",
         "smtp_port": "25"
     }
  }

Now we need to create one mail handler file in this location /etc/sensu/conf.d/:-

{
     "handlers": {
         "mymailer": {
             "type": "pipe",
             "command": "/opt/sensu/embedded/bin/handler-mailer.rb",
             "severities": [
                 "critical",
                 "unknown"
             ]
         }
     }
  }

in above file handler name is mymailer we need to use this handler name in our checks.

Title: sensu mailer and pipe

Body:
i'm switching over from nagios to sensu.  i'm using chef to automated the process.  everything is working great except the mailer or actually, i narrowed it down to the "pipe" that is suppose to redirect the json output from the check to the handler.  it doesn't.  when i use

{
  "handlers": {
    "email": {
      "type": "pipe",
      "command": "mail -s \"sensu alert\" alert@example.com",
      "severities": [
        "ok",
        "critical"
      ]
    }
  }
}

i get a blank email.  when i use the mailer.rb handler, i get no email whatsoever. i made sure to include mail to and mail from in the mailer.json.  i see the logs have the correct information for the handler and email parameters.

so i've concluded the "pipe" isn't working.  can anybody help with that?  i would greatly appreciate it.  i wish there was a sensu community, but it may be too new to have one.


问:
Java ArrayList Index
```<code>int[] alist = new int [3];
alist.add("apple");
alist.add("banana");
alist.add("orange");
</code>```

Say that I want to use the second item in the ArrayList. What is the coding in order to get the following output?

output:

banana

答:
You have ArrayList all wrong,

You can't have an integer array and assign a string value.

You cannot do a add() method in an array

Rather do this:

```<code>List<String> alist = new ArrayList<String>();
alist.add("apple");
alist.add("banana");
alist.add("orange");

String value = alist.get(1); //returns the 2nd item from list, in this case "banana"
</code>```

Indexing is counted from 0 to N-1 where N is size() of list.

Title: Java ArrayList Index

Body:
int[] alist = new int [3];
alist.add("apple");
alist.add("banana");
alist.add("orange");

Say that I want to use the second item in the ArrayList. What is the coding in order to get the following output?

output:

banana

Body:
You have ArrayList all wrong,

You can't have an integer array and assign a string value.

You cannot do a add() method in an array

Rather do this:

List<String> alist = new ArrayList<String>();
alist.add("apple");
alist.add("banana");
alist.add("orange");

String value = alist.get(1); //returns the 2nd item from list, in this case "banana"

Indexing is counted from 0 to N-1 where N is size() of list.