text:
Q: Proper LogoutRequest for Single Logout with ADFS IdP I'm successfully using OneLogin java-saml library for SAML SSO. But there are problems with SLO (Single Logout) with Active Directory Federation Service (ADFS). LogoutRequest created by the library is rejected by ADFS, while it is accepted by SimpleSAMLphp IdP. I pass both nameId and sessionIndex received from ADFS in Response at LogoutRequest creation.
Here are generated requests and received responses:
AuthNRequest:
<samlp:AuthnRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" ID="ONELOGIN_a80567d6-8957-482b-90e9-99d1b40ec8b1" Version="2.0" IssueInstant="2017-05-31T15:43:07Z" ProviderName="My Company Service Provider" Destination="https://wintest.mycompany.test/adfs/ls/" ProtocolBinding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" AssertionConsumerServiceURL="https://localhost:8443/builder/login_check_sso">
   <saml:Issuer>http://localhost:4568/sso/saml/metadata</saml:Issuer>
   <samlp:NameIDPolicy Format="urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified" AllowCreate="true" />
   <samlp:RequestedAuthnContext Comparison="exact">
      <saml:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:Password</saml:AuthnContextClassRef>
   </samlp:RequestedAuthnContext>
</samlp:AuthnRequest>

Response:
<samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" Consent="urn:oasis:names:tc:SAML:2.0:consent:unspecified" Destination="https://localhost:8443/builder/login_check_sso" ID="_f5ea3a59-92f9-4b22-aaf0-36ed392df051" InResponseTo="ONELOGIN_a80567d6-8957-482b-90e9-99d1b40ec8b1" IssueInstant="2017-05-31T15:43:10.158Z" Version="2.0">
   <Issuer xmlns="urn:oasis:names:tc:SAML:2.0:assertion">http://wintest.mycompany.test/adfs/services/trust</Issuer>
   <samlp:Status>
      <samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success" />
   </samlp:Status>
   <Assertion xmlns="urn:oasis:names:tc:SAML:2.0:assertion" ID="_6f6daef8-f0b5-4437-8e35-ae44ffc48cfe" IssueInstant="2017-05-31T15:43:10.158Z" Version="2.0">
      <Issuer>http://wintest.mycompany.test/adfs/services/trust</Issuer>
      <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
         <ds:SignedInfo>
            <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
            <ds:SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256" />
            <ds:Reference URI="#_6f6daef8-f0b5-4437-8e35-ae44ffc48cfe">
               <ds:Transforms>
                  <ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
                  <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
               </ds:Transforms>
               <ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256" />
               <ds:DigestValue>FNwbMonYZBBvTXSRbCWP7WxZgPZPSCcCFZozok9eRK4=</ds:DigestValue>
            </ds:Reference>
         </ds:SignedInfo>
         <ds:SignatureValue>fG1SIq3azZfBFQ+5YBBruuCQ03sLIHJ/YpK/AAOYkyJKXEZ5+SvNLgl+8/3a6Tk8mabZmwmawoJRf5UPb+fNtk+CeeWJ7kiUYcb2uvB4ic7Qd4qB+OgfqK0qVCkn9FWGEODLXA6v4tXWBZfSnzDrHEg7xLHrngesSnffY3uyQvH/rm4G2Vjd59LUeUtpJo2X5ZjVuk4sT5r21+UxpNU9LX8z7hXAZHhD1o4d2dqAs21tAGoid3p0RgNDy1WWGh1WSjFLHPDh220ZIchRFKveJE3R9M9nTKtOFESQsYc6TfmhJ5+Xm/j0VY7vvdhgguyq4MKzcPFK6tBL7I8KREck/Q==</ds:SignatureValue>
         <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
            <ds:X509Data>
               <ds:X509Certificate>MIIC4DCCAcigAwIBAgIQawxJmIMxo49K2BnRDsVfGDANBgkqhkiG9w0BAQsFADAsMSowKAYDVQQDEyFBREZTIFNpZ25pbmcgLSBXSU5URVNULlRvbmljLnRlc3QwHhcNMTcwNDIwMTIxNzUyWhcNMTgwNDIwMTIxNzUyWjAsMSowKAYDVQQDEyFBREZTIFNpZ25pbmcgLSBXSU5URVNULlRvbmljLnRlc3QwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDLUb41Ui5/ytBky/npDW5eV6gQhR7WZ3KJs/JEHEN+pbyNRYZXDY3zXIXcUDRMMdDUnewOisNN4iAMHDri/J7c2zBa05XReyQarnTBDPuiB2Hex6pxA486Mk5KqW8MGB2oWexCM+g1VXiaaSJEOHTb0V+GOhYHcDckNOfnBCKehqnYxqAmJp5WHzmU7IZWNb5P6tl92EfbdATA5fU29dkKVoYDGQJqdDDeLDI1mzxyMENce3v8JER9cnTW7zC2k4hD0TYafF3xphn2yLpnqnGEgbHDla9vdDMqX82+L4DSt4747kEdpc4+V9wwrkOnM5Cz5KKHyzQqzOS91CorCJI/AgMBAAEwDQYJKoZIhvcNAQELBQADggEBACdbOOfVkVNgaPzD+o60HHytR2MzbPcksKq1tZnS++nR+KM5Vo9FiH3LQ8BUulv8sEEq3ITeiLo92fMRySwiaftunLAAEYdBDTIbdi/fUJgLBoCVkDQvdtlRpnunr1KY7ILhKq4w9eQ0I5M5RDZlY2g3LEbyZpFknV1P1Ykx4d/re7BP42kt6JvY8SeA6TnfzgoQUGRBP7DAHiJ3J/HFPQZUvhqpKf6b5SEFMiSczx7wT1/CManyQ9rxOc0rycbGOcIuMNvxCipKWHsBwxvX021uXojhiSx37VxHWSNyWx5HA60GKkOolK8z2xZ/kdXmn5lxaRvH1P169Cd6HrjKzes=</ds:X509Certificate>
            </ds:X509Data>
         </KeyInfo>
      </ds:Signature>
      <Subject>
         <NameID>hamilton1@mycompany.test</NameID>
         <SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">
            <SubjectConfirmationData InResponseTo="ONELOGIN_a80567d6-8957-482b-90e9-99d1b40ec8b1" NotOnOrAfter="2017-05-31T15:48:10.158Z" Recipient="https://localhost:8443/builder/login_check_sso" />
         </SubjectConfirmation>
      </Subject>
      <Conditions NotBefore="2017-05-31T15:43:10.158Z" NotOnOrAfter="2017-05-31T16:43:10.158Z">
         <AudienceRestriction>
            <Audience>http://localhost:4568/sso/saml/metadata</Audience>
         </AudienceRestriction>
      </Conditions>
      <AttributeStatement>
         <Attribute Name="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress">
            <AttributeValue>hamilton@mycompany.com</AttributeValue>
         </Attribute>
      </AttributeStatement>
      <AuthnStatement AuthnInstant="2017-05-31T12:18:50.194Z" SessionIndex="_6f6daef8-f0b5-4437-8e35-ae44ffc48cfe">
         <AuthnContext>
            <AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:Password</AuthnContextClassRef>
         </AuthnContext>
      </AuthnStatement>
   </Assertion>
</samlp:Response>

LogoutRequest:
<samlp:LogoutRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" ID="ONELOGIN_947f5e64-8423-4464-b4b0-fa416dfe62a0" Version="2.0" IssueInstant="2017-05-31T15:43:18Z" Destination="https://wintest.mycompany.test/adfs/ls/">
   <saml:Issuer>http://localhost:4568/sso/saml/metadata</saml:Issuer>
   <saml:NameID Format="urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified">hamilton1@mycompany.test</saml:NameID>
   <samlp:SessionIndex>_6f6daef8-f0b5-4437-8e35-ae44ffc48cfe</samlp:SessionIndex>
</samlp:LogoutRequest>

LogoutResponse:
<samlp:LogoutResponse xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" ID="_1b3e8c81-2aba-45be-8fe6-54edda514d51" Version="2.0" IssueInstant="2017-05-31T15:43:24.808Z" Destination="https://localhost:8443/builder/logout_sso" Consent="urn:oasis:names:tc:SAML:2.0:consent:unspecified" InResponseTo="ONELOGIN_947f5e64-8423-4464-b4b0-fa416dfe62a0">
   <Issuer xmlns="urn:oasis:names:tc:SAML:2.0:assertion">http://wintest.mycompany.test/adfs/services/trust</Issuer>
   <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
      <ds:SignedInfo>
         <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
         <ds:SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256" />
         <ds:Reference URI="#_1b3e8c81-2aba-45be-8fe6-54edda514d51">
            <ds:Transforms>
               <ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
               <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
            </ds:Transforms>
            <ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256" />
            <ds:DigestValue>NDfLVWPkh2/UCEbLQ6V97OK2u4pajv3aLB9cPs5JkSc=</ds:DigestValue>
         </ds:Reference>
      </ds:SignedInfo>
      <ds:SignatureValue>M1JaIz/AeJAh1bUzAUBrljch9EVOVA6K3lzuFDWwF0LtmXgcMEZV9Htp9owq5MNcOZ/mymBrKmndz1EDwDxwOCLjpvp5QX42G23dUCyYAGfQXE1Dzub7dsaTSlMWnkbh6fMLk/j5/fcLEi8vwXMInQv6isVpxnbYI+4ayQWOzo9QpfJBaromDDqVwbmkoT8lhRo06n32OAi8CtaAS2rjNqJyPfcnLp3jMpfg5Qh3wiKYnT6VkMpXw5ddVASByKlqzIRiuItwJsqF4JDDj+f2qgSdq6PaTgYpu8xnbFXTdOvDeg0ZgetQrnaZ07+5xLFLGI73feAWPUFPXwMHQ2THXA==</ds:SignatureValue>
      <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
         <ds:X509Data>
            <ds:X509Certificate>MIIC4DCCAcigAwIBAgIQawxJmIMxo49K2BnRDsVfGDANBgkqhkiG9w0BAQsFADAsMSowKAYDVQQDEyFBREZTIFNpZ25pbmcgLSBXSU5URVNULlRvbmljLnRlc3QwHhcNMTcwNDIwMTIxNzUyWhcNMTgwNDIwMTIxNzUyWjAsMSowKAYDVQQDEyFBREZTIFNpZ25pbmcgLSBXSU5URVNULlRvbmljLnRlc3QwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDLUb41Ui5/ytBky/npDW5eV6gQhR7WZ3KJs/JEHEN+pbyNRYZXDY3zXIXcUDRMMdDUnewOisNN4iAMHDri/J7c2zBa05XReyQarnTBDPuiB2Hex6pxA486Mk5KqW8MGB2oWexCM+g1VXiaaSJEOHTb0V+GOhYHcDckNOfnBCKehqnYxqAmJp5WHzmU7IZWNb5P6tl92EfbdATA5fU29dkKVoYDGQJqdDDeLDI1mzxyMENce3v8JER9cnTW7zC2k4hD0TYafF3xphn2yLpnqnGEgbHDla9vdDMqX82+L4DSt4747kEdpc4+V9wwrkOnM5Cz5KKHyzQqzOS91CorCJI/AgMBAAEwDQYJKoZIhvcNAQELBQADggEBACdbOOfVkVNgaPzD+o60HHytR2MzbPcksKq1tZnS++nR+KM5Vo9FiH3LQ8BUulv8sEEq3ITeiLo92fMRySwiaftunLAAEYdBDTIbdi/fUJgLBoCVkDQvdtlRpnunr1KY7ILhKq4w9eQ0I5M5RDZlY2g3LEbyZpFknV1P1Ykx4d/re7BP42kt6JvY8SeA6TnfzgoQUGRBP7DAHiJ3J/HFPQZUvhqpKf6b5SEFMiSczx7wT1/CManyQ9rxOc0rycbGOcIuMNvxCipKWHsBwxvX021uXojhiSx37VxHWSNyWx5HA60GKkOolK8z2xZ/kdXmn5lxaRvH1P169Cd6HrjKzes=</ds:X509Certificate>
         </ds:X509Data>
      </KeyInfo>
   </ds:Signature>
   <samlp:Status>
      <samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Requester" />
   </samlp:Status>
</samlp:LogoutResponse>

The error appeared on ADFS is: The SAML Single Logout request does not correspond to the logged-in session participant. With extra error description:
User Action
Verify that the claim provider trust or the relying party trust configuration is up to date. If the name identifier in the request is different from the name identifier in the session only by NameQualifier or SPNameQualifier, check and correct the name identifier policy issuance rule using the AD FS Management snap-in.

What should be modified in LogoutRequest to make logout happen?

A: OK, the problem is solved.
As you can see in SAML Response I've posted NameID element doesn't have Format attribute:
<Subject>
     <NameID>hamilton1@mycompany.test</NameID>
     ...
</Subject>

So ADFS expects that Format attribute will be absent in LogouRequest too.
The following LogoutRequests results in successful logout:
<samlp:LogoutRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" ID="ONELOGIN_947f5e64-8423-4464-b4b0-fa416dfe62a0" Version="2.0" IssueInstant="2017-05-31T15:43:18Z" Destination="https://wintest.mycompany.test/adfs/ls/">
   <saml:Issuer>http://localhost:4568/sso/saml/metadata</saml:Issuer>
   <saml:NameID>hamilton1@mycompany.test</saml:NameID>
   <samlp:SessionIndex>_6f6daef8-f0b5-4437-8e35-ae44ffc48cfe</samlp:SessionIndex>
</samlp:LogoutRequest>

If I change Claim Issuing Policy to map Name ID to EmailAddress in ADFS with the following rules:
c:[Type == "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsaccountname", Issuer == "AD AUTHORITY"]
 => issue(store = "Active Directory", types = ("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress"), query = ";mail;{0}", param = c.Value);

c:[Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress"]
 => issue(Type = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", Issuer = c.Issuer, OriginalIssuer = c.OriginalIssuer, Value = c.Value, ValueType = c.ValueType, Properties["http://schemas.xmlsoap.org/ws/2005/05/identity/claimproperties/format"] = "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress");

I receive the following SAML Response:
<Subject>
     <NameID Format="urn:oasis:names:tc:SAML:2.0:nameid-format:emailAddress">hamilton1@mycompany.test</NameID>
     ...
</Subject>

And sending LogutRequest with <NameID Format="urn:oasis:names:tc:SAML:2.0:nameid-format:emailAddress"> logout happens successfully:
I'm using java-saml of version 2.0.1, so I'm doing the following in Java because LogoutRequest doesn't have a constructor accepting nameIdFormat: https://github.com/onelogin/java-saml/blob/v2.0.1/core/src/main/java/com/onelogin/saml2/logout/LogoutRequest.java:
LogoutRequest logoutRequest = new LogoutRequest(settings, null, nameId, sessionIndex);
String samlRequestXml = logoutRequest.getLogoutRequestXml();
samlRequestXml = samlRequestXml.replaceAll(" Format=\".+\"", "");

There plans to add LogoutRequest constructor accepting nameIdFormat as an argument. More details in https://github.com/onelogin/java-saml/issues/98.


text:
Q: Apache Spark Parquet: Cannot build an empty group I use Apache Spark 2.1.1 (used 2.1.0 and it was the same, switched today).
I have a dataset:
root
|-- muons: array (nullable = true)
|    |-- element: struct (containsNull = true)
|    |    |-- reco::Candidate: struct (nullable = true)
|    |    |-- qx3_: integer (nullable = true)
|    |    |-- pt_: float (nullable = true)
|    |    |-- eta_: float (nullable = true)
|    |    |-- phi_: float (nullable = true)
|    |    |-- mass_: float (nullable = true)
|    |    |-- vertex_: struct (nullable = true)
|    |    |    |-- fCoordinates: struct (nullable = true)
|    |    |    |    |-- fX: float (nullable = true)
|    |    |    |    |-- fY: float (nullable = true)
|    |    |    |    |-- fZ: float (nullable = true)
|    |    |-- pdgId_: integer (nullable = true)
|    |    |-- status_: integer (nullable = true)
|    |    |-- cachePolarFixed_: struct (nullable = true)
|    |    |-- cacheCartesianFixed_: struct (nullable = true)

As you can see, there are 3 empty structs in this schema. I know 100% that I can read/manipulate/do whatever. However, when I try writing to disk in parquet, I get the following Exception:
dsReduced.write.format("parquet").save(outputPathName):

java.lang.IllegalStateException: Cannot build an empty group
at org.apache.parquet.Preconditions.checkState(Preconditions.java:91)
at org.apache.parquet.schema.Types$BaseGroupBuilder.build(Types.java:622)
at org.apache.parquet.schema.Types$BaseGroupBuilder.build(Types.java:497)
at org.apache.parquet.schema.Types$Builder.named(Types.java:286)
at org.apache.spark.sql.execution.datasources.parquet.ParquetSchemaConverter.convertField(ParquetSchemaConverter.scala:535)
at org.apache.spark.sql.execution.datasources.parquet.ParquetSchemaConverter.convertField(ParquetSchemaConverter.scala:321)
at org.apache.spark.sql.execution.datasources.parquet.ParquetSchemaConverter$$anonfun$convertField$1.apply(ParquetSchemaConverter.scala:534)
at org.apache.spark.sql.execution.datasources.parquet.ParquetSchemaConverter$$anonfun$convertField$1.apply(ParquetSchemaConverter.scala:533)

So, basically I would like to understand if it's a bug or an intended behavior??? I also assume that it's related to the empty structs. Any help would be really appreciated!
Update: I've quickly created stripped version and that one works without any issues! Any insight would be really helpful!
VK

A: Parquet does not write empty structs:
for more info - see here https://issues.apache.org/jira/browse/SPARK-20593
VK

redpajama_set_name: RedPajamaStackExchange


text:
Q: Rating script wont update when multiple rate Hi i am currently making a rating script and i have a few problems
Right now the script "kinda" works -> http://xch07.wi2.sde.dk/sandbox/rating2/index.php
The problem is that if i open up 2 browsers and load image 1 on both browsers and rate the image on both the browsers the last query sent will override anything inbetween so basically in the end only 1 vote out of the 2 is submitted?.
Right now my db looks like this:
id - votes - rating
Currently i just increment the votes with 1 when a vote is submitted
And i raise the raiting with whatever value has ben voted
Could someone tell what i have to do to overcove this problem? and any other thoughs on my code are greatly appreciated :)
OBS: Does anyone have an idea of how i can check if a person has already voted a given image?
HTML

        <img id="imgSrc" src="assets/img/<?php echo $id ?>.png" class="carImg">

        <input id="imgValue" class="absolute displayn" type="radio" value="<?php echo $id ?>">
        <input id="imgVotes" class="absolute displayn" type="radio" value="<?php echo $votes ?>">
        <input id="imgRating" class="absolute displayn" type="radio" value="<?php echo $rating ?>">

        <form action="" method="post" class="flex flex-drr absolute bot0 left0">
            <input id="vote5" class="vote displayn" type="radio" name="vote" value="5">

            <input id="vote4" class="vote displayn" type="radio" name="vote" value="4">

            <input id="vote3" class="vote displayn"  type="radio" name="vote" value="3">

            <input id="vote2" class="vote displayn" type="radio" name="vote" value="2">

            <input id="vote1" class="vote displayn" type="radio" name="vote" value="1">

            <input type="submit" id="voteSubmit" class="displayn">
        </form>

Javascript/Ajax
var vote = document.getElementsByClassName('vote');
var voteL = vote.length;

for (let i = 0; i < voteL; i++) {
    vote[i].addEventListener('click', function () {

        let imgValue = document.getElementById("imgValue");
        let imgVotes = document.getElementById("imgVotes");
        let imgRating = document.getElementById("imgRating");

        let imgValueVal = imgValue.value;
        let imgVotesVal = imgVotes.value;
        let imgRatingVal = imgRating.value;

        let voteValue = vote[i].value;

        newImage(imgValueVal, imgVotesVal, imgRatingVal, voteValue);
    });
}

function newImage(id, votes, rating, voteValue) {
    var http = new XMLHttpRequest();
    var url = "pages/newImage.php";
    var params = "id=" + id + "&votes=" + votes + "&rating=" + rating + "&voteValue=" + voteValue;
    http.open("POST", url, true);

    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

    http.onreadystatechange = function () {//Call a function when the state changes.
        if (http.readyState == 4 && http.status == 200) {
            alert(http.responseText);

            var Data = JSON.parse(this.responseText);
            alert(Data.id);

            let imgSrc = document.getElementById('imgSrc');
            imgSrc.src = Data.imgSrc;

            let imgValue = document.getElementById('imgValue');
            imgValue.value = Data.id;

            let imgVotes = document.getElementById('imgVotes');
            imgVotes.value = Data.votes;
            console.log(Data.votes);

            let imgRating = document.getElementById('imgRating');
            imgRating.value = Data.rating;

        }
    }
    http.send(params);
}

THE PAGE AJAX REQUESTS
<?php

require_once '../includes/db.php';
require_once '../includes/functions.php';
$dbCon = dbCon();

//UPDATERE DATABASED
$id = $_POST['id'];
$votes = $_POST['votes'];
$rating = $_POST['rating'];
$voteValue = $_POST['voteValue'];

$votes++;
$rating = $rating + $voteValue;

$stmt = $dbCon->prepare("UPDATE rating SET
    votes = ?,
    rating = ? WHERE id = " . $id);
$stmt->bind_param('ii', $votes, $rating);
$stmt->execute();

//SENDER NY QUERY AFSTED
define("SQL", "SELECT * FROM rating ORDER BY rand() LIMIT 1");
$result = $dbCon->query(SQL);
$result = $result->fetch_object();

$id = $result->id;
$votes = $result->votes;
$rating = $result->rating;

$imgSrc = "assets/img/" . $id . ".png";
$arr = array('imgSrc' => $imgSrc, 'id' => $id, 'votes' => $votes, 'rating' => $rating);

echo json_encode($arr);

A: Why don't you replace the prepared statement with the following:
$stmt = $dbCon->prepare("UPDATE rating SET
    votes = ?,
    rating = rating + ? WHERE id = " . $id);

Held og lykke :-)

A: Just amend your query to add 1 to what is currently in the column like this
$stmt = $dbCon->prepare("UPDATE rating
                            SET votes = votes + 1,
                                rating = rating + ?
                        WHERE id = ?");
$stmt->bind_param('ii', $_POST['voteValue'], $_POST['id']);

A: By submitting the current rating/votes to your PHP script, you open yourself up to potentially updating your database based on stale information. You can UPDATE values in the database based on current row values, so the following would work as well:
$stmt = $dbCon->prepare("UPDATE rating SET votes = votes + 1, rating = rating + ? WHERE id = ?");
$stmt->bind_param('ii', $_POST['voteValue'], $_POST['id']);
$stmt->execute();


text:
Q: App Crashes when I click any button My app crashes whenever I click on any button. Any ideas what might be going wrong?
The error is I get is

Error - Could not find method openMastermind(View) in a parent or
  ancestor Context for android:onClick attribute defined on view class
  android.support.v7.widget.AppCompatButton with id 'button1'

public class MainActivity extends ListActivity {

ArrayList<Guess> guesses = new ArrayList<>();
ListView listview;
//ImageButton checkButton = (ImageButton) findViewById(R.id.checkButton);
private ImageView[] guessViews;
private Colour[] currentGuess = new Colour[4];
private int guessPosition = 0;
private Colour[] solution = new Colour[4];

public void openInstructions(View view) {
    Intent startInstructionsActivity = new Intent(this, Instructions.class);
    startActivity(startInstructionsActivity);
}

public void openMastermind(View view) {
    Intent startMastermindActivity = new Intent(this, mastermind1.class);
    startActivity(startMastermindActivity);
}

public void openHighscores(View view) {
    Intent startHighscoresActivity = new Intent(this, Highscores.class);
    startActivity(startHighscoresActivity);
}

public MainActivity() {

    Random r = new Random();
    for (int i = 0; i < solution.length; i++) {
        solution[i] = Colour.values()[r.nextInt(Colour.values().length)];
    }
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_mastermind1);

    final ListAdapter myAdapter = new CustomAdapter(this, guesses);
    listview = getListView();

    listview.setAdapter(myAdapter);

    guessViews = new ImageView[4];
    guessViews[0] = (ImageView) findViewById(R.id.guess1);
    guessViews[1] = (ImageView) findViewById(R.id.guess2);
    guessViews[2] = (ImageView) findViewById(R.id.guess3);
    guessViews[3] = (ImageView) findViewById(R.id.guess4);

And here is the xml file that contains the buttons.
**<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:background="#006699">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="Mastermind"
    android:id="@+id/textView"
    android:textColor="#000000"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/play_button"
    android:id="@+id/button1"
    android:layout_marginTop="70dp"
    android:layout_below="@+id/textView"
    android:layout_alignLeft="@+id/textView"
    android:onClick="openMastermind"
    android:background="#ffffff"
    android:layout_alignRight="@+id/textView" />

<Button

    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/instructions_button"
    android:id="@+id/button2"
    android:onClick="openInstructions"
    android:background="#ffffff"
    android:layout_centerVertical="true"
    android:layout_alignLeft="@+id/button1"
    android:layout_alignRight="@+id/button1" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/highscores_button"
    android:id="@+id/button3"
    android:layout_marginTop="45dp"
    android:onClick="openHighscores"
    android:layout_below="@+id/button2"
    android:layout_alignLeft="@+id/button2"
    android:textColor="#000000"
    android:background="#ffffff"
    android:layout_alignRight="@+id/button1" />

</RelativeLayout>

And here is the logcat of the crash
02-21 19:18:30.788 2506-2506/? E/AndroidRuntime: FATAL EXCEPTION: main
02-21 19:18:30.788 2506-2506/? E/AndroidRuntime: Process: com.example.i7678939.mastermind4, PID: 2506
02-21 19:18:30.788 2506-2506/? E/AndroidRuntime: java.lang.IllegalStateException: Could not find method openMastermind(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'button1'
02-21 19:18:30.788 2506-2506/? E/AndroidRuntime:     at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:307)
02-21 19:18:30.788 2506-2506/? E/AndroidRuntime:     at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:266)
02-21 19:18:30.788 2506-2506/? E/AndroidRuntime:     at android.view.View.performClick(View.java:5198)
02-21 19:18:30.788 2506-2506/? E/AndroidRuntime:     at android.view.View$PerformClick.run(View.java:21147)
02-21 19:18:30.788 2506-2506/? E/AndroidRuntime:     at android.os.Handler.handleCallback(Handler.java:739)
02-21 19:18:30.788 2506-2506/? E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:95)
02-21 19:18:30.788 2506-2506/? E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:148)
02-21 19:18:30.788 2506-2506/? E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5417)
02-21 19:18:30.788 2506-2506/? E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Native Method)
02-21 19:18:30.788 2506-2506/? E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
02-21 19:18:30.788 2506-2506/? E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
02-21 19:18:30.799 262-475/? W/ActivityManager:   Force finishing activity com.example.i7678939.mastermind4/.mastermind1
02-21 19:18:30.857 62-62/? E/EGL_emulation: tid 62: eglCreateSyncKHR(1243): error 0x3004 (EGL_BAD_ATTRIBUTE)
02-21 19:18:31.302 262-764/? I/OpenGLRenderer: Initialized EGL, version 1.4
02-21 19:18:31.390 262-764/? W/EGL_emulation: eglSurfaceAttrib not implemented
02-21 19:18:31.391 262-764/? W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xa3bd6b20, error=EGL_SUCCESS
02-21 19:18:31.498 262-280/? W/ActivityManager: Activity pause timeout for ActivityRecord{eb0a95a u0 com.example.i7678939.mastermind4/.mastermind1 t22 f}
02-21 19:18:31.857 262-272/? I/art: Background partial concurrent mark sweep GC freed 18556(1531KB) AllocSpace objects, 11(220KB) LOS objects, 33% free, 7MB/10MB, paused 6.822ms total 943.879ms
02-21 19:18:31.987 262-715/? W/art: Long monitor contention event with owner method=void com.android.server.am.ActivityStack$ActivityStackHandler.handleMessage(android.os.Message) from ActivityStack.java:283 waiters=0 for 110ms
02-21 19:18:32.317 690-770/? W/EGL_emulation: eglSurfaceAttrib not implemented
02-21 19:18:32.317 690-770/? W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xa3cddec0, error=EGL_SUCCESS
02-21 19:18:33.593 1002-1013/? I/art: Background partial concurrent mark sweep GC freed 28190(1126KB) AllocSpace objects, 0(0B) LOS objects, 39% free, 4MB/8MB, paused 2.418ms total 389.758ms
02-21 19:18:42.119 262-280/? W/ActivityManager: Activity destroy timeout for ActivityRecord{eb0a95a u0 com.example.i7678939.mastermind4/.mastermind1 t22 f}

A: Try to set Button's onClickListener in Activity class code, not in XML layout. That practice makes Your code better and more relieble. Better keep UI xml and application logic separeted.
Button mButton = (Button) findViewById(R.id.button1);
mButton.setOnClickListener(new View.OnClickListener() {
         public void onClick(View v) {
             openInstructions(v);
         }
     });


text:
Q: Apache + mod_ssl build not linking to my OpenSSL build I have spent some time searching online but none of what I found seems to help.
I'm running CentOS 6 64bit and would like to compile Apache with mod_ssl and need to link it to my own OpenSSL build (which is newer than the OS provided version).
OpenSSL 1.1.0i is configured with:
./config --prefix=/opt/openssl-1.1.0 --openssldir=/opt/openssl-1.1.0 shared

Apache 2.4 is configured with:
./configure --enable-layout=mycustomlayout \
    --prefix=/opt/httpd-2.4.34 \
    --exec-prefix=/opt/httpd-2.4.34 \
    --with-mpm=prefork \
    --enable-so \
    --enable-ssl \
    --with-ssl=/opt/openssl-1.1.0 \
    --enable-cgi \
    --enable-http2 \
    --enable-proxy-http2 \
    --with-included-apr

It appears to compile just fine but mod_ssl isn't aware of where OpenSSL 1.1.0 is installed:
[root@host .libs]# ldd ./mod_ssl.so | grep -iP 'ssl|crypto'
    libssl.so.1.1 => not found
    libcrypto.so.1.1 => not found

And so only works when you explicitly tell it where to look:
[root@host .libs]# export LD_LIBRARY_PATH=/opt/openssl-1.1.0/lib:$LD_LIBRARY_PATH
[root@host .libs]# ldd ./mod_ssl.so | grep -iP 'ssl|crypto'
    libssl.so.1.1 => /opt/openssl-1.1.0/lib/libssl.so.1.1 (0x00007f069149a000)
    libcrypto.so.1.1 => /opt/openssl-1.1.0/lib/libcrypto.so.1.1 (0x00007f069100a000)

Even building mod_ssl statically into httpd binary with --enable-mods-static=ssl doesn't help.
I tried --enable-ssl, --enable-ssl --enable-ssl-staticlib-deps, and --enable-ssl --enable-ssl-staticlib-deps --enable-mods-static=ssl and still the same result:
    libssl.so.1.1 => not found
    libcrypto.so.1.1 => not found

Also tried, without luck, setting these variables before ./configure:
export PKG_CONFIG_PATH=/opt/openssl-1.1.0/lib/pkgconfig:$PKG_CONFIG_PATH \
       LD_LIBRARY_PATH=/opt/openssl-1.1.0/lib:$LD_LIBRARY_PATH \
       LDFLAGS="-L/opt/openssl-1.1.0/lib"

I know I can just add to /etc/ld.so.conf.d to autoload the new OpenSSL library or adjust Apache's init script to add to LD_LIBRARY_PATH but I'd much prefer to have it working properly, have the program where to look for libssl.so / libcrypto.so, just like my PHP build:
[root@host php]# export PKG_CONFIG_PATH=/opt/openssl-1.1.0/lib/pkgconfig:$PKG_CONFIG_PATH \
       LD_LIBRARY_PATH=/opt/openssl-1.1.0/lib:$LD_LIBRARY_PATH \
       LDFLAGS="-L/opt/openssl-1.1.0/lib" \
       PHP_PREFIX=/opt/php-7.2.9 \
       EXTENSION_DIR=$PHP_PREFIX/usr/lib64/php/modules
[root@host php]# ./configure […] \
    --with-imap=shared \
    --with-imap-ssl \
    --with-openssl=shared \
    --with-openssl-dir=/opt/openssl-1.1.0/bin

[root@host php]# make
[root@host php]# unset PKG_CONFIG_PATH LD_LIBRARY_PATH LDFLAGS

[root@host modules]# ldd ./openssl.so | grep -iP 'ssl|crypto'
    libssl.so.1.1 => /opt/openssl-1.1.0/lib/libssl.so.1.1 (0x00007fc2220a6000)
    libcrypto.so.1.1 => /opt/openssl-1.1.0/lib/libcrypto.so.1.1 (0x00007fc221c17000)

What am I doing wrong? Could this be a bug?

A: Try adding the following to your LDFLAGS env variable:
-Bstatic -lssl -lcrypto

Also, make sure that you don't have any .so file on your openssl libdir, only the static .a ones. This ideally can be done by passing the no-shared parameter to openssl configure.
I am still unsure why sometimes the linker still prefers the shared version if it's present, even when we explicitly require the static ones, but probably it has to do with the way the ./configure script from httpd is handling library dependency.
While a patch on the configure script would probably be cleaner, just not having .so files seems to be enough for the linker to pick up the static version instead.


text:
Q: Center a UI element in Android I am looking for a way to center a UI element in android. Specifically the ImageView. Since I know the image I will be displaying isn't as wide as the screen I need to center it! Any ideas on how to do this?

A: If you want to center an imageView in the layout , use layout_gravity , (if its linear layout)
If you are talking about an image inside the imageView , use android:scaleType in xml of imageView

A: You can position the imageview within a relative layout. Set the layout properties for your image using these:
android:layout_centerInParent="true"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"


text:
Q: In Magento, is there a way to remove attribute from configurable product after already created? In Magento, I have have a bunch of configurable products already created and now have a client that has changed their mind and wants to remove one of the attributes.  I'm having a hard time figuring out how to do this b/c I keep getting an error message saying:

This attribute is used in configurable
  products. You cannot remove it from
  the attribute set.

I have tried going into the attribute and changing Use to Create Configurable Product from "yes" to "no", but that didn't seem to do anything when trying to remove attribute from existing products

A: It seems like you're trying to remove the attribute from the attribute set first, but you need to remove it from the configurable products, then the attribute set.  Open each configurable product, go to the Associated Products tab and remove the attribute (and linked products) that is not required.  Save each product and then try removing the attribute from the set.

A: To remove one super product attribute (as they are called) from all configurable products, you could execute this SQL query in the database:
DELETE FROM catalog_product_super_attribute
WHERE attribute_id = <id>

The table catalog_product_super_attribute links products to super product attributes. You can add and remove attributes to created configurable products there.

A: Simply use phpmyadmin and connect to your database.
Look for the eav_attribute table.
Delete the attribute you want.

A: may be this could help:
http://www.magentocommerce.com/boards/viewthread/6059/#t327478

A: Unfortunately, this is not possible from the standard Magento backend.
As such, you have to look at SQL solutions (I'm not familair with these).

A: Building on Christian Davén's answer, you could use the following to delete based on the attribute_code name instead of the attribute_id itself, just to be sure that you are referencing the right ID:
DELETE FROM `catalog_product_super_attribute`
WHERE `attribute_id` IN (
    SELECT `attribute_id` FROM `eav_attribute`
    WHERE `attribute_code` = "attribute"
)


text:
Q: Removing a num from a string in a list of numbers An example like:
print("1.", get_list_nums_without_9([589775, 677017, 34439, 48731548,     782295632, 181967909]))
print("2.", get_list_nums_without_9([6162, 29657355, 5485406, 422862350, 74452, 480506, 2881]))
print("3.", get_list_nums_without_9([292069010, 73980, 8980155, 921545108, 75841309, 6899644]))
print("4.", get_list_nums_without_9([]))

nums = [292069010, 73980, 8980155, 21545108, 7584130, 688644, 644908219, 44281, 3259, 8527361, 2816279, 985462264, 904259, 3869, 609436333, 36915, 83705, 405576, 4333000, 79386997]
print("5.", get_list_nums_without_9(nums))

I'm trying to get number list without 9. If the list is empty or if all of the numbers in the list contain the digit 9, the function should return an empty list. I tried the function below, it doesn't work.
def get_list_nums_without_9(a_list):
    j=0
    for i in a_list:
    a_list[j]=i.rstrip(9)
    j+=1
    return a_list

expected:
1. [677017, 48731548]
2. [6162, 5485406, 422862350, 74452, 480506, 2881]
3. []
4. []
5. [21545108, 7584130, 688644, 44281, 8527361, 83705, 405576, 4333000]

A: your lists contain integers. To remove the ones containing 9 the best way is to test if 9 belongs to the number as string and rebuild the output using a list comprehension with a conditional.
(Besides, rstrip removes the trailing chars of a string. Not suitable at all for your problem)
def get_list_nums_without_9(a_list):
    return [x for x in a_list if "9" not in str(x)]

testing with your data:
>>> numbers = [
...    [589775, 677017, 34439, 48731548, 782295632, 181967909],
...    [6162, 29657355, 5485406, 422862350, 74452, 480506, 2881],
...    [292069010, 73980, 8980155, 921545108, 75841309, 6899644],
...    [],
...    [292069010, 73980, 8980155, 21545108, 7584130, 688644, 644908219,
...     44281, 3259, 8527361, 2816279, 985462264, 904259, 3869, 609436333,
...     36915, 83705, 405576, 4333000, 79386997]
... ]

>>> for i, l in enumerate(numbers, 1):
...    print("{}. {}".format(i, get_list_nums_without_9(l)))
1. [677017, 48731548]
2. [6162, 5485406, 422862350, 74452, 480506, 2881]
3. []
4. []
5. [21545108, 7584130, 688644, 44281, 8527361, 83705, 405576, 4333000]

A: You don't want to replace anything in the list, you want to generate a new list based on what you detect in the old list:
def get_list_nums_without_9(numbers):
    sans_9 = []

    for number in numbers:
        if '9' not in str(number):
            sans_9.append(number)

    return sans_9

This will get you an empty list if there are no valid numbers.


text:
Q: In C#, if I have generic objects, how can I generically specify getting and setting fields on those objects? I have two very similiar functions:
        public Dictionary<string, T> UpdateSuccessProperties<T, TU>(Dictionary<string, T> oldSObjectByAlternativeIds, List<TU> updatedSObjects)
        where TU : T
        where T : AlternativeIdentifiable {
            updatedSObjects.ForEach((updatedSObject) => {
                    if (oldSObjectByAlternativeIds.TryGetValue(updatedSObject.GetAlternativeId(), out T oldSObject)) {
                        oldSObject.SalesforceId = updatedSObject.SalesforceId;
                    }
                });

            return oldSObjectByAlternativeIds;
        }

        public Dictionary<string, T> UpdateFailureProperties<T, TU>(Dictionary<string, T> oldSObjectByAlternativeIds, List<TU> updatedSObjects)
        where TU : T
        where T : AlternativeIdentifiable {
            updatedSObjects.ForEach((updatedSObject) => {
                    if (oldSObjectByAlternativeIds.TryGetValue(updatedSObject.GetAlternativeId(), out T oldSObject)) {
                        oldSObject.SalesforceError = updatedSObject.SalesforceError;
                    }
                });

            return oldSObjectByAlternativeIds;
        }

It will be noticed there are only 3 differences other than the method name:

*

*The very end of the url

*The property on oldSObject of type T which will receive a new value.

*The property on updatedSObjectof type TU which will supply the old value.

Is there some way I can consolidate these into something like this (pseudocode, doesn't work):
        public Dictionary<string, T> UpdateProperties<T, TU>(Dictionary<string, T> oldSObjectByAlternativeIds, List<TU> updatedSObjects, string receiverField, string supplierField)
        where TU : T
        where T : AlternativeIdentifiable {
            updatedSObjects.ForEach((updatedSObject) => {
                    if (oldSObjectByAlternativeIds.TryGetValue(updatedSObject.GetAlternativeId(), out T oldSObject)) {
                        oldSObject.set(receiverField, updatedSObject.get(supplierField));
                    }
                });

            return oldSObjectByAlternativeIds;
        }

?
The last two parameters needn't be strings; I'd actually prefer something typesafe.

A: Why not use Action<T, TU>, which could be: (oldSObject, updatedSObject) => oldSObject.SalesforceError = updatedSObject.SalesforceError:
public Dictionary<string, T> UpdateFailureProperties<T, TU>(Dictionary<string, T> oldSObjectByAlternativeIds, List<TU> updatedSObjects, Action<T, TU> callback)
    where TU : T
    where T : AlternativeIdentifiable
{
    updatedSObjects.Get(url, context.token)
        .FromCsv<List<TU>>()
        .ForEach((updatedSObject) =>
        {
            if (oldSObjectByAlternativeIds.TryGetValue(updatedSObject.GetAlternativeId(), out T oldSObject))
            {
                callback(oldSObject, updatedSObject);
            }
        });

    return oldSObjectByAlternativeIds;
}


text:
Q: Illegal character in javascript string parameter coming from SQL I'm maintaining an asp.net rest api where SQL data is loaded trough stored procedures and converted to rest.
On the web page I have an html element with an onclick attribute passing in the content of a result as a parameter. This works fine for almost all occurrences, but one gives an Uncaught SyntaxError: Unexpected token ILLEGAL in the chrome console.
I'm expecting that this character in the string is the issue:
↵

I just can't find out what character I need to replace in C# to remove this from the string. And I don't have a good environment to test or debug this.
Ps altering the stored procedure in SQL is not an option.
-- update --
I can't give the exact values as this is a bit confidential, but this is returned form the rest api when I inspect it with chrome (the result of the api call in the network tab):
21.12.15 xxx xxx xxx
↵
↵[xxx 13-01-2016] gebeld, gesproken met xxx : hij heeft met xxx besproken dat

I have an info icon with an onclick event passing in the string above (PayComment) as parameter. {{PayComment}} is replaced by handlebars with the string above.
i

I've set a debugger on the first line of the javascript function but it never reaches that line.
function GetInvoicePayComment(Comment) {
//
}

-- update 2 --
With the discussions here I thought I needed to check the source html as handlebars replaces the {{PayComment}} with the value. The result looks like this:

I'm guessing the newline here is the issue and not the characters.

A: you can eleminate return character in str string like that:
str.replace("↵", "");

or you can preferably replace it with new line chars like that:
str.replace("↵", "\n");
str.replace("↵", "
");

A: I've solved it by removing the newline in the api:
PayComment = item.PayComment.Replace(Environment.NewLine, "")


text:
Q: Undefined javascript function in MVC view I have a simple javascript function
function SayTest() {
    alert("test");
}

I include the javascript file in my MVC 4 view
<script type="javascript" src="~/Scripts/MyScripts/MyScript.js"></script>

and call the SayTest function from within my view
<script type="text/javascript">
    $(document).ready(function () {
        $("#myBtn").click(function () {
            SayTest();
        });
    });
</script>

I'm getting an undefined function error. This is driving me nuts. If the js file was included and the function is define, why do I get an undefined function error?

A: Try using :
<script type="text/javascript" src="~/Scripts/MyScripts/MyScript.js"></script>

A: You probably need to include jQuery into your View page:
<script type="text/javascript" src="~/Scripts/jquery.min.js"></script>

Make sure that's before any code that calls $().
(Note: You might have to change the exact filename to match what's in your project).


text:
Q: SOAPExtension methods not working According to the following blog post I have done Everything. Extend the SOAP extension class and had the Config binding. Still my soap extension methods are not calling. I have put a break point and checked. Here is the Sample code. TraceExt there are more overridden methods.
Blog

 public class TraceExt : SoapExtension
    {
        Stream oldStream;
        Stream newStream;
        string filename;

        // Save the Stream representing the SOAP request or SOAP response into
        // a local memory buffer.
        public override Stream ChainStream(Stream stream)
        {
        }
    }

 <system.web>
    <webServices>
      <soapExtensionTypes>
        <add type="WindowsFormSOAP.TraceExt, WindowsFormSOAP" group="High" priority="0"/>
      </soapExtensionTypes>
    </webServices>
  </system.web>

A: I just found an answer for this problem. When you add a web service reference you must have to add it as  the "Web Service Reference" as in .net 2.0. If you add the reference as "Add Service Reference" a new way of adding reference, the SOAP extension will not work.
Way to do :
Right Click on Reference Folder -> Add Service Reference - > Click on Advance Button -> Add Web Reference


text:
Q: Unable to get Error message for HTTP request in Groovy through NiFi Below is the code which I have written in Groovy
def flowFile = session.get()

def postResult=''
def url = new URL("https://instrument-api.systems.uk.hsbc/gbm/ts/financial-instrument/v1/exchange-calendars?calendarCode=Hns")

HttpURLConnection connection = (HttpURLConnection) url.openConnection()
connection.setRequestMethod("GET")
//connection.setConnectTimeout(10000)
connection.connect()

rMsg = connection.getResponseMessage()
rCode= connection.getResponseCode()

flowFile = session.putAttribute(flowFile, 'api_response_code', rCode.toString())
flowFile = session.putAttribute(flowFile, 'api_response_message', rMsg)

if (rCode == 200) {
    flowFile = session.write(flowFile, {outputStream ->
    outputStream.write(connection.content.getBytes())
    } as OutputStreamCallback)
    connection.disconnect();
    session.transfer(flowFile,REL_SUCCESS)
} else {
    flowFile = session.putAttribute(flowFile, 'api_response_error', connection.getErrorStream().toString())
    flowFile = session.putAttribute(flowFile, 'api_response_message', connection.getInputStream())
    session.transfer(flowFile,REL_FAILURE)
}

When I run this via postman, it gives me 500 response code with the following in Body:
  "timestamp": "2021-01-15T10:47:54.938+0000",
  "status": 500,
  "error": "Internal Server Error",
  "message": "JwtTokenMissingException: No JWT token found in request headers",
  "path": "/xxx/xx/xxxxxxxxx/v1/exchange-caxxxxx"
}

But I am not able to get this body from my groovy script. If I try using connection.getInputStream() or connection.content.getBytes() it returns me null pointer exception.


text:
Q: Python NLTK collocation for roman numerals As there is a collocation for numbers in nltk such as ('RS', '##number##')
I'm wondering if there is such a specifier for Roman numerals which I want to use for something like this: ('volume', '##roman number##')
If there is no way to do such a thing, it would be helpful if there was a viable way to convert Roman numerals to decimal for sentence segmentation, and then after segmentation convert the text back to the original Roman numerals.


text:
Q: C++ override error for signatures of const int and int& I am compiling a C++ program by GCC 7.5.0, but it complained about ambiguous override functions bool ReadRegister(const uint16_t, const uint16_t) and bool ReadRegister(const uint16_t, uint16_t &). The const uint16_t and uint16_t & are completely different data types, am I wrong about it?

A: Your code is wrong.When you call the readRegister function, the compiler doesn't know which one you're calling,it will report 'call of overload is ambiguous' error.
In C++,Reference Binding does not have a const qualified conversion.Direct reference bindings compare to pass-values only at the Exact Match  and Derived to Base Conversion.more details in https://en.cppreference.com/w/cpp/language/overload_resolution
For example:
void f(int (*)() noexcept); // #1
void f(int (*)()); // #2

void g(int (&)() noexcept); // #3
void g(int (&)()); // #4

#1 has a higher priority than #2, while #3 and #4 are equal.So just memorize the rules.


text:
Q: Dynamic expression: How compiler compiles and what lamda expression to expect I am following this question Returning a nested generic Expression<Func<T, bool>>
And I am interested in how compiler reads and compile it to
for example
ParameterExpression pe = Expression.Parameter(typeof(T), "p");
PropertyInfo pi = typeof(T).GetProperty(prop);
MemberExpression me = Expression.MakeMemberAccess(pe, pi);
ConstantExpression ce = Expression.Constant(val);
BinaryExpression be = Expression.Equal(me, ce);
return Expression.Lambda<Func<T, bool>>(be, pe);

Update Also need explanation of each method
My question is what lamda expression should I expect after it compiles?

A: See the comments in the code below.
using System;
using System.Linq.Expressions;
using System.Reflection;

namespace ConsoleApp5
{
    class Program
    {
        static void Main(string[] args)
        {
            var myType = new MyType();
            myType.p = "Some Value";

            var compareMethod = DoWork<MyType>("Some Value", "p");
            var isEqual = compareMethod(myType);
        }

        public static Func<T, bool>  DoWork<T>(object val, string prop)
        {
            //The code below will construct an expression like 'p => p.prop == value'
            //Creates the parameter part of an expression. So the 'p =>' part of the expression.
            ParameterExpression pe = Expression.Parameter(typeof(T), "p");
            //Get access to the property info, like the getter and setter.
            PropertyInfo pi = typeof(T).GetProperty(prop);
            // // Constructs the part of the expression where the member is referenced, so the 'p.prop' part.
            MemberExpression me = Expression.MakeMemberAccess(pe, pi);
            //Creates the constant part of the expression, the 'value' part.
            ConstantExpression ce = Expression.Constant(val);
            //creates the comparison part '==' of the expression.
            //So this requires the left and right side of 'left == right'
            //Which is the property and the constant value.
            //So 'p.prop == value'
            BinaryExpression be = Expression.Equal(me, ce);
            //Puts the 'p => ' and 'p.prop == value' parts of the expression together to form the
            //complete lambda
            //Compile it to have an executable method according to the same signature, as
            //specified with Func<T, bool>, so you put a class in of type T and
            //the 'p.prop == value' is evaluated, and the result is returned.
            return Expression.Lambda<Func<T, bool>>(be, pe).Compile();
        }
    }

    public class MyType
    {
        public string p { get; set; }
    }
}

That said, I think it is a complex way of only comparing. The usage case you have in mind may justify it. Are you working with LINQ-to-SQL or so that you have to work with expressions? In most cases from my epxerience, you can solve this with Funcs and interfaces, maybe in combination with a wrapper class in case of 3rd party classes. The code itself probably creates some in memory MSIL, which is then compiled in memory to native code using the Just-In-Time compiler of the CLR, where the allocation of the memory is marked as executable. I do not have detailed knowledge of how that works, this is just a guess. For more information on how memory allocation can be marked for different purposes see Memory Protection Constants.


text:
Q: mPDF nested list styling I am exporting tablular data to a PDF file, and within one of the cells is/can be a list of items, with each item itself potentially having a child list.
e.g.:

Parent Item text

Child Item text

...

Styling is minimal.
Parent list:
ul.parent-list {
    /*list-style: disc outside;*/
    list-style-type: disc; // just trying verbose styling
    list-style-position: outside;
}
.parent-list > li {
    margin-top: 5px;
}
.parent-list > li.first {
    margin-top: 0;
}
ul.child-list {
    /*list-style: circle outside;*/
    list-style-type: circle;
    list-style-position: outside;
    margin-top: 0.5em;
}

The CSS is fed to mPDF via a separate stylesheet, although I have also tried to resolve this using inline styles.
What I want to appear is typical list styling, with list items padded and the list furniture outside:

What I'm getting is this:

Is there an issue with nesting lists within mPDF? Their documentation does not mention any issues with lists at all...

A: mPDF doesn't support block level elements within tables.
Styling must be achieved via inline styles on span elements.


text:
Q: intranet with local databases Need to create a intranet for a management.
there are 4 institutions under this management:3colleges and a school
student biodata(recorded at priliminary admission until he/she leaves the school)
and the daily financial incomes(tution fee, bus fee, co-curricular fee) ,
and expenses should be fed into the intranet.
teachers attendance is also to be tracked via a biometric(finngerprint) scanner,
which is also to be fed to the system.
the 4 educational institutions are not in the same location.
we also have the main manager's office in a 5th location.
the manager should be able to view the daily transactions and
expenses at each institutions from his office.
even if internet is not available at any of the 4 institutions,
data entry should be possiblle(to loacal servers i assume) and should sync data to the
main server as soon as internet is available.
the client dosent need any type of data processing, they just need to record the data and retreive it whenever required.
questions:
1.should i use dedicated server equipment at the managers office, and have vpn connections over the internet to all institutions?
2.if no dedicated server is required at the customer premises, is online hosting via companies like godaddy is enough(so that the server is accesible by anyone with internet,via a login)?
3.is mysql(phpmyadmin)+lumen(laravel)+angular js enough for this project or should i go for python(django or tornado  with postgres or mongodb) or any other web stack?
4.should i have a desktop application ?

A: The issue is solved,
I decided to use online hosting server for the project.
We chose php laravael phpmyadmin mysql as the web stack.
We did it completely as a web app.


text:
Q: getting axes in numeric rather than alphabetical order when using xyplot I have the following dataframe:
interest       field1           date
1       0.191          3   January 2014
2        0.06          5   January 2014
3       0.012          7   January 2014
4           0         10   January 2014
5        0.01         15   January 2014
6        0.01         30   January 2014
7           0         60   January 2014
8           0         90   January 2014
9           0        999   January 2014
10      0.228          3  February 2014
11          0          5  February 2014
12      0.025          7  February 2014
13      0.031         10  February 2014
14      0.009         15  February 2014
15      0.005         30  February 2014
16          0         60  February 2014
17      0.012         90  February 2014
18      0.016        999  February 2014
19      0.205          3     March 2014
20      0.018          5     March 2014
21      0.013          7     March 2014
22          0         10     March 2014
23          0         15     March 2014
24      0.005         30     March 2014
25      0.004         60     March 2014
26      0.011         90     March 2014
27          0        999     March 2014
28      0.206          3     April 2014
29      0.034          5     April 2014
30      0.011          7     April 2014
31      0.029         10     April 2014
32       0.02         15     April 2014
33      0.006         30     April 2014
34          0         60     April 2014
35      0.009         90     April 2014
36          0        999     April 2014
37      0.281          3       May 2014
38      0.073          5       May 2014
39      0.069          7       May 2014
40      0.035         10       May 2014
41       0.01         15       May 2014
42      0.006         30       May 2014
43      0.013         60       May 2014
44      0.009         90       May 2014
45          0        999       May 2014
46      0.264          3      June 2014
47      0.078          5      June 2014
48      0.026          7      June 2014
49      0.024         10      June 2014
50       0.03         15      June 2014
51      0.005         30      June 2014
52          0         60      June 2014
53          0         90      June 2014
54          0        999      June 2014
55      0.179          3      July 2014
56      0.064          5      July 2014
57      0.026          7      July 2014
58      0.027         10      July 2014
59      0.011         15      July 2014
60      0.006         30      July 2014
61          0         60      July 2014
62      0.011         90      July 2014
63          0        999      July 2014
64       0.27          3    August 2014
65      0.072          5    August 2014
66      0.031          7    August 2014
67      0.018         10    August 2014
68      0.009         15    August 2014
69      0.017         30    August 2014
70      0.005         60    August 2014
71          0         90    August 2014
72          0        999    August 2014
73      0.216          3 September 2014
74       0.03          5 September 2014
75      0.045          7 September 2014
76      0.054         10 September 2014
77       0.02         15 September 2014
78      0.011         30 September 2014
79          0         60 September 2014
80          0         90 September 2014
81          0        999 September 2014
82      0.253          3   October 2014
83      0.037          5   October 2014
84      0.065          7   October 2014
85      0.049         10   October 2014
86      0.018         15   October 2014
87          0         30   October 2014
88      0.012         60   October 2014
89          0         90   October 2014
90          0        999   October 2014
91      0.219          3  November 2014
92      0.061          5  November 2014
93      0.007          7  November 2014
94      0.033         10  November 2014
95      0.006         15  November 2014
96      0.015         30  November 2014
97      0.004         60  November 2014
98          0         90  November 2014
99          0        999  November 2014
100     0.214          3  December 2014
101     0.047          5  December 2014
102     0.018          7  December 2014
103     0.008         10  December 2014
104     0.006         15  December 2014
105     0.012         30  December 2014
106         0         60  December 2014
107         0         90  December 2014
108         0        999  December 2014
109       0.3          3   January 2015
110     0.026          5   January 2015
111     0.018          7   January 2015
112     0.025         10   January 2015
113         0         15   January 2015
114     0.014         30   January 2015
115     0.003         60   January 2015
116         0         90   January 2015
117         0        999   January 2015

and I want to be able to plot interest vs. field 1, grouping by date. However, when I try the following code:
xyplot(as.numeric(interest)~(field1),Rates,groups=date,type="l",main = "title",auto.key=TRUE)

the problem is that the x axis is not in numerical order, but rather alphabetical order. Someone told me I could fix this by making the variable on the x-axis numeric, which is why I have the as.numeric functions in my code. But this did not work. Any suggestions? This seems like it should be the default for plotting a numerical variable, and yet I can't for the life of me figure out how to get it to order the points numerically. any help would be greatly appreciated!


text:
Q: Imprimir colunas alternadas vba excel com o código abaixo:
    Range("C1:S" & Linha).Select
    ActiveSheet.PageSetup.PrintArea = "$C$1:$S$" & Linha
    Application.ScreenUpdating = True
    Range("C2").Select

consigo imprimir todas as colunas do intervalo col. "c" até col. "S".
Há algum modo de imprimir só as col. "c", "D", "N", "O", "S" ?
Obrg.
Júlio Faria

A: Edit:
Não é possível imprimir na mesma folha uma range não contínua diretamente.
Então uma planilha temporária é criada para armazenar os dados em ordem de imprimí-los.

Obs.: Isto vai funcionar somente se todas as colunas tiverem a mesma quantidade de linhas

Código:
Sub ImprimirNaoContinuo()

    Dim rngPrint As Range
    Dim Linha As Long, i As Long
    Dim temp As Worksheet, ws As Worksheet
    Dim Arr() As Variant
    Linha = 15
    Set temp = Sheets.Add
    temp.Name = "Temporário"
    Set ws = Worksheets("Planilha1")
    Set rngPrint = Union(ws.Range("C1:$D" & Linha), ws.Range("$N$1:$O" & Linha), ws.Range("$S$1:$S" & Linha))

    'Função para preencher array com intervalo não contínuo
    'https://stackoverflow.com/a/18994211/7690982
    nr = rngPrint.Areas(1).Rows.Count
    ReDim Arr(1 To nr, 1 To rngPrint.Cells.Count / nr)
    cnum = 0
    For Each ar In rngPrint.Areas
        For Each col In ar.Columns
            cnum = cnum + 1
            rnum = 1
            For Each c In col.Cells
                Arr(rnum, cnum) = c.Value
                rnum = rnum + 1                  'EDIT: added missing line...
            Next c
        Next col
    Next ar

    For k = 1 To cnum
        For i = LBound(Arr) To UBound(Arr)
            temp.Cells(i, k) = Arr(i, k)
        Next i
    Next k

    lngLstRow = ws.UsedRange.Rows.Count
    lngLstCol = ws.UsedRange.Columns.Count

    temp.Range(temp.Cells(1, 1), temp.Cells(lngLstRow, lngLstCol)).PrintPreview
    Application.ScreenUpdating = True
    Application.DisplayAlerts = False
    temp.Delete
    Application.DisplayAlerts = True
End Sub

Explicação

*

*Define a Quantidade de Linhas a serem utilizadas
Linha = 15

Ou pode ser pela última linha preenchida na coluna C:
    Linha = ws.Cells(ws.Rows.Count, "C").End(xlUp).Row

*

*Cria a planilha temporária e define a planilha em que os dados a serem utilizados estão armazenados:
Set temp = Sheets.Add
temp.Name = "Temporário"
Set ws = Worksheets("Planilha1")

*Define o Range com os dados que serão salvos
Set rngPrint = Union(ws.Range("C1:$D" & Linha), ws.Range("$N$1:$O" & Linha), ws.Range("$S$1:$S" & Linha))

*Função para ordenar o intervalo não contínuo numa array
nr = rngPrint.Areas(1).Rows.Count
ReDim Arr(1 To nr, 1 To rngPrint.Cells.Count / nr)
cnum = 0
For Each ar In rngPrint.Areas
    For Each col In ar.Columns
        cnum = cnum + 1
        rnum = 1
        For Each c In col.Cells
            Arr(rnum, cnum) = c.Value
            rnum = rnum + 1                  'EDIT: added missing line...
        Next c
    Next col
Next ar

*Inserir os valores da Array na planilha temporária
For k = 1 To cnum
    For i = LBound(Arr) To UBound(Arr)
        temp.Cells(i, k) = Arr(i, k)
    Next i
Next k

*Abrir a janela de Visualização de impressão com o range utilizado
temp.Range(temp.Cells(1, 1), temp.Cells(lngLstRow, lngLstCol)).PrintPreview

*Deletar a planilha Temporária
Application.DisplayAlerts = False
temp.Delete
Application.DisplayAlerts = True

Edit2:
Para manter a formatação, cada coluna utilizada será copiada e depois colada na planilha temporária, mantendo assim, a formatação
Código
Sub ImprimirNaoContinuo2()

    Dim rngPrint As Range
    Dim Linha As Long, i As Long
    Dim temp As Worksheet, ws As Worksheet
    Dim Arr() As Variant

    Set temp = Sheets.Add
    temp.Name = "Temporário"
    Set ws = Worksheets("Planilha1")
    Linha = ws.Cells(ws.Rows.Count, "C").End(xlUp).Row
    Set rngPrint = Union(ws.Range("C1:$D" & Linha), ws.Range("$N$1:$O" & Linha), ws.Range("$S$1:$S" & Linha))

    For Each coluna In rngPrint.Columns
        i = i + 1
        coluna.Copy temp.Cells(1, i)
    Next coluna

    lngLstRow = temp.UsedRange.Rows.Count
    lngLstCol = temp.UsedRange.Columns.Count

    temp.Range(temp.Cells(1, 1), temp.Cells(lngLstRow, lngLstCol)).PrintPreview
    Application.ScreenUpdating = True
    Application.DisplayAlerts = False
    temp.Delete
    Application.DisplayAlerts = True
End Sub

Explicação
    For Each coluna In rngPrint.Columns
        i = i + 1
        coluna.Copy temp.Cells(1, i)
    Next coluna

Cada coluna no intervalo não contínuo é copiado e colado em ordem na nova planilha temporária. As outras partes do código já foram explicadas anteriormente.
Resposta Original
Você pode definir um intervalo não contínuo deste modo:
"$C$1:$D" & Linha & ", $N$1:$O" & Linha & ", $S$1:$S" & Linha

Em que, cada intervalo pode ser separado por uma vígula ,
Assim o código ficaria:
ActiveSheet.PageSetup.PrintArea = "$C$1:$D" & Linha & ", $N$1:$O" & Linha & ", $S$1:$S" & Linha
Application.ScreenUpdating = True
Range("C2").Select

Obs.: Tente evitar o uso de .Select, ActiveCell, ActiveSheet, etc. Pois podem ocorrer erros. No SOEN há um tópico com alguns exemplos de como evitá-los neste link: How to avoid using Select in Excel VBA


text:
Q: How can I tell if an array of integers is an alternating array? I want to tell if an array of integers is alternating.
in JAVA.
For example:
a[]={1,-1,1,-1,1,-1}  --> true
a[]={-1,1,-1,1,-1}    --> true
a[]={1,-4,1-6,1}      --> true
a[]={1,1,1,14,5,3,2}  --> false

I have started to write some code that uses flags. For example if the current_is_positive=0 and else = 1, but I'm not getting anywhere. What is a good way to achieve this effect?

A: I think you mean alternating in sign, i.e. positive number, negative number, positive number, etc.?
You could use the following strategy:
Skip the first element.
For every other element, compare its sign with the sign of the previous element:

*

*If they're different, the sequence is still alternating upto now - you should continue.

*If they're the same sign, the sequence is not alternating. You can stop processing at this point.

As this sounds like a homework assignment, I'll leave it upto you to write the appropriate code in Java.

A: Here my solution:
This checks that element n+1 is the inverse of the element n.
    public static void main(String[] args) {
        int[] ints = {1, -1, 2, -1};
        System.out.println(new Example().isArrayAlternating(ints));
    }

    public boolean isArrayAlternating(int[] ints) {
        if (ints == null || ints.length % 2 != 0) {
            return false;
        }
        for (int i = 0; i < ints.length - 1; i++) {
            if (ints[i] != ints[i + 1]*(-1)) {
                return false;
            }
        }
        return true;
    }

If you only wanted to check for positive number, negative number...n times, without paying attention to value:
public static void main(String[] args) {
    int[] ints = {1, -1, 2, -1};
    System.out.println(new Example().isArrayAlternating(ints));
}

public boolean isArrayAlternating(int[] ints) {
    if (ints == null || ints.length % 2 != 0) {
        return false;
    }
    for (int i = 0; i < ints.length - 1; i++) {
        if (ints[i] >= 0 && ints[i + 1] >= 0 || ints[i] <= 0 && ints[i + 1] <= 0) {
            return false;
        }
    }
    return true;
}

A: You can simply check if all items are equal to the item two steps back. I don't know what language you are using, but for example using C# you could do it like this:
bool alternating = a.Skip(2).Where((n, i) => a[i] == n).Count() == a.Length - 2;

Edit:
So you want to check if the sign of the values are alternating, not the values?
Then just check the sign against the previous item:
bool alternating = a.Skip(1).Where((n,i) => Math.Sign(n) == -Math.Sign(a[i])).Count() == a.Length-1;

A: boolean prevPositive = arr[0] > 0, error = false;
for (int i = 1; i < arr.length; ++i) {
    boolean current = arr[i] > 0;
    if (current != prevPositive) {
        current = prevPositive;
    } else {
        error = true;
        break;
    }
}
if (error)
   System.out.println("No");
else
   System.out.println("Yes");

A: *

*Run a loop, from first index to maximum possible with a step of 2, to check for same sign.

*Then again a loop, from 2nd index to maximum possible with a step of 2, to check for opposite sign, but all same.

*So, loop from index -  0, 2, 4, 6, ...

*then loop from index - 1, 3, 5, 7, ...

*Then check that the multiplication of every number in both loop with the first number in that iteration should be positive.
int a[]={1,-1,1,-1,1,-1};

boolean alternating = true;

for (int i = 0; i < a.length; i = i + 2) {
    if (a[i] * a[0] > 0) {
    } else {
        alternating = false;
    }
}
for (int i = 1; i < a.length; i = i + 2) {
    if (a[i] * a[1] > 0) {
    } else {
        alternating = false;
    }
}

if (alternating) {
    System.out.println("Array is alternating");
} else
    System.out.println("Array is not alternating");
}

A: private enum SIGN {
    POSITIVE, NEGATIVE
};

public static boolean isAlternating(int... ints) {
    SIGN last = null;
    for (int i : ints) {
        if (i >= 0) {
            if (last == null) {
                last = SIGN.POSITIVE;
            } else {
                if (last == SIGN.POSITIVE) {
                    return false;
                } else {
                    last = SIGN.POSITIVE;
                }
            }
        } else {
            if (last == null) {
                last = SIGN.NEGATIVE;
            } else {
                if (last == SIGN.NEGATIVE) {
                    return false;
                } else {
                    last = SIGN.NEGATIVE;
                }
            }
        }
    }
    return true;
}

A: Run through the array from index 1 till the end.
At each index, evaluate (a[i] > 0) == (a[i-1] > 0). If this is true, then your array is not alternating.
If you make it till the end without concluding it is not alternating, then it is alternating :)

A: For i = 2 to n

   check whether A[i-1] && A[i] are with diff sign..
   in C++; return  ((A[i-1] ^  A[i]) < 0).

Same explained here : http://www.youtube.com/watch?v=Z59REm2YKX0
EDIT
If an integer is negative, then the high order bit is 1.  Otherwise, it's 0.  You can check if two integers have different signs by XORing them together.  If the signs are different, then the high order bit of the result will be 1.  If they're the same, then the high order bit will be 0.  Thus,
A XOR B < 0 is equivalent to "A and B have different signs"
Peter Ruderman


text:
Q: Using a variable to set the x point of a line How can I draw a line using one of my variables as x point?
For example: variable =  (an engulfing which close under an ema)
If I write: line.new(x1=variable....) The script gives me error.

A: I suppose the variable candle is a boolean?
line.new() function requires a bar_index or timestamp for the x argument.
The example below connects 2 latest bearish Engulfing candle's closes with a red line using the ta.valuewhen() built-in function.
*using the built-in source code for the engulfing candle
//@version=5
indicator("Engulfing - Bearish", shorttitle = "Engulfing - Bear", overlay=true)

C_DownTrend = true
C_UpTrend = true
var trendRule1 = "SMA50"
var trendRule2 = "SMA50, SMA200"
var trendRule = input.string(trendRule1, "Detect Trend Based On", options=[trendRule1, trendRule2, "No detection"])

if trendRule == trendRule1
    priceAvg = ta.sma(close, 50)
    C_DownTrend := close < priceAvg
    C_UpTrend := close > priceAvg

if trendRule == trendRule2
    sma200 = ta.sma(close, 200)
    sma50 = ta.sma(close, 50)
    C_DownTrend := close < sma50 and sma50 < sma200
    C_UpTrend := close > sma50 and sma50 > sma200
C_Len = 14 // ta.ema depth for bodyAvg
C_ShadowPercent = 5.0 // size of shadows
C_ShadowEqualsPercent = 100.0
C_DojiBodyPercent = 5.0
C_Factor = 2.0 // shows the number of times the shadow dominates the candlestick body

C_BodyHi = math.max(close, open)
C_BodyLo = math.min(close, open)
C_Body = C_BodyHi - C_BodyLo
C_BodyAvg = ta.ema(C_Body, C_Len)
C_SmallBody = C_Body < C_BodyAvg
C_LongBody = C_Body > C_BodyAvg
C_UpShadow = high - C_BodyHi
C_DnShadow = C_BodyLo - low
C_HasUpShadow = C_UpShadow > C_ShadowPercent / 100 * C_Body
C_HasDnShadow = C_DnShadow > C_ShadowPercent / 100 * C_Body
C_WhiteBody = open < close
C_BlackBody = open > close
C_Range = high-low
C_IsInsideBar = C_BodyHi[1] > C_BodyHi and C_BodyLo[1] < C_BodyLo
C_BodyMiddle = C_Body / 2 + C_BodyLo
C_ShadowEquals = C_UpShadow == C_DnShadow or (math.abs(C_UpShadow - C_DnShadow) / C_DnShadow * 100) < C_ShadowEqualsPercent and (math.abs(C_DnShadow - C_UpShadow) / C_UpShadow * 100) < C_ShadowEqualsPercent
C_IsDojiBody = C_Range > 0 and C_Body <= C_Range * C_DojiBodyPercent / 100
C_Doji = C_IsDojiBody and C_ShadowEquals

patternLabelPosLow = low - (ta.atr(30) * 0.6)
patternLabelPosHigh = high + (ta.atr(30) * 0.6)

label_color_bearish = input(color.red, "Label Color Bearish")
C_EngulfingBearishNumberOfCandles = 2
C_EngulfingBearish = C_UpTrend and C_BlackBody and C_LongBody and C_WhiteBody[1] and C_SmallBody[1] and close <= open[1] and open >= close[1] and ( close < open[1] or open > close[1] )
alertcondition(C_EngulfingBearish, title = "New pattern detected", message = "New Engulfing – Bearish pattern detected")
if C_EngulfingBearish
    var ttBearishEngulfing = "Engulfing\nAt the end of a given uptrend, a reversal pattern will most likely appear. During the first day, this candlestick pattern uses a small body. It is then followed by a day where the candle body fully overtakes the body from the day before it and closes in the trend's opposite direction. Although similar to the outside reversal chart pattern, it is not essential for this pattern to fully overtake the range (high to low), rather only the open and the close."
    label.new(bar_index, patternLabelPosHigh, text="BE", style=label.style_label_down, color = label_color_bearish, textcolor=color.white, tooltip = ttBearishEngulfing)
bgcolor(ta.highest(C_EngulfingBearish?1:0, C_EngulfingBearishNumberOfCandles)!=0 ? color.new(color.red, 90) : na, offset=-(C_EngulfingBearishNumberOfCandles-1))

// -----
// line connects closing values of the 2 latest engulfing candles
var line line1 = line.new(bar_index, close, bar_index, close, xloc.bar_index, extend.both, color.red)
line.set_xy1(line1, ta.valuewhen(C_EngulfingBearish, bar_index, 0), ta.valuewhen(C_EngulfingBearish, close, 0))
line.set_xy2(line1, ta.valuewhen(C_EngulfingBearish, bar_index, 1), ta.valuewhen(C_EngulfingBearish, close, 1))

You can compare the values of the engulfing candle later using the built-in fixnan() function:
C_EngulfingBearishClose = fixnan(C_EngulfingBearish ? close : na)
C_EngulfingBearishTime = fixnan(C_EngulfingBearish ? time : na)
plot(C_EngulfingBearishClose)
bgcolor(C_EngulfingBearishTime == time ? color.purple : na)


text:
Q: How do I eliminate the call to http://fpdownload.adobe.com/pub/swz/crossdomain.xml in my Adobe AIR application? I have an Adobe AIR application and at a certain point it issues the warning:
Warning: Ignoring 'secure' attribute in policy file from http://fpdownload.adobe.com/pub/swz/crossdomain.xml.  The 'secure' attribute is only permitted in HTTPS and socket policy files.  See http://www.adobe.com/go/strict_policy_files for details.
I am not directly loading any external files at this point in the code.  I also have tried setting static-link-runtime-shared-libraries to true and that seems to make no difference.
I'd like to know what else might be causing this request, and how to eliminate it.  My application should be able to run without an internet connection, but this request is essentially blocking that ability.

A: Had the same error message, solved it by removing references to fonts that were not included in my asset.swf
Was running localy in FD 4.2.4, with parent.swf loading asset.swf as an asset library.
asset.swf had movieclips with textfields and fonts assigned as Font 1*, Font 2* etc., which were included in the library.
One of these textfields had a reference to "Times New Roman", which was not included.
Removing this textfield made everything work again!
Hope this helps anyone who has the same error message.

A: In Flash Professional, this error may be because of the TLF texts...


text:
Q: creating dynamic bootstrap style with asp net web forms i just created a pagination function that i need to be styled with css. the problem is that it does not take the class i want for some reason. here is my code:
C#:
using System;
using System.Collections;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Linq;

namespace SourceTech.Web.UI.WebControls
{
    ///
    /// Class for pagination.
    ///
    public class SourceTechPager : Panel
    {

        ///
        /// Renders the databind to aspx.
        ///
        protected override void Render(HtmlTextWriter writer)
        {
            CssClass = "Pagination"; //My css class

            base.Render(writer);
        }

        ///
        /// Algorithm for paging.
        ///
        public override void DataBind()
        {
            Controls.Clear();

            var startLoop = CurrentPage - 2;

            var totalLoop = TotalPage;

            if ((TotalPage - 2) > 7)
            {
                totalLoop = (CurrentPage - 2) + (CurrentPage + 4);

                if (totalLoop > TotalPage)
                {
                    totalLoop = TotalPage;
                }
            }

            if (startLoop <= 1)
            {
                startLoop = 0;
            }

            for (var i = (startLoop); i < totalLoop; i++)
            {
                var lb = new LinkButton();

                if (TotalPage == 1)
                {
                    lb.Visible = false;
                }

                lb.ID = "Pager" + i;

                lb.CommandArgument = (i + 1).ToString();
            if (i + 1 == CurrentPage)
            {
                lb.CssClass = "Pagination"; //My css class
            }

            lb.Text = (i + 1).ToString();

            lb.Click += ((sender, args) =>
            {
                CurrentPage = int.Parse(((LinkButton)sender).CommandArgument);
            });

            Controls.Add(lb);
        }

        base.DataBind();
    }
}

}
ASPX:

                    «

                <asp:SourceTechPager runat="server" ID="pagerId" CurrentPage="1" />

                    »

CSS:
.SourceTechPager .Pagination {
    display: inline-block;
    padding-left: 0;
    margin: 20px 0;
    border-radius: 4px;
    position: relative;
    float: left;
    padding: 6px 12px;
    margin-left: -1px;
    line-height: 1.42857143;
    color: #337ab7;
    text-decoration: none;
    background-color: #fff;
    border: 1px solid #ddd;
}

.pagerCssClass {
    margin-left: 500px;
}

.pagination {
    display: inline-block;
    padding-left: 0;
    margin: 20px 0;
    border-radius: 4px;
}

    .pagination > li {
        display: inline;
    }

        .pagination > li > a,
        .pagination > li > span {
            position: relative;
            float: left;
            padding: 6px 12px;
            margin-left: -1px;
            line-height: 1.42857143;
            color: #337ab7;
            text-decoration: none;
            background-color: #fff;
            border: 1px solid #ddd;
        }

        .pagination > li:first-child > a,
        .pagination > li:first-child > span {
            margin-left: 0;
            border-top-left-radius: 4px;
            border-bottom-left-radius: 4px;
        }

        .pagination > li:last-child > a,
        .pagination > li:last-child > span {
            border-top-right-radius: 4px;
            border-bottom-right-radius: 4px;
        }

        .pagination > li > a:hover,
        .pagination > li > span:hover,
        .pagination > li > a:focus,
        .pagination > li > span:focus {
            z-index: 2;
            color: #23527c;
            background-color: #eee;
            border-color: #ddd;
        }

    .pagination > .active > a,
    .pagination > .active > span,
    .pagination > .active > a:hover,
    .pagination > .active > span:hover,
    .pagination > .active > a:focus,
    .pagination > .active > span:focus {
        z-index: 3;
        color: #fff;
        cursor: default;
        background-color: #337ab7;
        border-color: #337ab7;
    }

    .pagination > .disabled > span,
    .pagination > .disabled > span:hover,
    .pagination > .disabled > span:focus,
    .pagination > .disabled > a,
    .pagination > .disabled > a:hover,
    .pagination > .disabled > a:focus {
        color: #777;
        cursor: not-allowed;
        background-color: #fff;
        border-color: #ddd;
    }

.pagination-lg > li > a,
.pagination-lg > li > span {
    padding: 10px 16px;
    font-size: 18px;
    line-height: 1.3333333;
}

.pagination-lg > li:first-child > a,
.pagination-lg > li:first-child > span {
    border-top-left-radius: 6px;
    border-bottom-left-radius: 6px;
}

.pagination-lg > li:last-child > a,
.pagination-lg > li:last-child > span {
    border-top-right-radius: 6px;
    border-bottom-right-radius: 6px;
}

.pagination-sm > li > a,
.pagination-sm > li > span {
    padding: 5px 10px;
    font-size: 12px;
    line-height: 1.5;
}

.pagination-sm > li:first-child > a,
.pagination-sm > li:first-child > span {
    border-top-left-radius: 3px;
    border-bottom-left-radius: 3px;
}

.pagination-sm > li:last-child > a,
.pagination-sm > li:last-child > span {
    border-top-right-radius: 3px;
    border-bottom-right-radius: 3px;
}

I tried with hardcoding an integer "1" to my listitem tag, and that works fine with the style, but it does not for some reason once i place my control tag in it. what should i do?


text:
Q: How can I group users into sessions in a node.js draw application? I made a draw app in node.js and socket.io recently. It works fine but all things drawn by a user will be seen by all users. I want to add the concept of sessions so the things a user draws will only be seen by people in the same session. How can I do it?
Here's the server code I use:
var express = require('express');
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(8000);

app.use(express.static(__dirname));
app.use(express.logger());
app.engine('html', require('ejs').__express);

app.get('/',function(req,res){
    res.sendfile(__dirname+'/index.html');
});

io.sockets.on('connection',function(socket){
    socket.on('mousedown',function(data){
        socket.broadcast.emit('mousedown',data);
    });
    socket.on('mousemove',function(data){
        socket.broadcast.emit('mousedown',data);
    });
    socket.on('mouseup',function(data){
        socket.broadcast.emit('mousedown',data);
    });
    socket.on('tool',function(data){
        socket.broadcast.emit('mousedown',data);
    });
});

Also, this is the code I used for the clinet side:
var socket = {};

if(typeof io !== 'undefined' && io){
    socket = io.connect('http://127.0.0.1:8000');
}
else
{
    socket = {
        emit:function(){
            console.log(arguments);
        },
        on:function(){
            console.log(arguments);
        }
    };
}

$(function(){
  var canvas, context, canvaso, contexto;

  // The active tool instance.
  var tool;
  var tool_default = 'line';

  function init () {
    // Find the canvas element.
    canvaso = document.getElementById('imageView');
    canvaso.width = window.innerWidth * 0.9;
    canvaso.height = window.innerHeight/2;
    if (!canvaso) {
      console.log('Error: I cannot find the canvas element!');
      return;
    }

    if (!canvaso.getContext) {
      console.log('Error: no canvas.getContext!');
      return;
    }

    // Get the 2D canvas context.
    contexto = canvaso.getContext('2d');
    if (!contexto) {
      console.log('Error: failed to getContext!');
      return;
    }

    // Add the temporary canvas.
    var container = canvaso.parentNode;
    canvas = document.createElement('canvas');
    if (!canvas) {
      console.log('Error: I cannot create a new canvas element!');
      return;
    }

    canvas.id     = 'imageTemp';
    canvas.width  = canvaso.width;
    canvas.height = canvaso.height;
    container.appendChild(canvas);

    context = canvas.getContext('2d');

    // Get the tool select input.
    var tool_select = document.getElementById('dtool');
    if (!tool_select) {
      console.log('Error: failed to get the dtool element!');
      return;
    }
    tool_select.addEventListener('change', ev_tool_change, false);

    // Activate the default tool.
    if (tools[tool_default]) {
      tool = new tools[tool_default]();
      tool_select.value = tool_default;
    }

    // Attach the mousedown, mousemove and mouseup event listeners.
    $(canvas).on('mousedown',ev_canvas);
    $(canvas).on('mousemove',ev_canvas);
    $(canvas).on('mouseup',ev_canvas);
  }

  // The general-purpose event handler. This function just determines the mouse
  // position relative to the canvas element.
  function ev_canvas (ev) {
    ev._x = ev.offsetX;
    ev._y = ev.offsetY;

    // Call the event handler of the tool.
    var func = tool[ev.type];
    socket.emit(ev.type,{x:ev._x,y:ev._y});
    if (func) {
      func(ev);
    }
  }

  socket.on('mousedown',function(data){
    ev_canvas({type:'mousedown',_x:data.x,_y:data.y});
  });

  socket.on('mousemove',function(data){
    ev_canvas({type:'mousemove',_x:data.x,_y:data.y});
  });

  socket.on('mouseup',function(data){
    ev_canvas({type:'mouseup',_x:data.x,_y:data.y});
  });

  // The event handler for any changes made to the tool selector.
  function ev_tool_change (ev) {
    if (tools[this.value]) {
      tool = new tools[this.value]();
      socket.emit('tool',this.value);
    }
  }
  socket.emit('tool',tool_default);
  socket.on('tool',function(stool){
    tool = new tools[stool]();
  });

  // This function draws the #imageTemp canvas on top of #imageView, after which
  // #imageTemp is cleared. This function is called each time when the user
  // completes a drawing operation.
  function img_update () {
        contexto.drawImage(canvas, 0, 0);
        context.clearRect(0, 0, canvas.width, canvas.height);
  }

  // This object holds the implementation of each drawing tool.
  var tools = {};

  // The drawing pencil.
  tools.pencil = function () {
    var tool = this;
    this.started = false;

    // This is called when you start holding down the mouse button.
    // This starts the pencil drawing.
    this.mousedown = function (ev) {
        context.beginPath();
        context.moveTo(ev._x, ev._y);
        tool.started = true;
    };

    // This function is called every time you move the mouse. Obviously, it only
    // draws if the tool.started state is set to true (when you are holding down
    // the mouse button).
    this.mousemove = function (ev) {
      if (tool.started) {
        context.lineTo(ev._x, ev._y);
        context.stroke();
      }
    };

    // This is called when you release the mouse button.
    this.mouseup = function (ev) {
      if (tool.started) {
        tool.mousemove(ev);
        tool.started = false;
        img_update();
      }
    };
  };

  // The rectangle tool.
  tools.rect = function () {
    var tool = this;
    this.started = false;

    this.mousedown = function (ev) {
      tool.started = true;
      tool.x0 = ev._x;
      tool.y0 = ev._y;
    };

    this.mousemove = function (ev) {
      if (!tool.started) {
        return;
      }

      var x = Math.min(ev._x,  tool.x0),
          y = Math.min(ev._y,  tool.y0),
          w = Math.abs(ev._x - tool.x0),
          h = Math.abs(ev._y - tool.y0);

      context.clearRect(0, 0, canvas.width, canvas.height);

      if (!w || !h) {
        return;
      }

      context.strokeRect(x, y, w, h);
    };

    this.mouseup = function (ev) {
      if (tool.started) {
        tool.mousemove(ev);
        tool.started = false;
        img_update();
      }
    };
  };

  // The line tool.
  tools.line = function () {
    var tool = this;
    this.started = false;

    this.mousedown = function (ev) {
      tool.started = true;
      tool.x0 = ev._x;
      tool.y0 = ev._y;
    };

    this.mousemove = function (ev) {
      if (!tool.started) {
        return;
      }

      context.clearRect(0, 0, canvas.width, canvas.height);

      context.beginPath();
      context.moveTo(tool.x0, tool.y0);
      context.lineTo(ev._x,   ev._y);
      context.stroke();
      context.closePath();
    };

    this.mouseup = function (ev) {
      if (tool.started) {
        tool.mousemove(ev);
        tool.started = false;
        img_update();
      }
    };
  };

  init();

});

Any help will be appreciated.

A: It sounds to me like you want to be using Rooms
You can add users to rooms as they connect just within io.sockets.on('connection')
For example:
io.sockets.on('connection', function (socket) {
  socket.join('room');
  socket.broadcast.to('room').send("I'm in this room now");
});

You can then use this to broadcast new drawings within just the room of where it originated.


text:
Q: Codeigniter file upload from a form without ajax/jquery/javascript Context : I am updating user_profile data after user registration using form #updateprofileform ,
i am able to process all other form fields using standard validations and insert/update using user_model.
issue is with resume field which should accept a file as input type and upload to server and store its path on server (say http://domain/uploads/$filename) to a column in database.
Expectation A logged in user , able to view his details(if already in database),update details if incomplete profile.
Question : I found methods how we can upload a file to server using CI framework or how we can upload a file in this context using jquery/ajax/java-script. But i am looking for simple solution for above problem which can do the job with out dependency on technologies.
user_profile.php (view)

<form class="row" name="updateprofile" action = "<?php echo base_url()?>user/user_profile" method="POST">

        Email ID	<input class="form-control" name="email" placeholder="Email-ID" type="text" value="<?php if (isset($email)) echo $email;?>" /> <?php  echo form_error('email'); ?>

        Resume

          <input name="resume" placeholder="Upload resume" type="file" value="<?php if (isset($resume)) echo $resume;?>" />
          <?php  echo form_error('resume'); ?>

 <button type="submit" class="btn btn--primary type--uppercase" name="updateprofile" value="updateprofile" formaction = "<?php echo base_url()?>user/user_profile">Update Profile</button>

  </form>

user_controller
class User extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
$config = array(
        'upload_path' => "./uploads/",
        'allowed_types' => "doc|docx|pdf",
        'overwrite' => TRUE,
        'max_size' => "2048000", // Can be set to particular file size , here it is 2 MB(2048 Kb)
        //'max_height' => "768",
        //'max_width' => "1024"
        );
        $this->load->library('upload', $config);
    }
  public function user_profile()
    {
      $resume = $this->input->post('resume');
  if ($this->user_model->set_user_profile($id,FALSE) )
            { if($this->do_upload($resume)){
                $this->session->set_flashdata('msg_success','Updation Successful!');
                  echo validation_errors();}
            }
            else
            {
                $this->session->set_flashdata('msg_error','Error! Please try again later.');
                redirect('user/user_profile');
            }
  public function do_upload($resume){

    if($this->upload->do_upload($resume))
    {
    $data = array('upload_data' => $this->upload->data($resume));

    $this->load->view('user_profile',$data);
    }
    else
    {
    $error = array('error' => $this->upload->display_errors($resume));
    $this->load->view('user_profile', $error);
    }
    }

currently always error.... Error! Please try again later . so appreciate some pointers here to upload both file and form data together and save file location in database without ajax/jquery.
Thanks

A: Change the form definition to the following:
<form class="row" action = "<?php echo base_url('user/user_profile'); ?>" method="post" enctype="multipart/form-data" name="updateprofile" >

A: Resolved !
4 important steps needed and some missing in most Q&A in all other posts to make this complete.will share samplecode in github when i get sometime.

*

*form encryption type must be enctype="multipart/form-data" (thanks
to @Javier Larroulet and @dexter )

*do_upload method by default look for file field with name=userfile
(Thanks to @Alex ! for referencing this), so, if you have your
form's file field name different than userfile, then only it is
required to mention as do_upload('filefieldname') otherwise
optional

*loading of upload library configuration is tricky..  if you
autoupload the upload library , then load->library upload config will fail!, you
just =>initialize it.$this->upload->initialize($config); if you
are not using  autoload for upload library, then yes, you can load it
from controller.  $this->load->library('upload', $config);

*when ever, you are using upload, you have to catch the form validation errors
and data errors separately (again thanks to @Alex for pointing this)

a nice documentation is given from codeigniter at this link (https://www.codeigniter.com/userguide3/libraries/file_uploading.html#the-controller ) but doesn't highlight routine mistakes.
hope this post help someone not to waste another 24 hours to debug.


text:
Q: Why no asterisk sign when creating instance of NSString NSString listOfNames = @"..."; // a long list of names
NSString name = @"Ward";
NSRange match = [listOfNames rangeOfString:name];
if (match.location == NSNotFound) {
    NSLog(@"No match found!");
    // Other actions to be taken
} else {
    NSLog(@"Match found!");
    // Other actions to be taken
}

Why don't the 1st, 2nd and third line of code use asterisk sign like this
NSString *listOfNames = @"...";
NSString *name = @"Ward";
NSRange *match = [listOfNames rangeOfString:name];

A: NSString listOfNames = @"..."; // a long list of names
NSString name = @"Ward";
NSRange match = [listOfNames rangeOfString:name];

First two lines are creating NSString's objectect. NSString is a subclass of NSObject, and all NSObject and its subclass should have * (pointer sign associated with them).
While NSRange is a struct not in the inheritance chain with NSObject, hence no pointer sign is required, however under some situations you can make pointers to NSRange too.
*Your above code will give compiler errors.
You need to use it as :
NSString *listOfNames = @"..."; // a long list of names
NSString *name = @"Ward";
NSRange match = [listOfNames rangeOfString:name];

A:  NSString* str = [NSString stringWithString:@"Blah..."];

Note the * after NSString. You're working objective C here so pointers to objects!

A: I think we can't execute this code, if you execute this code you will get errors.

A:
This is what I normally see when try to do same. XCode automatically prompt you to add "*" before property name.

A: Generally in Cocoa object, you're always declaring a pointer, so you always use an asterisk. You can't put the object itself into the variable; you always handle a pointer to the object.
for other objects
If the variable contain's the object, then you don't use an asterisk, because you're not putting a pointer in it. If it contain's a pointer, then you do declare it with an asterisk.


text:
Q: Insert posted data in SQL Server Database I am able to post the data from Excel to ASP.NET MVC web service. Here is My code for that:
Sub SendData()
Dim HttpReq As Object, url As String
Set HttpReq = CreateObject("MSXML2.ServerXMLHTTP")
url = "http://localhost:11121/Student/PostData/"
HttpReq.Open "POST", url, False
HttpReq.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded"
HttpReq.Send "Student=jsmith112"
Debug.Print HttpReq.ResponseText
End Sub

Now, I Want to have a ControllerAction "Insert" That will Insert this posted data in SQLServer Database.
What do I need to do to controller action for this?

A: You need to add <AcceptVerbs(HttpVerbs.POST)> attribute if it's vs2008 or just <HttpPost()> for vs2010 to your controller method, so it receives the posted data.
Please note that this is in C#, syntax is slightly different for VB.