问:
How to pass, from <input>, a different value that the chosen one
I use <input> to choose a value in a Vue.js context. The context does not matter (I believe) - this is just to say the value of the <input> field is always synchronized with a variable called searchedName and that there is no actual "submission" of the input (as it is already available at all times):

<input id="searchedName" list="foundNames">
<datalist id="foundNames">
    <option>One</option>
    <option>Two</option>
    <option>Three</option>
</datalist>```
</div>
</div>
</p>

<p>When choosing from the dropdown a value, it is this exact string which is chosen (<code>One</code> for instance). </p>

<p>I would like, however, this string to just be a display name, and that the actual choice is an Object. As an example, when choosing <code>One</code> from the dropdown, I would like to pass further <code>{"choice": "one", "value": 1, "weather": ["cloudy", "rainy"]}</code> - and not the string <code>"One"</code>.</p>

<p><strong>Is this possible?</strong></p>

<hr>

<p><strong>EDIT</strong>: Just in case, I am posting the actual Vue.js code which handle this bit. <code>foundNames</code> is updated somewhere else (in an AJAX call) and is an Array of Objects. The <code>addID</code> method is supposed to use <code>{{name._source}}</code>, which is currently displayed as it. I would like to hide it and display some of its elements instead.</p>

```
            Input "Something":
            <input v-model="searchedName" list="foundNames">
            <datalist id="foundNames">
                <option v-for="name in foundNames" value="name">{{name._source}}</option>
            </datalist>

        <button v-on:click="addID">add name</button>
```

<p>Looking at the first answers, the way to go would be something along the lines of </p>

```<option v-for="name in foundNames" value="name">{{name._source.interesingelementtodisplay}}</option>
```

but value="name" sets the value to "name" (verbatim) and not the current value of the variable name in the v-for iteration.

答:
The answer in your edit is close. You need to bind the value.

```<code><option v-for="name in foundNames" :value="name">{{name._source.interesingelementtodisplay}}</option>
</code>```

or

```<code><option v-for="name in foundNames" v-bind:value="name">{{name._source.interesingelementtodisplay}}</option>
</code>```

Note the : in front of value. If you do not bind it, it will just be the literal value between the quotes, which, as you found, is just name.

Body:
I use <input> to choose a value in a Vue.js context. The context does not matter (I believe) - this is just to say the value of the <input> field is always synchronized with a variable called searchedName and that there is no actual "submission" of the input (as it is already available at all times):

<input id="searchedName" list="foundNames">
<datalist id="foundNames">
    <option>One</option>
    <option>Two</option>
    <option>Three</option>
</datalist>

When choosing from the dropdown a value, it is this exact string which is chosen (One for instance).

I would like, however, this string to just be a display name, and that the actual choice is an Object. As an example, when choosing One from the dropdown, I would like to pass further {"choice": "one", "value": 1, "weather": ["cloudy", "rainy"]} - and not the string "One".

Is this possible?

EDIT: Just in case, I am posting the actual Vue.js code which handle this bit. foundNames is updated somewhere else (in an AJAX call) and is an Array of Objects. The addID method is supposed to use {{name._source}}, which is currently displayed as it. I would like to hide it and display some of its elements instead.

            Input "Something":
            <input v-model="searchedName" list="foundNames">
            <datalist id="foundNames">
                <option v-for="name in foundNames" value="name">{{name._source}}</option>
            </datalist>

        <button v-on:click="addID">add name</button>

Looking at the first answers, the way to go would be something along the lines of

<option v-for="name in foundNames" value="name">{{name._source.interesingelementtodisplay}}</option>

but value="name" sets the value to "name" (verbatim) and not the current value of the variable name in the v-for iteration.

Body:
The answer in your edit is close. You need to bind the value.

<option v-for="name in foundNames" :value="name">{{name._source.interesingelementtodisplay}}</option>

or

<option v-for="name in foundNames" v-bind:value="name">{{name._source.interesingelementtodisplay}}</option>

Note the : in front of value. If you do not bind it, it will just be the literal value between the quotes, which, as you found, is just name.

ContentLicense: CC BY-SA 4.0


来源: stackexchange

问:
CSS background image make darker
I have the following: www.thewhozoo.com

As you can see, it has a background image.

```<code>.top-container {
    float: left;
    width: 100%;
    background: url('../images/background1.jpg') no-repeat center center fixed;
       -webkit-background-size: cover;
       -moz-background-size: cover;
       -o-background-size: cover;
       background-size: cover;
  }
</code>```

The background image has white text on top of it, which may be a little difficult to read.

I have added a text-shadow to the text, which has helped make the text stand out more.

```<code>.text-description-header {
    font-size: 250%;
    color: white;
    text-shadow: 0px 1px 14px rgba(0,0,0,1.0);
}
</code>```

However, I would like the text to stand out even more.

Question

Are there suggestions how I can make the text-shadow even darker?

Or, make the background image a little darker?

Thanks

答:
You can stack multiple text shadows with , to make it darker.

```<code>text-shadow: 0px 0px 10px black, 0px 0px 10px black;
</code>```

ContentLicense: CC BY-SA 3.0

Title: CSS background image make darker

Body:
I have the following: www.thewhozoo.com

As you can see, it has a background image.

.top-container {
    float: left;
    width: 100%;
    background: url('../images/background1.jpg') no-repeat center center fixed;
       -webkit-background-size: cover;
       -moz-background-size: cover;
       -o-background-size: cover;
       background-size: cover;
  }

The background image has white text on top of it, which may be a little difficult to read.

I have added a text-shadow to the text, which has helped make the text stand out more.

.text-description-header {
    font-size: 250%;
    color: white;
    text-shadow: 0px 1px 14px rgba(0,0,0,1.0);
}

However, I would like the text to stand out even more.

Question

Are there suggestions how I can make the text-shadow even darker?

Or, make the background image a little darker?

Thanks

Body:
You can stack multiple text shadows with , to make it darker.

text-shadow: 0px 0px 10px black, 0px 0px 10px black;


问:
How do I return the success value of chaining multiple Results if no errors occur or another value if any error happens?
I'm trying to play with chaining multiple Results. I want to write a function which receives a &[u8] and returns a Tm. If any of the steps give a error, I just want to return time::now().

I wrote:

```<code>extern crate time;

use time::{strptime, Tm};
use std::str;

pub fn buf_to_tm(buffer: &[u8]) -> Tm {
    str::from_utf8(buffer)
        .and_then(|val| strptime(val, "%d %b %y%H:%M:%S"))
        .unwrap_or(time::now())
}
</code>```

But I'm getting this error:

error[E0308]: mismatched types
 --> src/main.rs:8:25
  |
8 |         .and_then(|val| strptime(val, "%d %b %y%H:%M:%S"))
  |                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected struct `std::str::Utf8Error`, found enum `time::ParseError`
  |
  = note: expected type `std::result::Result<_, std::str::Utf8Error>`
             found type `std::result::Result<time::Tm, time::ParseError>`
  = help: here are some functions which might fulfill your needs:
          - .unwrap()
          - .unwrap_err()
```

How do I tell Rust I don't really care what type of error this code gives, I just want to return the parsed Tm if no errors occur or time::now() if any error happens.

答:
Since you don't care about which error was the cause of the failure, you can fix this in a simple way by mapping both error types to (), or Result<T, _> => Option<T>, since Result<T, ()> is isomorphic to Option<T>.

This is done with the function .ok() seen here:

```<code>extern crate time;

use time::{strptime, Tm};
use std::str;

pub fn buf_to_tm(buffer: &[u8]) -> Tm {
    str::from_utf8(buffer).ok()
        .and_then(|val| strptime(val, "%d %b %y%H:%M:%S").ok())
        .unwrap_or_else(time::now)
}
</code>```

Body:
I'm trying to play with chaining multiple Results. I want to write a function which receives a &[u8] and returns a Tm. If any of the steps give a error, I just want to return time::now().

I wrote:

extern crate time;

use time::{strptime, Tm};
use std::str;

pub fn buf_to_tm(buffer: &[u8]) -> Tm {
    str::from_utf8(buffer)
        .and_then(|val| strptime(val, "%d %b %y%H:%M:%S"))
        .unwrap_or(time::now())
}

But I'm getting this error:

error[E0308]: mismatched types
 --> src/main.rs:8:25
  |
8 |         .and_then(|val| strptime(val, "%d %b %y%H:%M:%S"))
  |                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected struct `std::str::Utf8Error`, found enum `time::ParseError`
  |
  = note: expected type `std::result::Result<_, std::str::Utf8Error>`
             found type `std::result::Result<time::Tm, time::ParseError>`
  = help: here are some functions which might fulfill your needs:
          - .unwrap()
          - .unwrap_err()

How do I tell Rust I don't really care what type of error this code gives, I just want to return the parsed Tm if no errors occur or time::now() if any error happens.

Body:
Since you don't care about which error was the cause of the failure, you can fix this in a simple way by mapping both error types to (), or Result<T, _> => Option<T>, since Result<T, ()> is isomorphic to Option<T>.

This is done with the function .ok() seen here:

extern crate time;

use time::{strptime, Tm};
use std::str;

pub fn buf_to_tm(buffer: &[u8]) -> Tm {
    str::from_utf8(buffer).ok()
        .and_then(|val| strptime(val, "%d %b %y%H:%M:%S").ok())
        .unwrap_or_else(time::now)
}


问:
A web app with logins in a kiosk situation
We are looking at setting up an internal web application (ASP.NET MVC) as a kiosk for the employees that don't have a dedicated computer. We currently do not have this kiosk setup. Each employee will have their own login to look at some basic payroll information and request leaves of absence. This same web application will be used by the office workers with a dedicated PC at their desk.

I am going to go out on a limb and say that no matter how many times we tell the employees, the employees will not click log off when they walk away from the kiosk. What would you do to help prevent this from happening?

答:
Assuming you've already thought of the obvious (aggressive session timeouts, non-persistent authentication cookies, etc); how about a bit of an "out there" suggestion?

I'm not sure how do-able this would be with a web-based interface; but what about using some form of IR sensor with a usb/serial interface and an API you can tie into? This may make it possible to invoke some form of "logout" operation when someone walks away from the kiosk.

Perhaps someone has a better suggestion for external hardware, but this was the first thing that lept to my mind as a out-of-the-box approach.

ContentLicense: CC BY-SA 2.5


问:
How to sign xml with X509 cert, add digest value and signature to xml template
I am quite new to C# and especially new to Signing with X509. I have an xml template in which I have to add the certificate used (done) and sign the timestamp (TS-1), the binary security token and the body (id-1).
Furthermore, I need to write (e.g. replace placeholders) with the digest value of these 3 elements and add the signature value.

However, I do not really understand the concept, e.g. how to do this. I read a couple of websites, e.g. signing a xml document with x509 certificate
but I cannot adapt the code to my problem.

Here is what I tried:

```<code>public static string SignXml(string template)
{

    XmlDocument document = new XmlDocument();
    document.LoadXml(template);

        // define elements that will be signed
        XmlNode securityToken = null;
        XmlNode validityPeriod = null;
        XmlNode body = null;
        XmlNode signedInfo = null;
        XmlNode signatureValue = null;
        XmlNodeList digestTags = null;

        XmlNamespaceManager namespaces = new XmlNamespaceManager(document.NameTable);
        namespaces.AddNamespace("ns", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
        namespaces.AddNamespace("nu", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
        namespaces.AddNamespace("bo", "http://schemas.xmlsoap.org/soap/envelope/");
        namespaces.AddNamespace("si", "http://www.w3.org/2000/09/xmldsig#");
        namespaces.AddNamespace("sinfo", "soapenv xd xe");

        document.LoadXml(template);
        //XmlNode idNode = document.SelectSingleNode("/My_RootNode/ns:id", namespaces);

        securityToken = document.SelectSingleNode("descendant::ns:BinarySecurityToken", namespaces);
        validityPeriod = document.SelectSingleNode("descendant::nu:Timestamp", namespaces);
        body = document.SelectSingleNode("descendant::bo:Body", namespaces);
        signedInfo = document.SelectSingleNode("descendant::si:SignedInfo", namespaces);
        signatureValue = document.SelectSingleNode("descendant::si::sinfo:SignatureValue", namespaces);
        digestTags = document.SelectNodes("descendant::si:DigestValue", namespaces);

        // add the digests (to know where to write the digests)
        String nodeName = null;
        for (int counter = 0; counter < digestTags.Count; counter++)
        {
            nodeName = digestTags[counter].FirstChild.InnerText;
            if (WebserviceConstants.PLACEHOLDER_AUTHNREQUEST_DIGEST.Equals(nodeName))
            {

                generateDigest(body, digestTags[counter]);
            }
            else if (WebserviceConstants.PLACEHOLDER_CERTIFICATE_DIGEST.Equals(nodeName))
            {

                generateDigest(securityToken, digestTags[counter]);
            }
            else if (WebserviceConstants.PLACEHOLDER_TIMESTAMP_TAG_DIGEST.Equals(nodeName))
            {

                generateDigest(validityPeriod, digestTags[counter]);
            }
        }

        SignedXml signedXml = new SignedXml(document);

    X509Certificate2 cert = new X509Certificate2();
    cert = getbase();

    signedXml.SigningKey = cert.PrivateKey;

    // Create a reference to be signed.
    Reference reference = new Reference();
    reference.Uri = "#TS-1";

    // Add an enveloped transformation to the reference.
    XmlDsigEnvelopedSignatureTransform env =
       new XmlDsigEnvelopedSignatureTransform(true);
    reference.AddTransform(env);

    //canonicalize
    XmlDsigC14NTransform c14t = new XmlDsigC14NTransform();
    reference.AddTransform(c14t);

    KeyInfo keyInfo = new KeyInfo();
    KeyInfoX509Data keyInfoData = new KeyInfoX509Data(cert);
    KeyInfoName kin = new KeyInfoName();
    kin.Value = "Public key of certificate";
    RSACryptoServiceProvider rsaprovider = (RSACryptoServiceProvider)cert.PublicKey.Key;
    RSAKeyValue rkv = new RSAKeyValue(rsaprovider);
    keyInfo.AddClause(kin);
    keyInfo.AddClause(rkv);
    keyInfo.AddClause(keyInfoData);
    signedXml.KeyInfo = keyInfo;

    // Add the reference to the SignedXml object.
    signedXml.AddReference(reference);

    // Compute the signature.
    signedXml.ComputeSignature();

    // Get the XML representation of the signature and save
    // it to an XmlElement object.
    XmlElement xmlDigitalSignature = signedXml.GetXml();

    document.DocumentElement.AppendChild(
    document.ImportNode(xmlDigitalSignature, true));
    document.DocumentElement.AppendChild(document.ImportNode(xmlDigitalSignature, true));

        return document.OuterXml;
    }
}
</code>```

I am questioning myself:

How do I get the digest value and how to write it to the corresponding xml node

How to calculate the signature value as it "contains" the signed info of all 3 references???

As you can see, I am missing some general background and understanding. Would be really cool if you could help me out!

Thank you

答:
You don't have to manually create the nodes of the signature, after you compute the signature you call the GetXml method (you are already doing it: signedXml.GetXml()) and this will return something like this:

```<code><Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
  <SignedInfo>
    <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
    <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" />
    <Reference URI="">
        <Transforms>
            <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
            <Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
        </Transforms>
        <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
        <DigestValue>zRSPtja5EtX7hVbyJ11EjoYTRDk=</DigestValue>
    </Reference>
  </SignedInfo>
  <SignatureValue>Ua1/WP28WzfXaxUj....</SignatureValue>
  <KeyInfo>
    <X509Data>
        <X509Certificate>MIIF3jCCBUegAwIBAgIEPQa1....</X509Certificate>
    </X509Data>
  </KeyInfo>
</Signature>
</code>```

Then you will only have to replace the whole signature node on your xml template.

--Keeping in mind that the SignedXml will give you that structure now I'll answer your questions

Your first question is it about the digest value of your references? If so, when you call the ComputeSignature method it will calculate it and add it to the corresponding xml node.

The signature value is calculated when you compute the signature you don't have to calculate it yourself.

When you call the ComputeSignature method what it does is take the SignedInfo node and digest it. Your references are inside this node so you will get the signature value containing the info of all your references

This is how the ComputeSignature method gets the digest value of the signedinfo node,using this value it calculates the signature value:

```<code>XmlElement e = this.SignedInfo.GetXml(); //get the signedinfo nodes
document.AppendChild(document.ImportNode(e, true));
Transform canonicalizationMethodObject=this.SignedInfo.CanonicalizationMethodObject;
canonicalizationMethodObject.LoadInput(document);
canonicalizationMethodObject.GetDigestedOutput(hash); //digest the signedinfo node
</code>```

Body:
I am quite new to C# and especially new to Signing with X509. I have an xml template in which I have to add the certificate used (done) and sign the timestamp (TS-1), the binary security token and the body (id-1).
Furthermore, I need to write (e.g. replace placeholders) with the digest value of these 3 elements and add the signature value.

However, I do not really understand the concept, e.g. how to do this. I read a couple of websites, e.g. signing a xml document with x509 certificate
but I cannot adapt the code to my problem.

Here is what I tried:

public static string SignXml(string template)
{

    XmlDocument document = new XmlDocument();
    document.LoadXml(template);

        // define elements that will be signed
        XmlNode securityToken = null;
        XmlNode validityPeriod = null;
        XmlNode body = null;
        XmlNode signedInfo = null;
        XmlNode signatureValue = null;
        XmlNodeList digestTags = null;

        XmlNamespaceManager namespaces = new XmlNamespaceManager(document.NameTable);
        namespaces.AddNamespace("ns", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
        namespaces.AddNamespace("nu", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
        namespaces.AddNamespace("bo", "http://schemas.xmlsoap.org/soap/envelope/");
        namespaces.AddNamespace("si", "http://www.w3.org/2000/09/xmldsig#");
        namespaces.AddNamespace("sinfo", "soapenv xd xe");

        document.LoadXml(template);
        //XmlNode idNode = document.SelectSingleNode("/My_RootNode/ns:id", namespaces);

        securityToken = document.SelectSingleNode("descendant::ns:BinarySecurityToken", namespaces);
        validityPeriod = document.SelectSingleNode("descendant::nu:Timestamp", namespaces);
        body = document.SelectSingleNode("descendant::bo:Body", namespaces);
        signedInfo = document.SelectSingleNode("descendant::si:SignedInfo", namespaces);
        signatureValue = document.SelectSingleNode("descendant::si::sinfo:SignatureValue", namespaces);
        digestTags = document.SelectNodes("descendant::si:DigestValue", namespaces);

        // add the digests (to know where to write the digests)
        String nodeName = null;
        for (int counter = 0; counter < digestTags.Count; counter++)
        {
            nodeName = digestTags[counter].FirstChild.InnerText;
            if (WebserviceConstants.PLACEHOLDER_AUTHNREQUEST_DIGEST.Equals(nodeName))
            {

                generateDigest(body, digestTags[counter]);
            }
            else if (WebserviceConstants.PLACEHOLDER_CERTIFICATE_DIGEST.Equals(nodeName))
            {

                generateDigest(securityToken, digestTags[counter]);
            }
            else if (WebserviceConstants.PLACEHOLDER_TIMESTAMP_TAG_DIGEST.Equals(nodeName))
            {

                generateDigest(validityPeriod, digestTags[counter]);
            }
        }

        SignedXml signedXml = new SignedXml(document);

    X509Certificate2 cert = new X509Certificate2();
    cert = getbase();

    signedXml.SigningKey = cert.PrivateKey;

    // Create a reference to be signed.
    Reference reference = new Reference();
    reference.Uri = "#TS-1";

    // Add an enveloped transformation to the reference.
    XmlDsigEnvelopedSignatureTransform env =
       new XmlDsigEnvelopedSignatureTransform(true);
    reference.AddTransform(env);

    //canonicalize
    XmlDsigC14NTransform c14t = new XmlDsigC14NTransform();
    reference.AddTransform(c14t);

    KeyInfo keyInfo = new KeyInfo();
    KeyInfoX509Data keyInfoData = new KeyInfoX509Data(cert);
    KeyInfoName kin = new KeyInfoName();
    kin.Value = "Public key of certificate";
    RSACryptoServiceProvider rsaprovider = (RSACryptoServiceProvider)cert.PublicKey.Key;
    RSAKeyValue rkv = new RSAKeyValue(rsaprovider);
    keyInfo.AddClause(kin);
    keyInfo.AddClause(rkv);
    keyInfo.AddClause(keyInfoData);
    signedXml.KeyInfo = keyInfo;

    // Add the reference to the SignedXml object.
    signedXml.AddReference(reference);

    // Compute the signature.
    signedXml.ComputeSignature();

    // Get the XML representation of the signature and save
    // it to an XmlElement object.
    XmlElement xmlDigitalSignature = signedXml.GetXml();

    document.DocumentElement.AppendChild(
    document.ImportNode(xmlDigitalSignature, true));
    document.DocumentElement.AppendChild(document.ImportNode(xmlDigitalSignature, true));

        return document.OuterXml;
    }
}

I am questioning myself:

How do I get the digest value and how to write it to the corresponding xml node

How to calculate the signature value as it "contains" the signed info of all 3 references???

As you can see, I am missing some general background and understanding. Would be really cool if you could help me out!

Thank you

Body:
You don't have to manually create the nodes of the signature, after you compute the signature you call the GetXml method (you are already doing it: signedXml.GetXml()) and this will return something like this:

<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
  <SignedInfo>
    <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
    <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" />
    <Reference URI="">
        <Transforms>
            <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
            <Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
        </Transforms>
        <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
        <DigestValue>zRSPtja5EtX7hVbyJ11EjoYTRDk=</DigestValue>
    </Reference>
  </SignedInfo>
  <SignatureValue>Ua1/WP28WzfXaxUj....</SignatureValue>
  <KeyInfo>
    <X509Data>
        <X509Certificate>MIIF3jCCBUegAwIBAgIEPQa1....</X509Certificate>
    </X509Data>
  </KeyInfo>
</Signature>

Then you will only have to replace the whole signature node on your xml template.

--Keeping in mind that the SignedXml will give you that structure now I'll answer your questions

Your first question is it about the digest value of your references? If so, when you call the ComputeSignature method it will calculate it and add it to the corresponding xml node.

The signature value is calculated when you compute the signature you don't have to calculate it yourself.

When you call the ComputeSignature method what it does is take the SignedInfo node and digest it. Your references are inside this node so you will get the signature value containing the info of all your references

This is how the ComputeSignature method gets the digest value of the signedinfo node,using this value it calculates the signature value:

XmlElement e = this.SignedInfo.GetXml(); //get the signedinfo nodes
document.AppendChild(document.ImportNode(e, true));
Transform canonicalizationMethodObject=this.SignedInfo.CanonicalizationMethodObject;
canonicalizationMethodObject.LoadInput(document);
canonicalizationMethodObject.GetDigestedOutput(hash); //digest the signedinfo node


问:
Amazon EC2 instance
I have setup an amazon EC2 intance using the command line tools. I have create a key pair for it etc. and it is up and running. I try to SSH into it using the following (I am running bash in Snow Leopard):

```<code>$ ssh -i ec2-keypair root@ec2-xxx-xxx-xx-xx.compute-1.amazonaws.com
</code>```

Snow Leopard pops up a box saying "Enter you password for the SSH key "ec2-keypair" ". Can someone please tell me what I should do? If I don't provide a password its just asks me for one in the bash terminal.

Thanks for the response. I create a key pair for Amazon EC2 using:

```<code>ec2-add-keypair ec2-keypair
</code>```

I have create a password protected sash key and now have two files in my .ssh directory:

```<code>id_rsa
id_rsa.pub
</code>```

Do I need to transfer one of these to my EC2 instance? Which one? What is the best way of doing this and where shall I put?

Max.

Any help greatly appreciated as I have spent some while trying to sort this out.

Max.

答:
The username should be ec2-user and not root. ssh Like this</p>

```<code>$ ssh -i ec2-keypair ec2-user@ec2-xxx-xxx-xx-xx.compute-1.amazonaws.com
</code>```

Title: Amazon EC2 instance

Body:
I have setup an amazon EC2 intance using the command line tools. I have create a key pair for it etc. and it is up and running. I try to SSH into it using the following (I am running bash in Snow Leopard):

$ ssh -i ec2-keypair root@ec2-xxx-xxx-xx-xx.compute-1.amazonaws.com

Snow Leopard pops up a box saying "Enter you password for the SSH key "ec2-keypair" ". Can someone please tell me what I should do? If I don't provide a password its just asks me for one in the bash terminal.

Thanks for the response. I create a key pair for Amazon EC2 using:

ec2-add-keypair ec2-keypair

I have create a password protected sash key and now have two files in my .ssh directory:

id_rsa
id_rsa.pub

Do I need to transfer one of these to my EC2 instance? Which one? What is the best way of doing this and where shall I put?

Max.

Any help greatly appreciated as I have spent some while trying to sort this out.

Max.

Body:
The username should be ec2-user and not root. ssh Like this

$ ssh -i ec2-keypair ec2-user@ec2-xxx-xxx-xx-xx.compute-1.amazonaws.com


问:
UIButton Text Margin / Padding
I have the following layout, and I'm trying to add a padding to the left and right..

The controls are a disabled UIButton.

My code for creating a button is this:

```<code>UIButton *buttonTime = [[UIButton alloc] initWithFrame:CGRectMake(90, 10, 50, 20)];
[buttonTime setBackgroundImage:[[UIImage imageNamed:@"bubble.png"] stretchableImageWithLeftCapWidth:9 topCapHeight:13] forState:UIControlStateDisabled];

[buttonTime setTitle:@"27 feb, 2011 11:10 PM" forState:UIControlStateDisabled];
[buttonTime setTitleColor:[UIColor blackColor] forState:UIControlStateDisabled];
buttonTime.titleLabel.font=[UIFont fontWithName:@"Helvetica" size:8.0];
buttonTime.titleLabel.lineBreakMode= UILineBreakModeWordWrap;
[buttonTime setEnabled:FALSE];
[scrollView addSubview:buttonTime];
[buttonTime release];
</code>```

答:
This option is also viable if its not too annoying to use a UIButton subclass

```<code>class Button: UIButton {
    override var intrinsicContentSize: CGSize {
        get {
            let baseSize = super.intrinsicContentSize
            return CGSize(width: baseSize.width + titleEdgeInsets.left + titleEdgeInsets.right,
                          height: baseSize.height + titleEdgeInsets.top + titleEdgeInsets.bottom)
        }
    }
}
</code>```

Then use titleEdgeInsets as desired

```<code> let button = Button()
 ... configure button
 button.titleEdgeInsets = ...
</code>```

Title: UIButton Text Margin / Padding

Body:
I have the following layout, and I'm trying to add a padding to the left and right..

The controls are a disabled UIButton.

My code for creating a button is this:

UIButton *buttonTime = [[UIButton alloc] initWithFrame:CGRectMake(90, 10, 50, 20)];
[buttonTime setBackgroundImage:[[UIImage imageNamed:@"bubble.png"] stretchableImageWithLeftCapWidth:9 topCapHeight:13] forState:UIControlStateDisabled];

[buttonTime setTitle:@"27 feb, 2011 11:10 PM" forState:UIControlStateDisabled];
[buttonTime setTitleColor:[UIColor blackColor] forState:UIControlStateDisabled];
buttonTime.titleLabel.font=[UIFont fontWithName:@"Helvetica" size:8.0];
buttonTime.titleLabel.lineBreakMode= UILineBreakModeWordWrap;
[buttonTime setEnabled:FALSE];
[scrollView addSubview:buttonTime];
[buttonTime release];

Body:
This option is also viable if its not too annoying to use a UIButton subclass

class Button: UIButton {
    override var intrinsicContentSize: CGSize {
        get {
            let baseSize = super.intrinsicContentSize
            return CGSize(width: baseSize.width + titleEdgeInsets.left + titleEdgeInsets.right,
                          height: baseSize.height + titleEdgeInsets.top + titleEdgeInsets.bottom)
        }
    }
}

Then use titleEdgeInsets as desired

 let button = Button()
 ... configure button
 button.titleEdgeInsets = ...


问:
ol inside li causing problems
I have the following code :

```<code><!DOCTYPE html>
<html>
<head>
    <title>Page Title</title>
    <meta charset="utf-8">

    <style>
.nav{
    border:1px solid #ccc;
    border-width:1px 0;
    list-style:none;
    margin:0;
    padding:0;
    text-align:center;
    background-color: #333;
}
.navLi{
    display:inline;
}
.nav ol{
  display:flex;

}
.nav a{
    display:inline-block;

    padding:10px;
 text-align: center;
    padding: 14px 16px;
    text-decoration: none;
    font-size: 17px;
    color:white;
}
.green{
    background-color:green;
}
.blue{
    background-color:blue;
}
.sideBar{
width:25%;
background:#333;
height: 850px;
}
.whiteColor{
  color:white;
}
.paragraph{
    padding: 20px;
    line-height: 150%;
    font-family: ariel;

}
.div1{
width: 75%;
background: white;
}
.textSize{
  font-size: 1px;
}
.div2{
    border:solid 1px;
    display:flex;
}
.image{
float:left;
}
.maxDiv{
    max-width: 1000px;
     margin: auto;
    width: 50%;
    border: 3px solid green;
    padding: 10px;
}

    </style>

</head>
<body>
<div class="maxDiv">
<div  id="myTopnav">
<ul class="nav">
 <li class="navLi"> <a href="givataiim.html" class = "green">0</a></li>
  <li  class="navLi"><a href="#news" >1</a></li>
  <li  class="navLi"><a href="#contact">2</a></li>
  <li  class="navLi"><a href="#about">3</a></li>
  <li  class="navLi"><a href="#about">4</a></li>
  <li  class="navLi"><a href="rishon.html" class = "blue">5</a></li>
  <li  class="navLi"><a href="#about">6</a></li>
  <li  class="navLi"><a href="hw9.html">7</a></li>
</ul>
</div>
</code>```

I want each of the li to have an ordered list below it (I know that it won't look pretty)
I tried making an ol element and some li inside of it and it looks weird.
When I do the ol inside each li and inside that ol I put some li it looks something like:

Code :

```<code> <li class="navLi"> <a href="1.html" class = "green">0</a>
 <ol>
  <li  class="navLi"><a href="#news" >1</a></li>
  <li  class="navLi"><a href="#news" >1</a></li>
 </ol>
 </li>
</code>```

The ol inside the li looks not good as marked in the red square in the photo.

Any idea ?

答:
You can hover 4 to see a submenu. I cleaned up the CSS, deleted classes/IDs I couldn't find being used.

The submenu has absolute positioning. Both menus are now defined using flexbox.

.nav {
  display: flex;
  justify-content: center;
  align-items: flex-start;
  list-style: none;
  margin: 0;
  padding: 0;
}

.navLi {
  border-top: 1px solid #ccc;
  border-bottom: 1px solid #ccc;
  position: relative;
}

.nav ol {
  display: none;
  position: absolute;
  background-color: red;
  list-style: none;
  padding: 0;
  margin: 1px;
}

.navLi:hover ol {
  display: flex;
  justify-content: center;
  align-items: center;
}

.navLi:hover ol li {
  padding: 14px 16px;
}

a {
  display: block;
  padding: 14px 16px;
  text-decoration: none;
  background-color: #333;
  font-size: 17px;
  color: white;
}

.green {
  background-color: green;
}

.blue {
  background-color: blue;
}

.maxDiv {
  max-width: 1000px;
  margin: auto;
  border: 3px solid green;
  padding: 10px;
  background-color: #333;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="maxDiv">
  <ul class="nav">
    <li class="navLi">0</li>
    <li class="navLi">1</li>
    <li class="navLi">2</li>
    <li class="navLi">3</li>
    <li class="navLi">4
      <ol>
        <li>1</li>
        <li>2</li>
        <li>3</li>
      </ol>
    </li>
    <li class="navLi">5</li>
    <li class="navLi">6</li>
    <li class="navLi">7</li>
  </ul>
</div></code>```

Title: ol inside li causing problems

Body:
I have the following code :

<!DOCTYPE html>

    <title>Page Title</title>
    <meta charset="utf-8">

 0

1

2

3

4

5

6

7

I want each of the li to have an ordered list below it (I know that it won't look pretty)
I tried making an ol element and some li inside of it and it looks weird.
When I do the ol inside each li and inside that ol I put some li it looks something like:

Code :

 0

1

1

The ol inside the li looks not good as marked in the red square in the photo.

Any idea ?

Body:
You can hover 4 to see a submenu. I cleaned up the CSS, deleted classes/IDs I couldn't find being used.

The submenu has absolute positioning. Both menus are now defined using flexbox.

.nav {
  display: flex;
  justify-content: center;
  align-items: flex-start;
  list-style: none;
  margin: 0;
  padding: 0;
}

.navLi {
  border-top: 1px solid #ccc;
  border-bottom: 1px solid #ccc;
  position: relative;
}

.nav ol {
  display: none;
  position: absolute;
  background-color: red;
  list-style: none;
  padding: 0;
  margin: 1px;
}

.navLi:hover ol {
  display: flex;
  justify-content: center;
  align-items: center;
}

.navLi:hover ol li {
  padding: 14px 16px;
}

a {
  display: block;
  padding: 14px 16px;
  text-decoration: none;
  background-color: #333;
  font-size: 17px;
  color: white;
}

.green {
  background-color: green;
}

.blue {
  background-color: blue;
}

.maxDiv {
  max-width: 1000px;
  margin: auto;
  border: 3px solid green;
  padding: 10px;
  background-color: #333;
}

<div class="maxDiv">
  <ul class="nav">
    <li class="navLi"><a href="givataiim.html" class="green">0</a></li>
    <li class="navLi"><a href="#news">1</a></li>
    <li class="navLi"><a href="#contact">2</a></li>
    <li class="navLi"><a href="#about">3</a></li>
    <li class="navLi"><a href="#about">4</a>
      <ol>
        <li>1</li>
        <li>2</li>
        <li>3</li>
      </ol>
    </li>
    <li class="navLi"><a href="rishon.html" class="blue">5</a></li>
    <li class="navLi"><a href="#about">6</a></li>
    <li class="navLi"><a href="hw9.html">7</a></li>
  </ul>
</div>


问:
Submit form that is located on different page
I'm having some troubles with the system I work on. I want to submit a form that is located on page A after submission but also after a user does something on page B or enters it or leaves it.

I want to make it so that after the user enters or leaves page B the form that is located on page A will be submitted without the user doing anything.

So far I've tried to submit the form from the page B with plain JavaScript and jQuery...

```<code><script type="text/javascript">
document.getElementById("formID").submit();
</script>
</code>```

... as well as doing the same with jQuery...

```<code>jQuery( document ).ready( function() {
    jQuery( "#formID" ).submit();
    });
</code>```

I even tried to add an onClick function to the form and this function I've placed in page B but it didn't work.

I'm open for ideas or possible fixes.

答:
Provided I understand your question correctly, the simple answer is you can't. JavaScript can only interact with the currently loaded page (it has no awareness of other browser tabs or anything similar, for security reasons).

Since it sounds like you don't require the user's input for the second form (otherwise why would you submit it automatically) then I would look into bringing the second form's data into the first one.

I probably shouldn't even suggest it because it really would be a terrible practice.... but you could trigger the second form's submission on the load event of the second page...

```<code>$(function(){ //in the html of the second page to load
    $('#form2').submit();
});
</code>```

this would cause the user to navigate to the second page, only to have them leave it at the instant of load and would be a terrible user experience.. but would answer the question you asked.

Body:
I'm having some troubles with the system I work on. I want to submit a form that is located on page A after submission but also after a user does something on page B or enters it or leaves it.

I want to make it so that after the user enters or leaves page B the form that is located on page A will be submitted without the user doing anything.

So far I've tried to submit the form from the page B with plain JavaScript and jQuery...

... as well as doing the same with jQuery...

jQuery( document ).ready( function() {
    jQuery( "#formID" ).submit();
    });

I even tried to add an onClick function to the form and this function I've placed in page B but it didn't work.

I'm open for ideas or possible fixes.

Body:
Provided I understand your question correctly, the simple answer is you can't. JavaScript can only interact with the currently loaded page (it has no awareness of other browser tabs or anything similar, for security reasons).

Since it sounds like you don't require the user's input for the second form (otherwise why would you submit it automatically) then I would look into bringing the second form's data into the first one.

I probably shouldn't even suggest it because it really would be a terrible practice.... but you could trigger the second form's submission on the load event of the second page...

$(function(){ //in the html of the second page to load
    $('#form2').submit();
});

this would cause the user to navigate to the second page, only to have them leave it at the instant of load and would be a terrible user experience.. but would answer the question you asked.


问:
parsing xml data return empty value in php
i'm trying to parse data in xml with simple_load_string function in php and it's return an empty data in the $parsed (data parsed) .

the data to parse is like :

```<code><cas:serviceResponse xmlns:cas="http://www.yale.edu/tp/cas">
    <cas:authenticationSuccess>
        <cas:user>yassine458</cas:user>
    </cas:authenticationSuccess>
</cas:serviceResponse>
</code>```

is that possible to parse data with this format or there is another method to do it .

this is my code :

```<code>$xml = simplexml_load_string($result);
$json = json_encode($xml);
$array = json_decode($json,TRUE);
$parsed= simplexml_load_string($result);
</code>```

i'm trying to convert it to json format

答:
When i was working with xml i am facing the same issue but i found this solution and it worked for me

Documentation :- https://github.com/rentpost/xml2array

OR

https://packagist.org/packages/verdant/xml2array

Use

```<code>    $xml = '<cas:serviceResponse xmlns:cas="http://www.yale.edu/tp/cas">
        <cas:authenticationSuccess>
            <cas:user>yassine458</cas:user>
        </cas:authenticationSuccess>
    </cas:serviceResponse>';

    $xml2array = XML2Array::createArray($xml);
    echo "```";
    print_r($xml2array);
    echo "```";
</code>```

Accessing "user"

```<code>    echo $xml2array['cas:serviceResponse']['cas:authenticationSuccess']['cas:user'];
</code>```

Result : -

```<code>    Array
    (
        [cas:serviceResponse] => Array
            (
                [cas:authenticationSuccess] => Array
                    (
                        [cas:user] => yassine458
                    )

            )

    )
</code>```

if you don't want cas: just replace it with "" in xml;

Tested sendbox

Body:
i'm trying to parse data in xml with simple_load_string function in php and it's return an empty data in the $parsed (data parsed) .

the data to parse is like :

<cas:serviceResponse xmlns:cas="http://www.yale.edu/tp/cas">
    <cas:authenticationSuccess>
        <cas:user>yassine458</cas:user>
    </cas:authenticationSuccess>
</cas:serviceResponse>

is that possible to parse data with this format or there is another method to do it .

this is my code :

$xml = simplexml_load_string($result);
$json = json_encode($xml);
$array = json_decode($json,TRUE);
$parsed= simplexml_load_string($result);

i'm trying to convert it to json format

Body:
When i was working with xml i am facing the same issue but i found this solution and it worked for me

Documentation :- https://github.com/rentpost/xml2array

OR

https://packagist.org/packages/verdant/xml2array

Use

    $xml = '<cas:serviceResponse xmlns:cas="http://www.yale.edu/tp/cas">
        <cas:authenticationSuccess>
            <cas:user>yassine458</cas:user>
        </cas:authenticationSuccess>
    </cas:serviceResponse>';

    $xml2array = XML2Array::createArray($xml);
    echo "<pre>";
    print_r($xml2array);
    echo "<pre>";

Accessing "user"

    echo $xml2array['cas:serviceResponse']['cas:authenticationSuccess']['cas:user'];

Result : -

    Array
    (
        [cas:serviceResponse] => Array
            (
                [cas:authenticationSuccess] => Array
                    (
                        [cas:user] => yassine458
                    )

            )

    )

if you don't want cas: just replace it with "" in xml;

Tested sendbox


问:
Using regex to filter a URL list
I'm trying to use regex to filter a list of site that doesn't include a specific word.

For example from the list below, i want to filter all sites with the word test and empty strings so the final output that I'll get is http://example.com. I tried to use ^((?!test).)* but that doesn't filter empty strings. Maybe there is a better way to filter them? Thanks.

```<code>http://test1.com
http://test2.com
*empty string*
http://example.com
</code>```

答:
You need to use a negative lookahead and .+ in your regex as this:

```<code>^(?!.*test).+
</code>```

RegEx Demo

Title: Using regex to filter a URL list

Body:
I'm trying to use regex to filter a list of site that doesn't include a specific word.

For example from the list below, i want to filter all sites with the word test and empty strings so the final output that I'll get is http://example.com. I tried to use ^((?!test).)* but that doesn't filter empty strings. Maybe there is a better way to filter them? Thanks.

http://test1.com
http://test2.com
*empty string*
http://example.com

Body:
You need to use a negative lookahead and .+ in your regex as this:

^(?!.*test).+

RegEx Demo


问:
SDK for .NET Forge Data Management search items API
Does anybody have already built an SDK for .NET, using the filters and find items calls for the Forge Data Management API?</p>

答:
Did you check the NuGet we have for Forge? https://www.nuget.org/packages/Autodesk.Forge/ </p>

<p>I'm not sure if it contains the calls you are requesting but you could use this to build it yourself. </p>

Body:
Did you check the NuGet we have for Forge? https://www.nuget.org/packages/Autodesk.Forge/

I'm not sure if it contains the calls you are requesting but you could use this to build it yourself.


问:
Java array initialization within argument list
How come the first call to someMethod doesn't compile without being explicit that it's String[]?

It's fine to use an array initializer to create a String[] array but you can't use it to pass an argument.  Are the curly braces used in some other fashion for passing arguments that derails how I'd expect this to behave?

```<code>public void someMethod(String[] arr){
    //do some magic
}

public void makeSomeMagic(){

    String[] arr = {"cat", "fish", "cow"};

    //Does not compile!
    someMethod({"cat", "fish", "cow"});

    //This compiles!
    someMethod(new String[]{"cat", "fish", "cow"});

    //This compiles!
    someMethod(arr);
}
</code>```

The compiler error is the following:

The method someMethod(String[]) in the type Moo is not applicable for the arguments (String, String, String)

答:
If you don't want to use explicit String[], use:

```<code>public void someMethod(String... arr){
    //do some magic
}
…
someMethod("cm", "applicant", "lead");
</code>```

The three periods after the final parameter's type indicate that the final argument may be passed as an array or as a sequence of arguments.

Read more.

Body:
How come the first call to someMethod doesn't compile without being explicit that it's String[]?

It's fine to use an array initializer to create a String[] array but you can't use it to pass an argument.  Are the curly braces used in some other fashion for passing arguments that derails how I'd expect this to behave?

public void someMethod(String[] arr){
    //do some magic
}

public void makeSomeMagic(){

    String[] arr = {"cat", "fish", "cow"};

    //Does not compile!
    someMethod({"cat", "fish", "cow"});

    //This compiles!
    someMethod(new String[]{"cat", "fish", "cow"});

    //This compiles!
    someMethod(arr);
}

The compiler error is the following:

The method someMethod(String[]) in the type Moo is not applicable for the arguments (String, String, String)

Body:
If you don't want to use explicit String[], use:

public void someMethod(String... arr){
    //do some magic
}
…
someMethod("cm", "applicant", "lead");

The three periods after the final parameter's type indicate that the final argument may be passed as an array or as a sequence of arguments.

Read more.


问:
Where can I get the original PCM data from the Android framework?
Where can I get the original pcm data from the Android framework?
I think I can get it from:

```<code>Write (const void * buffer, size_t userSize, bool blocking)
</code>```

in /framework/av/media/libmedia/AudioTrack.cpp

However, it differs from the pcm data in the file before streaming service and the pcm data obtained in write.

I think it is like re-sampling.

Where can I get original pcm data?

Note:

The sound source is a FLAC sound source.

The Android version is 6.0.1.

答:
You have better chance of tapping the pcm buffer at one layer below the android-framework layer - audio hal. Now that would be dependent on the hardware hence I can provide you with some probable examples:-

hardware/xxx/audio/hal/audio_hw.c (Where xxx is qcom in my case)

  in_read() --> pcm_read()

external/tinyalsa/pcm.c

  pcm_read()

Body:
Where can I get the original pcm data from the Android framework?
I think I can get it from:

Write (const void * buffer, size_t userSize, bool blocking)

in /framework/av/media/libmedia/AudioTrack.cpp

However, it differs from the pcm data in the file before streaming service and the pcm data obtained in write.

I think it is like re-sampling.

Where can I get original pcm data?

Note:

The sound source is a FLAC sound source.

The Android version is 6.0.1.


问:
Not able to clear cookie what ever I do using PHP
I have tried a few ways to clear my cookies on localhost. Whatever I do, I am unable to delete them in Chrome and Firefox in normal mode, but it is working fine in Chrome's Incognito and Firefox's Private Browsing modes.

Here is my code:

```<code>$name = 'keepsignin';

if (isset($_SERVER['HTTP_COOKIE'])){
   $cookies = explode(';', $_SERVER['HTTP_COOKIE']);
   foreach ($cookies as $cookie_id => $cookie_value){
       if($cookie_id === $name){
          self::set_cookie($cookie_id, $value, $expiry, $path, $domain);
       }
   }
}
</code>```

After clearing the cookie manually things work fine, but I am not able to delete cookies that already exist.

答: I would recommend iterating the $_COOKIE superglobal rather than parsing $_SERVER['HTTP_COOKIE'] yourself.

Body:
I have tried a few ways to clear my cookies on localhost. Whatever I do, I am unable to delete them in Chrome and Firefox in normal mode, but it is working fine in Chrome's Incognito and Firefox's Private Browsing modes.

Here is my code:

$name = 'keepsignin';

if (isset($_SERVER['HTTP_COOKIE'])){
   $cookies = explode(';', $_SERVER['HTTP_COOKIE']);
   foreach ($cookies as $cookie_id => $cookie_value){
       if($cookie_id === $name){
          self::set_cookie($cookie_id, $value, $expiry, $path, $domain);
       }
   }
}

After clearing the cookie manually things work fine, but I am not able to delete cookies that already exist.


问:
object references an unsaved transient instance - trouble saving new child / grandchild references
I'm having cascade save problem with hibernate and am not having much luck tracing the source code.

In short, I have a three level parent/child/grandchild relationship mapped and when I save a reference to 1 parent with 2 children and each child has a handful of grandchildren then first persist is successful and everyone gets the appropriate ids:

```<code>Parent (id:p1)
    child1 (id:parent,c1)
        grandchild (id:child1,g1)
        grandchild (id:child1,g2)
    child2 (id:parent,c2)
        grandchild (id:child2,g1)
        grandchild (id:child2,g2)
</code>```

If I then load the parent (eagerly) and add a new child with several of it's own new grand children, I get the unsaved transient error when I attempt to persist the changes via the parent object:

```<code>Parent (id:p1)
    child1 (id:parent,c1)
        grandchild1 (id:child1,g1)
        grandchild2 (id:child1,g2)
    child2 (id:parent,c2)
        grandchild3 (id:child2,g1)
        grandchild4 (id:child2,g2)
    child3 (id:<new>)
        grandchild5 (id:child3,<new>)
        grandchild6 (id:child3,<new>)
</code>```

This is the basic, JPA style, syntax I use to save the object both times:

rulesRepository.save(parent).

In the hibernate code I can see the code decides if the parent is transient and executes the appropriate save or merge methods.  The first pass performs a save, while the second calls merge.

Tracing the hibernate code I see where it's about to save a new grandchild, realizes it needs the parent's key (child3), and then tried to get the child's id fields. Only because the child is also new I get the unsaved transient error.

The question is why is hibernate unable to resolve child3's key (by inspecting it's parent) as it resolves the grandchild's id during a merge, when it's clearly able to do this for a save when the entire model is transient?

Adding to the possible problem is that the middle tier (child) is actually a JOINED subtype.  The grandchild objects are associated with all subtypes so are mapped to the discriminator class.

Here's what I have mapped:

Parent:

```<code>@Entity
@Transactional
@EntityListeners(AuditingEntityListener.class)
@Table(name="DS_EXTENDED_DATA_SOURCE")
public final class Rule {

    @Id
    @GeneratedValue(generator="IdentityProvider")
    @GenericGenerator(name="IdentityProvider", strategy="com.teradata.tac.domain.common.IdentityProvider")
    @Column(name="Extended_Data_Source_Id", nullable=false, length=MAX_ID_LENGTH, updatable=false, insertable=true)
    private String  extendedDataSourceId;

    @OneToMany(cascade=CascadeType.ALL, orphanRemoval=true, fetch=FetchType.EAGER, mappedBy="rule")
    @Fetch(FetchMode.SELECT)
    @OrderBy("Display_X_Position_Num,Display_Y_Position_Num,Extended_Data_Source_Id")
    private List<Node<?>> nodes = new ArrayList<>();
}
</code>```

Child - Discriminator:

```<code>@Entity
@IdClass(NodeId.class)
@Table(name="DS_XDS_NODE")
@Inheritance(strategy=InheritanceType.JOINED)
@DiscriminatorColumn(name="Xds_Node_Type_Cd")
public class Node<T extends Node<T>> extends BaseDomain<Node<T>> {

    @Id
    @GeneratedValue(generator="IdentityProvider")
    @GenericGenerator(name="IdentityProvider", strategy="com.teradata.tac.domain.common.IdentityProvider")
    @Column(name="Xds_Node_Id", nullable=false, length=MAX_ID_LENGTH, updatable=false, insertable=false)
    protected String xdsNodeId;

    @Column(name="Xds_Node_Type_Cd", nullable=false, insertable=false, updatable=false)
    protected short xdsNodeTypeCd;

    @Id
    @ManyToOne(fetch=FetchType.EAGER)
    @JoinColumn(name="Extended_Data_Source_Id", insertable=false, updatable=false, nullable=false)
    @ApiModelProperty(hidden=true)
    @JsonBackReference(value="rule")
    protected Rule rule;

    // Selected Columns
    @OneToMany(cascade=CascadeType.ALL, orphanRemoval=true, fetch=FetchType.EAGER, mappedBy="node")
    @Fetch(FetchMode.SELECT)
    @OrderBy("Display_Ord")
    protected List<SelectedColumn> selectedColumns = new ArrayList<>();
}
</code>```

Example Child-Subclass:

```<code>@Entity
@Table(name="DS_XDS_JOIN_NODE")
@DiscriminatorValue("60")
public class JoinNode extends Node<JoinNode> {

}
</code>```

Grandchild:

```<code>@Entity
@IdClass(SelectedColumnId.class)
@Table(name = "DS_XDS_SELECTED_COLUMN")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
public class SelectedColumn {

    @Id
    @GeneratedValue(generator = "IdentityProvider")
    @GenericGenerator(name = "IdentityProvider", strategy = "com.teradata.tac.domain.common.IdentityProvider")
    @Column(name = "Xds_Selected_Column_Id", nullable = false, length = MAX_ID_LENGTH, updatable = false, insertable = false)
    protected String xdsSelectedColumnId;

    @Id
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumns({
        @JoinColumn(name = "Extended_Data_Source_Id", insertable = false, updatable = false, nullable = false),
        @JoinColumn(name = "Xds_Node_Id", insertable = false, updatable = false, nullable = false) })
    protected Node<?> node;
}
</code>```

All of the IdClasses used have similar layouts:

```<code>public class NodeId {

    private Rule   rule;           // Parent object reference
    private String xdsNodeId;      // local instance id (not guaranteed to be unique)

    public NodeId() {}

    public NodeId(Rule rule, String xdsNodeId) {
        this.rule = rule;
        this.xdsNodeId = xdsNodeId;
    }

    public String getId() {
        return this.xdsNodeId;
    }

    public Rule getRule() {
        return this.rule;
    }
}
</code>```

I've omitted overloaded equals and hashcode methods but essentially they all match the key fields.

The best I've managed to trace the root cause to is this method: AbstractEntityPersister:4480

public boolean canExtractIdOutOfEntity() {

       return hasIdentifierProperty() || hasEmbeddedCompositeIdentifier() || hasIdentifierMapper();

     }

This is where hibernate (1.5.2.RELEASE) has determined that the grandchild being saved is transient and needs it's id to be pulled from it's parent (child3).  As it goes in search of the id it executes the function above and all of the reference methods return null, resulting in the call returning false.  At this point the exception is thrown

Any insight into what i might be doing wrong would be appreciated, and a solution would be very welcome.

Thanks,
Jason

答:
For the benefit of others, I'll answer my own question with how I managed to solve the problem.

The basic problem was that I was relying on the @ManyToOne mapping relationships to provide the parent ids into the child objects.  In doing so I wasn't directly mapping the parent id fields into the children.

While this might work for a two level hierarchy, what it appears to mean is that any subsequent levels below this see a dependency on the parent id in the 2nd level child, but don't see an explicit column to map to.  I feel like is a bug, but I'm not confident enough in my understanding to make that assumption.

Anyway, to solve the issue I performed the following three changes:

1) I mapped all parent @Id columns directly into each child (every level subsequently added more and more keys).  Only the field and @Column aspects were copied over.

2) The @ManyToOne parent mappings in each child were NOT marked as IDs

3) I added an @PrePersist mapping to each child to pull the parent id(s) from the @ManyToOne mapped parent object and copy the values into the mapped fields.

All along I felt like I needed to map the columns explicitly, but didn't know how I would get the ids from the parents populated.  Only when I put two and two together did I realize that a non-id @ManyToOne mapping combined with a @PrePersist could accomplish this.

I suspect @MapsId might have the same affect as the logic in the @PrePersist code block so will have to experiment, but for now... It works.

Hope this helps someone someday...

Body:
I'm having cascade save problem with hibernate and am not having much luck tracing the source code.

In short, I have a three level parent/child/grandchild relationship mapped and when I save a reference to 1 parent with 2 children and each child has a handful of grandchildren then first persist is successful and everyone gets the appropriate ids:

Parent (id:p1)
    child1 (id:parent,c1)
        grandchild (id:child1,g1)
        grandchild (id:child1,g2)
    child2 (id:parent,c2)
        grandchild (id:child2,g1)
        grandchild (id:child2,g2)

If I then load the parent (eagerly) and add a new child with several of it's own new grand children, I get the unsaved transient error when I attempt to persist the changes via the parent object:

Parent (id:p1)
    child1 (id:parent,c1)
        grandchild1 (id:child1,g1)
        grandchild2 (id:child1,g2)
    child2 (id:parent,c2)
        grandchild3 (id:child2,g1)
        grandchild4 (id:child2,g2)
    child3 (id:<new>)
        grandchild5 (id:child3,<new>)
        grandchild6 (id:child3,<new>)

This is the basic, JPA style, syntax I use to save the object both times:

rulesRepository.save(parent).

In the hibernate code I can see the code decides if the parent is transient and executes the appropriate save or merge methods.  The first pass performs a save, while the second calls merge.

Tracing the hibernate code I see where it's about to save a new grandchild, realizes it needs the parent's key (child3), and then tried to get the child's id fields. Only because the child is also new I get the unsaved transient error.

The question is why is hibernate unable to resolve child3's key (by inspecting it's parent) as it resolves the grandchild's id during a merge, when it's clearly able to do this for a save when the entire model is transient?

Adding to the possible problem is that the middle tier (child) is actually a JOINED subtype.  The grandchild objects are associated with all subtypes so are mapped to the discriminator class.

Here's what I have mapped:

Parent:

@Entity
@Transactional
@EntityListeners(AuditingEntityListener.class)
@Table(name="DS_EXTENDED_DATA_SOURCE")
public final class Rule {

    @Id
    @GeneratedValue(generator="IdentityProvider")
    @GenericGenerator(name="IdentityProvider", strategy="com.teradata.tac.domain.common.IdentityProvider")
    @Column(name="Extended_Data_Source_Id", nullable=false, length=MAX_ID_LENGTH, updatable=false, insertable=true)
    private String  extendedDataSourceId;

    @OneToMany(cascade=CascadeType.ALL, orphanRemoval=true, fetch=FetchType.EAGER, mappedBy="rule")
    @Fetch(FetchMode.SELECT)
    @OrderBy("Display_X_Position_Num,Display_Y_Position_Num,Extended_Data_Source_Id")
    private List<Node<?>> nodes = new ArrayList<>();
}

Child - Discriminator:

@Entity
@IdClass(NodeId.class)
@Table(name="DS_XDS_NODE")
@Inheritance(strategy=InheritanceType.JOINED)
@DiscriminatorColumn(name="Xds_Node_Type_Cd")
public class Node<T extends Node<T>> extends BaseDomain<Node<T>> {

    @Id
    @GeneratedValue(generator="IdentityProvider")
    @GenericGenerator(name="IdentityProvider", strategy="com.teradata.tac.domain.common.IdentityProvider")
    @Column(name="Xds_Node_Id", nullable=false, length=MAX_ID_LENGTH, updatable=false, insertable=false)
    protected String xdsNodeId;

    @Column(name="Xds_Node_Type_Cd", nullable=false, insertable=false, updatable=false)
    protected short xdsNodeTypeCd;

    @Id
    @ManyToOne(fetch=FetchType.EAGER)
    @JoinColumn(name="Extended_Data_Source_Id", insertable=false, updatable=false, nullable=false)
    @ApiModelProperty(hidden=true)
    @JsonBackReference(value="rule")
    protected Rule rule;

    // Selected Columns
    @OneToMany(cascade=CascadeType.ALL, orphanRemoval=true, fetch=FetchType.EAGER, mappedBy="node")
    @Fetch(FetchMode.SELECT)
    @OrderBy("Display_Ord")
    protected List<SelectedColumn> selectedColumns = new ArrayList<>();
}

Example Child-Subclass:

@Entity
@Table(name="DS_XDS_JOIN_NODE")
@DiscriminatorValue("60")
public class JoinNode extends Node<JoinNode> {

}

Grandchild:

@Entity
@IdClass(SelectedColumnId.class)
@Table(name = "DS_XDS_SELECTED_COLUMN")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
public class SelectedColumn {

    @Id
    @GeneratedValue(generator = "IdentityProvider")
    @GenericGenerator(name = "IdentityProvider", strategy = "com.teradata.tac.domain.common.IdentityProvider")
    @Column(name = "Xds_Selected_Column_Id", nullable = false, length = MAX_ID_LENGTH, updatable = false, insertable = false)
    protected String xdsSelectedColumnId;

    @Id
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumns({
        @JoinColumn(name = "Extended_Data_Source_Id", insertable = false, updatable = false, nullable = false),
        @JoinColumn(name = "Xds_Node_Id", insertable = false, updatable = false, nullable = false) })
    protected Node<?> node;
}

All of the IdClasses used have similar layouts:

public class NodeId {

    private Rule   rule;           // Parent object reference
    private String xdsNodeId;      // local instance id (not guaranteed to be unique)

    public NodeId() {}

    public NodeId(Rule rule, String xdsNodeId) {
        this.rule = rule;
        this.xdsNodeId = xdsNodeId;
    }

    public String getId() {
        return this.xdsNodeId;
    }

    public Rule getRule() {
        return this.rule;
    }
}

I've omitted overloaded equals and hashcode methods but essentially they all match the key fields.

The best I've managed to trace the root cause to is this method: AbstractEntityPersister:4480

public boolean canExtractIdOutOfEntity() {

       return hasIdentifierProperty() || hasEmbeddedCompositeIdentifier() || hasIdentifierMapper();

     }

This is where hibernate (1.5.2.RELEASE) has determined that the grandchild being saved is transient and needs it's id to be pulled from it's parent (child3).  As it goes in search of the id it executes the function above and all of the reference methods return null, resulting in the call returning false.  At this point the exception is thrown

Any insight into what i might be doing wrong would be appreciated, and a solution would be very welcome.

Thanks,
Jason


问:
Regex to find last token on a string
I was wondering if there is a way having this

```<code>var string = "foo::bar"
</code>```

To get the last part of the string: "bar" using just regex.

I was trying to do look-aheads but couldn't master them enough to do this.

--

UPDATE

Perhaps some examples will make the question clearer.

```<code>var st1 = "foo::bar::0"
match should be 0

var st2 = "foo::bar::0-3aab"
match should be 0-3aab

var st3 = "foo"
no match should be found
</code>```

答:
Simply,

```<code>/::(.+)$/
</code>```

You can't use lookaheads unless you know exactly how long a string you're trying to match. Fortunately, this isn't an issue, because you're only looking at the end of the string $.

Title: Regex to find last token on a string

Body:
I was wondering if there is a way having this

var string = "foo::bar"

To get the last part of the string: "bar" using just regex.

I was trying to do look-aheads but couldn't master them enough to do this.

--

UPDATE

Perhaps some examples will make the question clearer.

var st1 = "foo::bar::0"
match should be 0

var st2 = "foo::bar::0-3aab"
match should be 0-3aab

var st3 = "foo"
no match should be found

Body:
Simply,

/::(.+)$/

You can't use lookaheads unless you know exactly how long a string you're trying to match. Fortunately, this isn't an issue, because you're only looking at the end of the string $.


问:
Maven crashes when trying to compile a project "Error executing Maven."
I'm trying to compile a project that uses maven.

Running mvn compile results in the following error:

```<code>[ERROR] Error executing Maven.
[ERROR] java.lang.IllegalStateException: Unable to load cache item
[ERROR] Caused by: Unable to load cache item
[ERROR] Caused by: Could not initialize class com.google.inject.internal.cglib.core.$ReflectUtils
</code>```

This happens anywhere that I run this, it doesn't have to be in the project directory.

What am I doing wrong?

maven 3.3.9, ubuntu 17.04

Full output from mvn -X:

```<code>Apache Maven 3.3.9
Maven home: /usr/share/maven
Java version: 9-Ubuntu, vendor: Oracle Corporation
Java home: /usr/lib/jvm/java-9-openjdk-amd64
Default locale: en_GB, platform encoding: UTF-8
OS name: "linux", version: "4.10.0-21-generic", arch: "amd64", family: "unix"
[ERROR] Error executing Maven.
com.google.common.util.concurrent.UncheckedExecutionException: java.lang.IllegalStateException: Unable to load cache item
    at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2205)
    at com.google.common.cache.LocalCache.get(LocalCache.java:3951)
    at com.google.common.cache.LocalCache.getOrLoad(LocalCache.java:3955)
    at com.google.common.cache.LocalCache$LocalLoadingCache.get(LocalCache.java:4870)
    at com.google.common.cache.LocalCache$LocalLoadingCache.getUnchecked(LocalCache.java:4876)
    at com.google.inject.internal.FailableCache.get(FailableCache.java:48)
    at com.google.inject.internal.ConstructorInjectorStore.get(ConstructorInjectorStore.java:50)
    at com.google.inject.internal.ConstructorBindingImpl.initialize(ConstructorBindingImpl.java:137)
    at com.google.inject.internal.InjectorImpl.initializeBinding(InjectorImpl.java:533)
    at com.google.inject.internal.AbstractBindingProcessor$Processor$1.run(AbstractBindingProcessor.java:160)
    at com.google.inject.internal.ProcessedBindingData.initializeBindings(ProcessedBindingData.java:44)
    at com.google.inject.internal.InternalInjectorCreator.initializeStatically(InternalInjectorCreator.java:123)
    at com.google.inject.internal.InternalInjectorCreator.build(InternalInjectorCreator.java:107)
    at com.google.inject.Guice.createInjector(Guice.java:99)
    at com.google.inject.Guice.createInjector(Guice.java:73)
    at com.google.inject.Guice.createInjector(Guice.java:62)
    at org.codehaus.plexus.DefaultPlexusContainer.addPlexusInjector(DefaultPlexusContainer.java:481)
    at org.codehaus.plexus.DefaultPlexusContainer.<init>(DefaultPlexusContainer.java:206)
    at org.apache.maven.cli.MavenCli.container(MavenCli.java:545)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:281)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:199)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:547)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
Caused by: java.lang.IllegalStateException: Unable to load cache item
    at com.google.inject.internal.cglib.core.internal.$LoadingCache.createEntry(LoadingCache.java:79)
    at com.google.inject.internal.cglib.core.internal.$LoadingCache.get(LoadingCache.java:34)
    at com.google.inject.internal.cglib.core.$AbstractClassGenerator$ClassLoaderData.get(AbstractClassGenerator.java:116)
    at com.google.inject.internal.cglib.core.$AbstractClassGenerator.create(AbstractClassGenerator.java:291)
    at com.google.inject.internal.cglib.reflect.$FastClass$Generator.create(FastClass.java:65)
    at com.google.inject.internal.BytecodeGen.newFastClass(BytecodeGen.java:204)
    at com.google.inject.internal.DefaultConstructionProxyFactory.create(DefaultConstructionProxyFactory.java:55)
    at com.google.inject.internal.ProxyFactory.create(ProxyFactory.java:159)
    at com.google.inject.internal.ConstructorInjectorStore.createConstructor(ConstructorInjectorStore.java:90)
    at com.google.inject.internal.ConstructorInjectorStore.access$000(ConstructorInjectorStore.java:29)
    at com.google.inject.internal.ConstructorInjectorStore$1.create(ConstructorInjectorStore.java:37)
    at com.google.inject.internal.ConstructorInjectorStore$1.create(ConstructorInjectorStore.java:33)
    at com.google.inject.internal.FailableCache$1.load(FailableCache.java:37)
    at com.google.common.cache.LocalCache$LoadingValueReference.loadFuture(LocalCache.java:3540)
    at com.google.common.cache.LocalCache$Segment.loadSync(LocalCache.java:2321)
    at com.google.common.cache.LocalCache$Segment.lockedGetOrLoad(LocalCache.java:2284)
    at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2199)
    ... 28 more
Caused by: java.lang.NoClassDefFoundError: Could not initialize class com.google.inject.internal.cglib.core.$ReflectUtils
    at com.google.inject.internal.cglib.reflect.$FastClassEmitter.<init>(FastClassEmitter.java:67)
    at com.google.inject.internal.cglib.reflect.$FastClass$Generator.generateClass(FastClass.java:77)
    at com.google.inject.internal.cglib.core.$DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25)
    at com.google.inject.internal.cglib.core.$AbstractClassGenerator.generate(AbstractClassGenerator.java:329)
    at com.google.inject.internal.cglib.core.$AbstractClassGenerator$ClassLoaderData$3.apply(AbstractClassGenerator.java:93)
    at com.google.inject.internal.cglib.core.$AbstractClassGenerator$ClassLoaderData$3.apply(AbstractClassGenerator.java:91)
    at com.google.inject.internal.cglib.core.internal.$LoadingCache$2.call(LoadingCache.java:54)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at com.google.inject.internal.cglib.core.internal.$LoadingCache.createEntry(LoadingCache.java:61)
    ... 44 more
</code>```

答:
Looks like you are using Java 9.
Try switching to a stabler version of Java 8.

Installing Java 8 on Linux

E.g. using this tutorial How To Install Java with Apt-Get on Ubuntu 16.04

That's the easy option, you can always download one directly. But before bemoaning about such semantics do try the easy way to check if the solution works :) If it does work you can always do a complete uninstall, remove the ppa and get to work on the semantics.

Body:
I'm trying to compile a project that uses maven.

Running mvn compile results in the following error:

[ERROR] Error executing Maven.
[ERROR] java.lang.IllegalStateException: Unable to load cache item
[ERROR] Caused by: Unable to load cache item
[ERROR] Caused by: Could not initialize class com.google.inject.internal.cglib.core.$ReflectUtils

This happens anywhere that I run this, it doesn't have to be in the project directory.

What am I doing wrong?

maven 3.3.9, ubuntu 17.04

Full output from mvn -X:

Apache Maven 3.3.9
Maven home: /usr/share/maven
Java version: 9-Ubuntu, vendor: Oracle Corporation
Java home: /usr/lib/jvm/java-9-openjdk-amd64
Default locale: en_GB, platform encoding: UTF-8
OS name: "linux", version: "4.10.0-21-generic", arch: "amd64", family: "unix"
[ERROR] Error executing Maven.
com.google.common.util.concurrent.UncheckedExecutionException: java.lang.IllegalStateException: Unable to load cache item
    at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2205)
    at com.google.common.cache.LocalCache.get(LocalCache.java:3951)
    at com.google.common.cache.LocalCache.getOrLoad(LocalCache.java:3955)
    at com.google.common.cache.LocalCache$LocalLoadingCache.get(LocalCache.java:4870)
    at com.google.common.cache.LocalCache$LocalLoadingCache.getUnchecked(LocalCache.java:4876)
    at com.google.inject.internal.FailableCache.get(FailableCache.java:48)
    at com.google.inject.internal.ConstructorInjectorStore.get(ConstructorInjectorStore.java:50)
    at com.google.inject.internal.ConstructorBindingImpl.initialize(ConstructorBindingImpl.java:137)
    at com.google.inject.internal.InjectorImpl.initializeBinding(InjectorImpl.java:533)
    at com.google.inject.internal.AbstractBindingProcessor$Processor$1.run(AbstractBindingProcessor.java:160)
    at com.google.inject.internal.ProcessedBindingData.initializeBindings(ProcessedBindingData.java:44)
    at com.google.inject.internal.InternalInjectorCreator.initializeStatically(InternalInjectorCreator.java:123)
    at com.google.inject.internal.InternalInjectorCreator.build(InternalInjectorCreator.java:107)
    at com.google.inject.Guice.createInjector(Guice.java:99)
    at com.google.inject.Guice.createInjector(Guice.java:73)
    at com.google.inject.Guice.createInjector(Guice.java:62)
    at org.codehaus.plexus.DefaultPlexusContainer.addPlexusInjector(DefaultPlexusContainer.java:481)
    at org.codehaus.plexus.DefaultPlexusContainer.<init>(DefaultPlexusContainer.java:206)
    at org.apache.maven.cli.MavenCli.container(MavenCli.java:545)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:281)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:199)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:547)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
Caused by: java.lang.IllegalStateException: Unable to load cache item
    at com.google.inject.internal.cglib.core.internal.$LoadingCache.createEntry(LoadingCache.java:79)
    at com.google.inject.internal.cglib.core.internal.$LoadingCache.get(LoadingCache.java:34)
    at com.google.inject.internal.cglib.core.$AbstractClassGenerator$ClassLoaderData.get(AbstractClassGenerator.java:116)
    at com.google.inject.internal.cglib.core.$AbstractClassGenerator.create(AbstractClassGenerator.java:291)
    at com.google.inject.internal.cglib.reflect.$FastClass$Generator.create(FastClass.java:65)
    at com.google.inject.internal.BytecodeGen.newFastClass(BytecodeGen.java:204)
    at com.google.inject.internal.DefaultConstructionProxyFactory.create(DefaultConstructionProxyFactory.java:55)
    at com.google.inject.internal.ProxyFactory.create(ProxyFactory.java:159)
    at com.google.inject.internal.ConstructorInjectorStore.createConstructor(ConstructorInjectorStore.java:90)
    at com.google.inject.internal.ConstructorInjectorStore.access$000(ConstructorInjectorStore.java:29)
    at com.google.inject.internal.ConstructorInjectorStore$1.create(ConstructorInjectorStore.java:37)
    at com.google.inject.internal.ConstructorInjectorStore$1.create(ConstructorInjectorStore.java:33)
    at com.google.inject.internal.FailableCache$1.load(FailableCache.java:37)
    at com.google.common.cache.LocalCache$LoadingValueReference.loadFuture(LocalCache.java:3540)
    at com.google.common.cache.LocalCache$Segment.loadSync(LocalCache.java:2321)
    at com.google.common.cache.LocalCache$Segment.lockedGetOrLoad(LocalCache.java:2284)
    at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2199)
    ... 28 more
Caused by: java.lang.NoClassDefFoundError: Could not initialize class com.google.inject.internal.cglib.core.$ReflectUtils
    at com.google.inject.internal.cglib.reflect.$FastClassEmitter.<init>(FastClassEmitter.java:67)
    at com.google.inject.internal.cglib.reflect.$FastClass$Generator.generateClass(FastClass.java:77)
    at com.google.inject.internal.cglib.core.$DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25)
    at com.google.inject.internal.cglib.core.$AbstractClassGenerator.generate(AbstractClassGenerator.java:329)
    at com.google.inject.internal.cglib.core.$AbstractClassGenerator$ClassLoaderData$3.apply(AbstractClassGenerator.java:93)
    at com.google.inject.internal.cglib.core.$AbstractClassGenerator$ClassLoaderData$3.apply(AbstractClassGenerator.java:91)
    at com.google.inject.internal.cglib.core.internal.$LoadingCache$2.call(LoadingCache.java:54)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at com.google.inject.internal.cglib.core.internal.$LoadingCache.createEntry(LoadingCache.java:61)
    ... 44 more


问:
Append an image to a div using jquery?
Currently I want to append an image in a div that is being created in a for loop. The image will be appended to the #hiddenItems. I can't figure out how to place a div holding an image within this for loop. I want to place a pin icon on a description box that is created through this for loop.

Is there a way to do this? Is this question clear enough? Any help would be greatly appreciated.

```<code>for(var x = 0; x < itemIDs.length; x++) {
  console.log("x: " + x);
  $('<div class="' + itemClass1s[x] + ' hidden" id="hidden' + itemIDs[x] + '"  style="left: ' + itemXs[x] + 'px top:' + itemYs[x] + 'px;">' + itemContents[x] +'<img src="pin_red.png">' + '</div>').appendTo($('#hiddenItems'));
}
</code>```

答:
Solution

Use append() on $('#hiddenItems')...

```<code>for(var x = 0; x < itemIDs.length; x++) {
  var $element = $('<div/>');

  // Build the element this way for less headaches
  $element
    .addClass(itemClass1s[x] + ' hidden')
    .attr('id', 'hidden' + itemIDs[x])
    .css({left: itemXs[x] + 'px', top: itemYs[x] + 'px'})
    .html(itemContents[x]);

  $('#hiddenItems').append($element);
}
</code>```

Title: Append an image to a div using jquery?

Body:
Currently I want to append an image in a div that is being created in a for loop. The image will be appended to the #hiddenItems. I can't figure out how to place a div holding an image within this for loop. I want to place a pin icon on a description box that is created through this for loop.

Is there a way to do this? Is this question clear enough? Any help would be greatly appreciated.

for(var x = 0; x < itemIDs.length; x++) {
  console.log("x: " + x);
  $('
' + itemContents[x] +'' + '
').appendTo($('#hiddenItems'));
}

Body:
Solution

Use append() on $('#hiddenItems')...

for(var x = 0; x < itemIDs.length; x++) {
  var $element = $('<div/>');

  // Build the element this way for less headaches
  $element
    .addClass(itemClass1s[x] + ' hidden')
    .attr('id', 'hidden' + itemIDs[x])
    .css({left: itemXs[x] + 'px', top: itemYs[x] + 'px'})
    .html(itemContents[x]);

  $('#hiddenItems').append($element);
}


问:
Check when script has loaded
I am trying to call a function that, on the load of the script above it, will run some JavaScript.

```<code><script src="../Layout/jquery.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript" src="helperscript.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        var itemid = '1';
        if(itemid)
        {
            idselect(itemid);
        }
    })
</script>
</code>```

helperscript.js contains the function idselect.
When I load the page I get an error saying that 'idselect is undefined', even though it is in the above file. I suspect that this is due to helperscript not being fully loaded yet, but that is just a hunch.

Can anyone help me?

答:
I don't think your hunch is right, because this script tag:

```<code><script type="text/javascript" language="javascript" src="helperscript.js"></script>
</code>```

should block any other javascript from executing until helperscript.js is downloaded and executed.

Title: Check when script has loaded

Body:
I am trying to call a function that, on the load of the script above it, will run some JavaScript.

helperscript.js contains the function idselect.
When I load the page I get an error saying that 'idselect is undefined', even though it is in the above file. I suspect that this is due to helperscript not being fully loaded yet, but that is just a hunch.

Can anyone help me?

Body:
I don't think your hunch is right, because this script tag:

<script type="text/javascript" language="javascript" src="helperscript.js"></script>

should block any other javascript from executing until helperscript.js is downloaded and executed.


问:
Using a Correlated Subquery within a Left Join
I need a fresh set of eyes on this query. Without getting mega in depth in this code my problem is I'm doing a left join to pull from the TXP_Digital_Signatures (tds) table which stores signatures to the most current version of Treatment Plans (txp_master txp). What this code is doing is bringing back results where tds.signed is null (no signature) or marked N (No). This works, but what this report has done is show people what No's need to become yes, but that is leaving the No left behind, so if there is a more recent Yes then the No in that version of the tds.plan_id it is still pulling that plan_id where I no longer want it where the most recent signature status is a Y (yes), etc. The code snippet below added to the where statement works, but it hides all No's even if there is not a newer Y (yes).

```<code>tds.date = (select Max(date) from TXP_Digital_Signatures where tds.plan_id = txp.plan_id)
</code>```

Can anyone think of a way to either add a correlated subquery to the left join, so it only pulls the max(tds.date) for each tds.plan_id or how to rework my where statements so the no's without a newer yes and the null's still show up. I really don't want to redo the entire report as a grouped report if I can help it where I feel it'll break a ton of stuff on me and basically have me redoing this report from scratch. SQL 2008 R2

```<code>SELECT  case_status,
    CONVERT(CHAR(10), episode_open_date, 101)AS 'Enrolled' ,
    txp.patient_id,
    p.lname+', ' + p.fname AS 'Client',
    CONVERT(CHAR(10), txp.effective_date, 101)AS 'Effective',
    CONVERT(CHAR(10), next_review_date, 101)AS 'Review',
    txp.signed,
    (SELECT location_code FROM staff s WHERE s.staff_id = txp_coordinator_id) AS 'Clinic',
    (SELECT s.lname+', ' +s.fname FROM staff s WHERE s.staff_id = txp_coordinator_id) AS 'Coordinator',
    (SELECT s.lname+', ' +s.fname FROM staff s WHERE s.staff_id = ts.team_member_id ) AS 'Team',
    ts.signed,
    tds.signed as 'Patient Sig'
FROM txp_master txp join patient p ON p.patient_id = txp.patient_id and p.episode_id = txp.episode_id
    join txp_signature ts on ts.plan_id = txp.plan_id and ts.version_no = txp.version_no and ts.team_member_id <> txp.txp_coordinator_id
    left join TXP_Digital_Signatures tds on tds.plan_id = txp.plan_id

where p.case_status = 'A' and
txp.status <> 'er' and patient_signed_date is null
and tds.signed is null or tds.signed = 'N'
and txp.effective_date > '2016-12-31 00:00:00.000'
and tds.date = (select Max(date) from TXP_Digital_Signatures where tds.plan_id = txp.plan_id)

order by patient_id
</code>```

答:
Your query should work if you correct the sub-query, like this:

```<code>(select Max(date) from TXP_Digital_Signatures x where x.plan_id = tds.plan_id)
</code>```

currently, you are not filtering the sub-query TXP_Digital_Signatures.

One other thing to take note of is that you have a LEFT JOIN on TXP_Digital_Signatures tds yet you include it on the WHERE clause. This will convert it to an INNER JOIN. So decide on what join you require and change accordingly.

If you want results regardless of TXP_Digital_Signatures tds then move those conditions to the ON clause.

If you only want results based on TXP_Digital_Signatures tds then change to INNER JOIN

Body:
I need a fresh set of eyes on this query. Without getting mega in depth in this code my problem is I'm doing a left join to pull from the TXP_Digital_Signatures (tds) table which stores signatures to the most current version of Treatment Plans (txp_master txp). What this code is doing is bringing back results where tds.signed is null (no signature) or marked N (No). This works, but what this report has done is show people what No's need to become yes, but that is leaving the No left behind, so if there is a more recent Yes then the No in that version of the tds.plan_id it is still pulling that plan_id where I no longer want it where the most recent signature status is a Y (yes), etc. The code snippet below added to the where statement works, but it hides all No's even if there is not a newer Y (yes).

tds.date = (select Max(date) from TXP_Digital_Signatures where tds.plan_id = txp.plan_id)

Can anyone think of a way to either add a correlated subquery to the left join, so it only pulls the max(tds.date) for each tds.plan_id or how to rework my where statements so the no's without a newer yes and the null's still show up. I really don't want to redo the entire report as a grouped report if I can help it where I feel it'll break a ton of stuff on me and basically have me redoing this report from scratch. SQL 2008 R2

SELECT  case_status,
    CONVERT(CHAR(10), episode_open_date, 101)AS 'Enrolled' ,
    txp.patient_id,
    p.lname+', ' + p.fname AS 'Client',
    CONVERT(CHAR(10), txp.effective_date, 101)AS 'Effective',
    CONVERT(CHAR(10), next_review_date, 101)AS 'Review',
    txp.signed,
    (SELECT location_code FROM staff s WHERE s.staff_id = txp_coordinator_id) AS 'Clinic',
    (SELECT s.lname+', ' +s.fname FROM staff s WHERE s.staff_id = txp_coordinator_id) AS 'Coordinator',
    (SELECT s.lname+', ' +s.fname FROM staff s WHERE s.staff_id = ts.team_member_id ) AS 'Team',
    ts.signed,
    tds.signed as 'Patient Sig'
FROM txp_master txp join patient p ON p.patient_id = txp.patient_id and p.episode_id = txp.episode_id
    join txp_signature ts on ts.plan_id = txp.plan_id and ts.version_no = txp.version_no and ts.team_member_id <> txp.txp_coordinator_id
    left join TXP_Digital_Signatures tds on tds.plan_id = txp.plan_id

where p.case_status = 'A' and
txp.status <> 'er' and patient_signed_date is null
and tds.signed is null or tds.signed = 'N'
and txp.effective_date > '2016-12-31 00:00:00.000'
and tds.date = (select Max(date) from TXP_Digital_Signatures where tds.plan_id = txp.plan_id)

order by patient_id

Body:
Your query should work if you correct the sub-query, like this:

(select Max(date) from TXP_Digital_Signatures x where x.plan_id = tds.plan_id)

currently, you are not filtering the sub-query TXP_Digital_Signatures.

One other thing to take note of is that you have a LEFT JOIN on TXP_Digital_Signatures tds yet you include it on the WHERE clause. This will convert it to an INNER JOIN. So decide on what join you require and change accordingly.

If you want results regardless of TXP_Digital_Signatures tds then move those conditions to the ON clause.

If you only want results based on TXP_Digital_Signatures tds then change to INNER JOIN


问:
Gradle sync failed: Cause: https://downloads.gradle.org/distributions/gradle-2.3.2-all.zip
Platform and Plugin Updates in Android Studio and
I get the error:

```<code>Gradle sync failed: Cause: https://downloads.gradle.org/distributions/gradle-2.3.2-all.zip
</code>```

In File > Project structure > Project Gradle version: 2.3.2/ Android plugin version 2.3.2

My Gradle:

```<code>buildscript {
  repositories {
      jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:2.3.2'
}
}

 allprojects {
   repositories {
      jcenter()
   }
 }

task clean(type: Delete) {
  delete rootProject.buildDir
 }
</code>```

答: Make sure Android studio is able to reach the internet (for example if you're behind a proxy)</p>

Body:
Platform and Plugin Updates in Android Studio and
I get the error:

Gradle sync failed: Cause: https://downloads.gradle.org/distributions/gradle-2.3.2-all.zip

In File > Project structure > Project Gradle version: 2.3.2/ Android plugin version 2.3.2

My Gradle:

buildscript {
  repositories {
      jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:2.3.2'
}
}

 allprojects {
   repositories {
      jcenter()
   }
 }

task clean(type: Delete) {
  delete rootProject.buildDir
 }


问:
I need my dropbox not to change after refreshing or opening the page
I have a dropdown selection of two options. In stock or out of stock. I need the dropdown to stay the same as what was selected after someone leaves the page. Im sorry if there is a simple fix to this. I am new to web development and cant seem to get it to work. Everytime I refresh the page it goes to the default.

Thank you.

答:
HTML alone is great if you want to give everyone the same exact page.  But in order to do what you want to do, you will most likely need Javascript. If you haven't used Javascript before, Codecademy can teach you how to use it.

You will need 3 parts if you go with this method.

Part 1. Store a cookie with the drop-down selected value.

```<code><script>
    function storeCookie(name, value){
        document.cookie = name + "=" + value + "; expires=Fri, 31 Dec 9999 23:59:59 GMT";
    }
</code>```

Part 2. Check if a cookie already exists, and if it does then get the value that should be selected in your drop-down.

```<code>    function cookieExists(name){
        return -1 != document.cookie.indexOf( name + "=");
    }

    function getCookie(cname) {
        var name = cname + "=";
        var decodedCookie = decodeURIComponent(document.cookie);
        var ca = decodedCookie.split(';');
        for(var i = 0; i <ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') {
                c = c.substring(1);
            }
            if (c.indexOf(name) == 0) {
                return c.substring(name.length, c.length);
            }
        }
        return "";
    }
</code>```

Part 3. Tie it all together.

```<code>    function main(){
        var cookieName = "yourcookiename";
        if(cookieExists(cookieName){
            var value = getCookie(cookiename);

            //This is where you set the value in your drop-down with Javascript

        }
    }
</script>
</code>```

Furthermore, you should call storeCookie("yourcookiename", "yourcookievalue") when the webpage knows what value should stay selected, and call main() when the page loads.

Body:
HTML alone is great if you want to give everyone the same exact page.  But in order to do what you want to do, you will most likely need Javascript. If you haven't used Javascript before, Codecademy can teach you how to use it.

You will need 3 parts if you go with this method.

Part 1. Store a cookie with the drop-down selected value.

<script>
    function storeCookie(name, value){
        document.cookie = name + "=" + value + "; expires=Fri, 31 Dec 9999 23:59:59 GMT";
    }

Part 2. Check if a cookie already exists, and if it does then get the value that should be selected in your drop-down.

    function cookieExists(name){
        return -1 != document.cookie.indexOf( name + "=");
    }

    function getCookie(cname) {
        var name = cname + "=";
        var decodedCookie = decodeURIComponent(document.cookie);
        var ca = decodedCookie.split(';');
        for(var i = 0; i <ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') {
                c = c.substring(1);
            }
            if (c.indexOf(name) == 0) {
                return c.substring(name.length, c.length);
            }
        }
        return "";
    }

Part 3. Tie it all together.

    function main(){
        var cookieName = "yourcookiename";
        if(cookieExists(cookieName){
            var value = getCookie(cookiename);

            //This is where you set the value in your drop-down with Javascript

        }
    }
</script>

Furthermore, you should call storeCookie("yourcookiename", "yourcookievalue") when the webpage knows what value should stay selected, and call main() when the page loads.


问:
how to display the maximum value in the array?
```<code>int main()
{
   int numbers[30];
   int i;

   // making array of 30 random numbers under 100
   for(i=0;i<30;i++)
   {
       numbers[i] = rand() % 100;
   }

   // finding the greatest number in the array
   int greatest = 0;
   srand(1);
   for(i=0;i<30;i++)
   {
        if ( numbers[i] > greatest)
            greatest = numbers[i];
   }
</code>```

How do I then tell the program to display the max value of the array??
Thank you

答:
To display it in the basic console output:</p>

```<code>#include <iostream>
...
std::cout << "Max value is: " << greatest << "\n";
</code>```

Body:
int main()
{
   int numbers[30];
   int i;

   // making array of 30 random numbers under 100
   for(i=0;i<30;i++)
   {
       numbers[i] = rand() % 100;
   }

   // finding the greatest number in the array
   int greatest = 0;
   srand(1);
   for(i=0;i<30;i++)
   {
        if ( numbers[i] > greatest)
            greatest = numbers[i];
   }

How do I then tell the program to display the max value of the array??
Thank you

Body:
To display it in the basic console output:

#include <iostream>
...
std::cout << "Max value is: " << greatest << "\n";


问:
Inner join or other equal solution
I have good working  sql query but I need to select also atribute from table advert. I tried with inner join but it wasn't successful. So this query is ok but I need to select one atribute from table advert.</p>

```<code>SELECT D.* FROM  details
WHERE (D.name LIKE ?) AND  (D.id_advert IN(
   SELECT A.id
   FROM advert A
   WHERE A.status=1 and duration >= CURDATE()
   ORDER BY duration DESC ))
</code>```

答:
You can change the in (subquery ) in a proper inner join  and the is simple use the columns form table A</p>

```<code>SELECT D.* , A.*
FROM  details
INNER JOIN advert A ON D.id_advert = A.id
    AND  A.status=1
    AND duration >= CURDATE()
WHERE D.name LIKE ?
</code>```

Title: Inner join or other equal solution

Body:
I have good working  sql query but I need to select also atribute from table advert. I tried with inner join but it wasn't successful. So this query is ok but I need to select one atribute from table advert.

SELECT D.* FROM  details
WHERE (D.name LIKE ?) AND  (D.id_advert IN(
   SELECT A.id
   FROM advert A
   WHERE A.status=1 and duration >= CURDATE()
   ORDER BY duration DESC ))

Body:
You can change the in (subquery ) in a proper inner join  and the is simple use the columns form table A

SELECT D.* , A.*
FROM  details
INNER JOIN advert A ON D.id_advert = A.id
    AND  A.status=1
    AND duration >= CURDATE()
WHERE D.name LIKE ?