text:
Q: Create SAML 2.0 response with signed and encrypted Assertion using c# Hi I am new to SAML and SSO techniques. I am trying to create a valid SAML reponse with signed and encrypted Assertion. I have created a SAML response which is signed but i am not able to encrypte the assertion and create the  tag. My Generated SAML response is,
<samlp:Response xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" ID="_88a4cf19-6f41-46ee-9dc3-98ac80168bd9" Version="2.0" IssueInstant="2015-03-26T11:43:13.4468624Z" Destination="Test1" xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol">
    <saml:Issuer>Test</saml:Issuer>
    <Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
        <SignedInfo>
            <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
            <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" />
            <Reference URI="#_49bc8835-7c9a-4ee2-8087-7cfcbe48375f">
                <Transforms>
                    <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
                    <Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
                </Transforms>
                <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
                <DigestValue>My4iQVO1Oy3i6jV+Jlp0czX0mpA=</DigestValue>
            </Reference>
        </SignedInfo>
        <SignatureValue>GWfdKMCHbiqq6OhyHQ0y2LoDQkmC95fs3SKWyPMzu6jSjbf6vrMRFCrlch+DU1k3+sfsj1tFkJNMPKpxZIx2XksjnEQv3Hdqy7oPSoGiODmrky7CTKEdYbCQqu6a8dwNBLNQTClYAgDz/m5yfbFlJNPy9TtsCl2l1R/qg6dzVkA=</SignatureValue>
        <KeyInfo>
            <X509Data>
                <X509Certificate>MIIBwTCCAS6gAwIBAgIQr71oSHfrBKpKpRUTWmBFCzAJBgUrDgMCHQUAMCMxITAfBgNVBAMeGABCAEYASQBcAGQAcwBwAGUAaQBnAGgAdDAeFw0xMDAyMTkxMzI4MzlaFw0xMTAyMTkxOTI4MzlaMCMxITAfBgNVBAMeGABCAEYASQBcAGQAcwBwAGUAaQBnAGgAdDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAxXmIj8FBaL+94B/fNsBcoNZZraicGsm5+8VtWQIaGdM65q6vgDSQAg4zOkTQCqKh2vlN2NHSZb2XjcrUTWm2Vb279dvkOZfZ1mdQeLjM2LbXvrY4e7qK1dhZy9gZ3Mhvuk3cKPwwPsLNFifOt6OsS8ZzK7/PC+uUKznZtRsCAwEAATAJBgUrDgMCHQUAA4GBADGP1MjZm28GdYy3mQGprHQNDn8fIyBQvhwVwl4SVPxYDTKG7OsUC/QDUzy8vGXm+9qd2Es5creZS1DTAweC60JsJLdmp631FnbG4xJOCRHbR0HWyruhGkN6wPJ0RyJbdUrAcEPG4cfcYwl3oBeL48MfUD56UC0jSfBezUvnOMBX</X509Certificate>
            </X509Data>
        </KeyInfo>
    </Signature>
    <samlp:Status>
        <samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success" />
    </samlp:Status>
    <saml:Assertion Version="2.0" ID="_49bc8835-7c9a-4ee2-8087-7cfcbe48375f" IssueInstant="2015-03-26T11:43:13.6835615Z">
        <saml:Issuer>Test</saml:Issuer>
        <saml:Subject>
            <saml:NameID NameQualifier="TestDomain">TestSubject</saml:NameID>
            <saml:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">
                <saml:SubjectConfirmationData NotOnOrAfter="2015-03-26T11:48:13.7304370Z" Recipient="Test1" />
            </saml:SubjectConfirmation>
        </saml:Subject>
        <saml:Conditions NotBefore="2015-03-26T11:43:13.6835615Z" NotOnOrAfter="2015-03-26T11:48:13.6835615Z">
            <saml:AudienceRestriction>
                <saml:Audience>TestDomain</saml:Audience>
            </saml:AudienceRestriction>
        </saml:Conditions>
        <saml:AuthnStatement AuthnInstant="2015-03-26T11:43:13.6835615Z">
            <saml:AuthnContext>
                <saml:AuthnContextClassRef>AuthnContextClassRef</saml:AuthnContextClassRef>
            </saml:AuthnContext>
        </saml:AuthnStatement>
        <saml:AttributeStatement>
            <saml:Attribute Name="UserId" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic">
                <saml:AttributeValue xmlns:q1="http://www.w3.org/2001/XMLSchema" p7:type="q1:string" xmlns:p7="http://www.w3.org/2001/XMLSchema-instance">1000001</saml:AttributeValue>
            </saml:Attribute>
            <saml:Attribute Name="UserName" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic">
                <saml:AttributeValue xmlns:q2="http://www.w3.org/2001/XMLSchema" p7:type="q2:string" xmlns:p7="http://www.w3.org/2001/XMLSchema-instance">Manish Pandey</saml:AttributeValue>
            </saml:Attribute>
        </saml:AttributeStatement>
    </saml:Assertion>
</samlp:Response>

Can any one suggest any method to accomplish this?

A: it depends what kind of encryption you want to use... Basically you would have to encrypt signed assertion and replace assertion node with EncryptedAssertion node.
I recommend using both symmetric and asymmetric encryption.
Using Symmetric key to encrypt the whole of assertion node and then use asymmetric (i.e. certificate public/private key to encrypt symmetric key). I have used our client's certificate public key to encrypt symmetric key so only they can decrypt using their private key.
I have also specified certificate I want to use in web.config...
    string samlResponseXml = '<SAML Response Message>'

    XmlDocument loginResponseXmlDocument = new XmlDocument();
    loginResponseXmlDocument.LoadXml(samlResponseXml);

    // Add name spaces
        XmlNamespaceManager namespaceManager = new XmlNamespaceManager(loginResponseXmlDocument.NameTable);
        namespaceManager.AddNamespace("samlp", "urn:oasis:names:tc:SAML:2.0:protocol");
        namespaceManager.AddNamespace("saml", "urn:oasis:names:tc:SAML:2.0:assertion");
        namespaceManager.AddNamespace("ds", "http://www.w3.org/2000/09/xmldsig#");
        namespaceManager.AddNamespace("xenc", "http://www.w3.org/2001/04/xmlenc#");

    Encrypt(loginResponseXmlDocument, namespaceManager);

    private void Encrypt(XmlDocument document, XmlNamespaceManager namespaceManager)
    {
        // create symmetric key
        var key = new RijndaelManaged();
        key.BlockSize = 128;
        key.KeySize = 256;
        key.Padding = PaddingMode.ISO10126;
        key.Mode = CipherMode.CBC;

        XmlElement assertion = (XmlElement)document.SelectSingleNode("/samlp:Response/saml:Assertion", namespaceManager);

        EncryptedXml eXml = new EncryptedXml();

        byte[] encryptedElement = eXml.EncryptData(assertion, key, false);

        EncryptedData edElement = new EncryptedData
        {
            Type = EncryptedXml.XmlEncAES256Url
        };

        const string encryptionMethod = EncryptedXml.XmlEncAES256Url;
        edElement.EncryptionMethod = new EncryptionMethod(encryptionMethod);
        edElement.CipherData.CipherValue = encryptedElement;

        // edElement = EncryptedData

        // Now encrypt symmetric key
        string certificateDn = ConfigurationManager.AppSettings["CertificateDN"];
        X509Certificate2 x509Certificate = GetCertificate(certificateDn);

        RSACryptoServiceProvider rsa = x509Certificate.PublicKey.Key as RSACryptoServiceProvider;
        byte[] cryptedData = rsa.Encrypt(key.Key, false);
        //string data = Convert.ToBase64String(cryptedData);

        //byte[] encryptedKey = EncryptedXml.EncryptKey(key.Key, rsa, true);

        EncryptedKey ek = new EncryptedKey();
        ek.CipherData = new CipherData(cryptedData);
        ek.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSA15Url);

        //EncryptedData edkey = new EncryptedData();
        //string data1 = Convert.ToBase64String(encryptedKey);
        //edkey.CipherData.CipherValue = System.Text.Encoding.Unicode.GetBytes(data);

        rsa.Clear();

        XmlDocument encryptedAssertion = new XmlDocument();

        // Add name spaces
        XmlDeclaration xmlDeclaration = encryptedAssertion.CreateXmlDeclaration("1.0", "UTF-8", null);
        XmlElement encryptedRoot = encryptedAssertion.DocumentElement;
        encryptedAssertion.InsertBefore(xmlDeclaration, encryptedRoot);

        XmlElement encryptedAssertionElement = encryptedAssertion.CreateElement("saml", "EncryptedAssertion", "urn:oasis:names:tc:SAML:2.0:assertion");
        encryptedAssertion.AppendChild(encryptedAssertionElement);

        string xml = edElement.GetXml().OuterXml;
        XmlElement element = AddPrefix(xml, "xenc", "http://www.w3.org/2001/04/xmlenc#");
        var encryptedDataNode = encryptedAssertion.ImportNode(element, true);
        encryptedAssertionElement.AppendChild(encryptedDataNode);

        xml = ek.GetXml().OuterXml;
        element = AddPrefix(xml, "xenc", "http://www.w3.org/2001/04/xmlenc#");
        var encryptedKeyNode = encryptedAssertion.ImportNode(element, true);
        encryptedAssertionElement.AppendChild(encryptedKeyNode);

        var root = document.DocumentElement;
        var node = root.OwnerDocument.ImportNode(encryptedAssertionElement, true);
        root.RemoveChild(assertion);
        root.AppendChild(node);

    }

Once assertion is encrypted.. this is what it will look like:

<samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
        xmlns:xenc="http://www.w3.org/2001/04/xmlenc#" Destination="https://aviva-rpt.distribution-technology.com" ID="_fba2f5af-a430-8001-5cb8-9714f3aeb4bc"
IssueInstant="2015-02-04T16:32:33.446Z" Version="2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" >
 <saml:Issuer Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity">https://www.client.sds</saml:Issuer>
 <samlp:Status>
  <samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success" />
 </samlp:Status>
 <saml:EncryptedAssertion>
  <xenc:EncryptedData>
   <xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#aes256-cbc"/>
   <xenc:CipherData>
    <xenc:CipherValue>zjAgkZ=</xenc:CipherValue>
   </xenc:CipherData>
  </xenc:EncryptedData>
  <xenc:EncryptedKey>
   <xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5"/>
   <xenc:CipherData>
    <xenc:CipherValue>DyA22==</xenc:CipherValue>
   </xenc:CipherData>
  </xenc:EncryptedKey>
 </saml:EncryptedAssertion>
</samlp:Response>


text:
Q: CSS Transition Width Right to Left I am have made a heading (the word Welcome) that reveals itself once the page has loaded (onload="").
Fiddle in case the code below doesn't work.

function animate() {
  document.getElementById("mainText").style.width = "100%";

}
#mainText {
  margin: 0px;
  display: inline-block;
  font-size: 100px;
  width: 0%;
  transition: width 2s;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: clip;
}

Welcome

The CSS and Plain JS work fine but I want the word "Welcome" to be revealed right side first and then moving along, so from the e to the W, instead of how it currently is, which opens left to right.
I have tried text align: right;, but this doesn't change anything.
I preferably don't want to use any jQuery, if the solution is a JS one.
An example of what the desired look should be, half way though the transition:

A: You can use the clip-path property to clip parts of the element so they are not visible. This property can also be animated to reveal the element again, using the forwards keyword in the animation so it stays in it's 'revealed' end state.
The inset takes values that are in order: from-top, from-right, from-bottom, from-left.

#text {
  margin: 0;
  font-size: 100px;
  animation: reveal 2s forwards;
}

@keyframes reveal {
  from {
    clip-path: inset(0 0 0 100%);
  }
  to {
    clip-path: inset(0 0 0 0);
  }
}

Welcome

A: Yes, it is possible using Transitions and Positions:

window.onload = function () {
  document.querySelector("h1").classList.add("active");
};
h1 {
  overflow: hidden;
  display: inline-block;
  position: relative;
}
h1 .mask {
  position: absolute;
  transition: all 0.5s linear;
  left: 0;
  top: 0;
  bottom: 0;
  right: 0;
  background-color: #fff;
}
h1.active .mask {
  right: 100%;
}

Welcome

I just wrote an article about this - CSS Transitions & JavaScript for Animated Entry Effects. Hope it is useful... :)

A: One option is transform: translate with a pseudo element, and no extra element needed.

function animate() {
  document.getElementById("mainText").classList.add('show');
}
#mainText {
  position: relative;
  margin: 0px;
  display: inline-block;
  font-size: 100px;
  white-space: nowrap;
  text-overflow: clip;
  overflow: hidden;
}
#mainText::after {
  content: '';
  position: absolute;
  left: 0; top: 0;
  width: 100%; height: 100%;
  background: white;
  transition: transform 2s;
}
#mainText.show::after {
  transform: translateX(-100%);
}

Welcome

Another option, an even better solution, using the pseudo with direction and left/width.
This one work in the same way clip-path does, completely transparent against its background, as opposite to having a mask that revels the text, and with much better browser support.

function animate() {
  document.getElementById("mainText").classList.add('show');
}
body {
  background: black;
}
#mainText {
  position: relative;
  margin: 0px;
  display: inline-block;
  font-size: 100px;
  white-space: nowrap;
  color: rgba(0, 0, 0, 0);
}
#mainText::before {
  content: attr(data-text);
  position: absolute;
  left: 100%;
  top: 0;
  width: 0;
  height: 100%;
  color: white;
  direction: rtl;
  overflow: hidden;
  transition: left 2s, width 2s;
}
#mainText.show::before {
  left: 0;
  width: 100%;
}

Welcome

A: Something like this

function animate() {
  document.getElementById("overlay").style.width = "0%";

}
#mainText {
  margin: 0px;
  display: inline-block;
  font-size: 100px;
  width: 100%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: clip;
}
#overlay{
  width: 100%;
  position:absolute;
  top:0;
  left:0;
  background:#fff;
  transition: width 2s;
  height:100%;
}

Welcome

A: This will require a pseudo-element with a background on top of your heading serving as a mask. Instead of altering the inline styles I will simply add a class is-active. So everything style related can be styled via CSS.

function animate() {
  document.getElementById("mainText").className = "is-active";
}
#mainText {
  margin: 0px;
  display: inline-block;
  position: relative;
  font-size: 100px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: clip;
}

#mainText:before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  width: 100%;
  background: #FFF;
  transition: width 2s;
}

#mainText.is-active:before {
  width: 0%;
}

Welcome

A: I use Transform: translateX to achieve the desired effect.
It slides the text sideways or horizontally on the X axis.

.message {
  color: darkred;
  font-size: 30px;
  display: inline-block;
  font-weight: 100;
  font-family: sans-serif;
}

.sliding-text-1,
.sliding-text-2,
.sliding-text-3 {
  animation-name: slide;
  animation-duration: 1s;
  animation-timing-function: ease-out;
  animation-iteration-count: 1;
  animation-fill-mode: forwards;
  opacity: 0;
}

.sliding-text-2 {
  animation-delay: 2s;
  color: darkblue;
}

.sliding-text-3 {
  animation-delay: 4s;
  color: darkgreen;
}

@keyframes slide {
  from {
    transform: translateX(200px);
  }
  to {
    transform: translateX(0px);
    opacity: 1;
  }
}

Hello!

Thanks for visiting!

Have a nice day!

redpajama_set_name: RedPajamaStackExchange


text:
Q: vertical tab with Kirby Im new here, so forgive me if i make any mistakes...
I built an vertical tab for my portfolio website, based on the tutorial of w3school:
https://www.w3schools.com/howto/howto_js_vertical_tabs.asp
So I changed the city names with php code referring to my project titles...
but the problem is, that when i reload my page, no tab is preselected and so the content of all project is shown.

                    <?php foreach($page->children()->listed() as $project): ?>

                        <button class="tablinks" onclick="openCity(event, '(<?= $project->title() ?>)')" id="defaultOpen"><?= $project->title() ?></button>

                    <?php endforeach ?>

            <?php foreach($page->children()->listed() as $project): ?>

                <div class="col-8 tabcontent" id="(<?= $project->title() ?>)">

<?= $project->title() ?>

            <?php endforeach ?>

I think the problem ist, that i have to select only the first project and put the defaultOpen id to it and then select all the other projects.
but im not sure how to code that in php...
i'd be very happy if you could help me and sorry for these very basic questions
thanks
cian

A: Pages in a collection have an isFirst() method you can use to check whether they are at the first position (Kirby docs).
If you only want the first child to have the defaultOpen id, you could use it like this:
<?php foreach($page->children()->listed() as $project): ?>
  <button
    <?= $project->isFirst() ? 'id="defaultOpen"' : '' ?>
    class="tablinks"
    onclick="openCity(event, '(<?= $project->title() ?>)')">
      <?= $project->title() ?>
  </button>
<?php endforeach ?>


text:
Q: onDetachedFromWindow Never get Called for a View Hi I have created a Custom Button Class by extending the Button class.
I had overridden the onAttachedToWindow and onDetachedFromWindow methods. Now the problem is onDetachedFromWindow never invoked.
Below is the use case.

*

*Launch Activity Containing your Custom Button class.

*Click on Home Button. Now you are on Home Screen of Your mobile.

*onDetachedFromWindow not called.

We should get callback when activity is no longer visible to the user. since activity lost it's window and no more attached to window.
Can anyone please help regarding this issue?

A: You want to override onWindowVisibilityChanged(int visibility).
Mainly you'd be interested in visibility = VISIBLE and visibility = GONE.

A: you can just override onPause() in your activity,and do things in it.this function will be called when your activity is no longer visible to the user


text:
Q: Properties of entire functions of which the $n$-derivatives have uncountably many zeros Let $f$ be an entire function and $$A = \{z \in \mathbb C: f^{(n)} (z) = 0 \text{ for some positive integer } n\}.$$
Then what can we say about the function $f$ if $A$ is uncountable?

A: The zeroes of an analytic function are isolated;  and any uncountable subset of the plane has an accumulation point. So, there is some $n $ with $f^{(n)}=0$, and thus $f $ is a polynomial of degree  $n-1$ or less.


text:
Q: React API manager with Caching, Retries and Fallback end points What's the best way to get API that supports Fallback end points (multiple)?
useQuery supports caching and retries but not fallback end points out of the box. Axios also looks like it doesn't support secondary end points.


text:
Q: Why is this bootstrap drop down not working? I know there are a lot of other similar questions and I have tried most of them, but nothing seems to work. It just does not expand to show the dropdown items.
I have included this in the head
 <link href="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">

And I have this

                 John W

New project

Settings

Profile

Sign out

A: If you're using Bootstrap 4 you need to use data-toggle="dropdown" rather than data-bs-toggle="dropdown".

                 John W

New project

Settings

Profile

Sign out

data-bs- was added to Bootstrap 5 only I believe.


text:
Q: Grouping a dataset into time intervals then counting many columns within each period My data set comes from a process control system with various digital inputs created by logical switching functions (recorded as 'alarms').  Each event changes the state of the input from 0 to 1 which is recorded as a "N" or "Y" character in the dataset, thus:
tstamp             alarm0   alarm1  alarm2  alarm3  alarm4...alarm204
2015-10-01 16:23:06 N       N       N       N       N
2015-10-01 16:23:36 N       N       N       N       N
2015-10-01 16:24:06 Y       Y       N       Y       N
2015-10-01 16:24:36 Y       N       N       Y       N
2015-10-01 16:25:06 N       Y       N       Y       N
2015-10-01 16:25:36 N       N       N       N       N

...etc, producing ~1m rows per year.
My first aim is to count the number of "Y" within a given period (say hourly or daily) and to compare that with the frequency of events from other similar periods using a heatmap or similar.   My second aim is to identify the number of times an alarm switches from 0 to 1, ie to determine if an event occurs infrequently and persists for a long period or if it occurs frequently for a short period.
I've cut the dataset into suitable time periods using...
cut(Mydf$tstamp,breaks="hour")

and I'm able to count "Y"s in the entire dataset using...
apply(X=Mydf,2,FUN = function(x) length(which(x=="Y")))

I've been unable to cut and count the the dataset when grouped by tstamp where breaks = 'hour' or 'week' or 'month'.
I've been trying to use ddply {plyr} to cut the dataset into time periods then count the instances of "Y" within each time period however this has been unsuccessful.
Here's my sample .csv dataset 1000 rows x 80 cols (~ 175kb)...
    http://1drv.ms/1HsdY75
library(plyr)

# Read in the data files...
Mydf <- read.csv("C:/.../Mydf_small.csv")

# convert tstamp from "factor" class to "POSIXct" class (requires plyr      package)
Mydf$tstamp <- as.POSIXct(Mydf$tstamp) # turn tstamp into a time format that can be evaluated
Mydf$timebrk <- cut(Mydf$tstamp,breaks="hour") # set the time interval to  count the number of active alarms in
mylevels <- unique(Mydf$timebrk)

# example... this counts all instances of "Y" regaldless of mylevel...
MyCount <- apply(X=Mydf,2,FUN = function(x) length(which(x=="Y")))
MyCount

# want to count instances of "Y" within mylevel (...but this doesn't work)
ddcount <- ddply(.data=Mydf,.variables=mylevels,.fun = function(x) length(which(x=="Y")))
ddcount

Any assistance on these matters appreciated...


text:
Q: Closing own question
Possible Duplicate:
How can a question be closed by a single (non-moderator) user?

I've noticed a few people closing their own question as "off-topic", like here, here and here.  I didn't even know you could close your question by yourself, and it seems strange that it's happening at all.
Did I miss some new announcement?
Edit: Actually I see that these are very old questions, so now I'm even more confused.  Also there are many more examples, just do a search on SO for closed:1.

A: Voting to close your own question as off-topic seems pointless to me.  If I thought the question was off-topic, I wouldn't have posted it in the first place.
If the community thinks I posted a question that is off-topic, I just delete it.  If I really want an answer to my question, I may let the community close it down, to give it time to attract some answers.  But I never vote to close my own question.
There was one exception here on meta where a question I posted was no longer relevant, and it had already attracted some good answers and a close vote for being no longer relevant, so I threw my own close vote onto the pile.


text:
Q: InvalidSignatureException Sending POST request to AWS Kinesis from SQL I'm trying to send data to my kinesis stream from SQL but I'm only able to get back the error.
{
    "__type": "InvalidSignatureException",
    "message": "The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details."
}

My key & secret are correct as I've done a successful test in Postman.
Here is my function for creating the Authentication header...
ALTER FUNCTION [dbo].[CreateAuth]
(
    @awsAccessKey NVARCHAR(MAX),
    @awsSecretKey NVARCHAR(MAX),
    @content NVARCHAR(MAX),
    @dateTime Datetime
)
RETURNS VARCHAR(MAX)
AS
BEGIN

    DECLARE @awsRegion NVARCHAR(MAX) = 'eu-west-2';
    DECLARE @awsService NVARCHAR(MAX) = 'kinesis';
    DECLARE @timeStamp NVARCHAR(16) = FORMAT(@dateTime, 'yyyyMMddTHHmmssZ');
    DECLARE @scope NVARCHAR(MAX) = FORMAT(@dateTime, 'yyyyMMdd') + '/'+@awsRegion+'/'+@awsService+'/aws4_request'

    DECLARE @x_amz_content_sha256 NVARCHAR(MAX);
    DECLARE @hexbin VARBINARY(max) =  HASHBYTES('SHA2_256 ',@content);

    SET @x_amz_content_sha256 = LOWER(CONVERT([varchar](512), @hexbin,2))

    -- CANONICAL REQUEST
        DECLARE @CanonicalRequest NVARCHAR(MAX) = '';
        -- HTTP verb
        SET @CanonicalRequest += 'POST' + CHAR(13)
        -- URL
        SET @CanonicalRequest += 'kinesis.eu-west-2.amazonaws.com' + CHAR(13)

        -- QUERYSTRING (must be sorted alphbetically)
        SET @CanonicalRequest += '' + CHAR(13)

        -- HEADERS (must be sorted alphbetically)
        SET @CanonicalRequest += 'content-type:application/x-amz-json-1.1' + CHAR(13)
        SET @CanonicalRequest += 'host:kinesis.eu-west-2.amazonaws.com' + CHAR(13)
        SET @CanonicalRequest += 'x-amz-content-sha256:' + @x_amz_content_sha256 + CHAR(13)
        SET @CanonicalRequest += 'x-amz-date:' + @timeStamp + CHAR(13)
        SET @CanonicalRequest += 'x-amz-target:' + 'Kinesis_20131202.PutRecord' + CHAR(13)

        -- SIGNED HEADERS
        DECLARE @signedheaders NVARCHAR(MAX) = 'content-type;host;x-amz-content-sha256;x-amz-date;x-amz-target'
        SET @CanonicalRequest += @signedheaders + CHAR(13)

        -- HASHED PAYLOAD
        SET @CanonicalRequest += @x_amz_content_sha256

        DECLARE @CanonicalRequestHexbin VARBINARY(max) = HASHBYTES('SHA2_256 ',@CanonicalRequest);

    -- STRING TO SIGN
        DECLARE @stringToSign NVARCHAR(MAX) = '';
        SET @stringToSign += 'AWS4-HMAC-SHA256' + CHAR(13)
        SET @stringToSign += @timeStamp + CHAR(13)
        SET @stringToSign += @scope + CHAR(13)
        SET @stringToSign += LOWER(CONVERT([varchar](512), @CanonicalRequestHexbin,2))

    -- CALCULATE SIGNATURE
        DECLARE @DateKey VARBINARY(64);
        DECLARE @DateRegionKey VARBINARY(64);
        DECLARE @DateRegionServiceKey VARBINARY(64);
        DECLARE @SigningKey VARBINARY(64);
        DECLARE @Signature VARBINARY(64);

        SET @DateKey                = dbo.HMAC('SHA2_256',CONVERT(VARBINARY(MAX), 'AWS4'+@awsSecretKey),CONVERT(VARBINARY(MAX),FORMAT(@dateTime, 'yyyyMMdd')))
        SET @DateRegionKey          = dbo.HMAC('SHA2_256', @DateKey,                CONVERT(VARBINARY(MAX),@awsRegion))
        SET @DateRegionServiceKey   = dbo.HMAC('SHA2_256', @DateRegionKey,          CONVERT(VARBINARY(MAX),@awsService))
        SET @SigningKey             = dbo.HMAC('SHA2_256', @DateRegionServiceKey,   CONVERT(VARBINARY(MAX),'aws4_request'))

        SET @Signature = dbo.HMAC('SHA2_256',@SigningKey,CONVERT(VARBINARY(MAX),@stringToSign));

    --BUILD Authorization
    DECLARE @AuthValue NVARCHAR(MAX) = '';
    SET @AuthValue += 'AWS4-HMAC-SHA256 Credential=' + @awsAccessKey + '/'+ @scope
    SET @AuthValue += ',SignedHeaders=' + @signedheaders
    SET @AuthValue += ',Signature=' + LOWER(CONVERT([varchar](512), @Signature,2))

    RETURN @AuthValue

And here is the call to kinesis
-- Open the connection.
    EXEC @ret = sp_OACreate 'MSXML2.ServerXMLHTTP', @token OUT;
    IF @ret <> 0 RAISERROR('Unable to open HTTP connection.', 10, 1);

-- Send the request.
    EXEC @ret = sp_OAMethod @token, 'open', NULL, 'POST', @url, 'false';
    SET @auth = dbo.CreateAuth('MYACCESSKEY','MYSECRETKEY',@postData, @datetime)
    EXEC @ret = sp_OAMethod @token, 'setRequestHeader', NULL, 'Authorization', @auth

    PRINT @auth
    PRINT ''

    DECLARE @hexbin VARBINARY(max) =  HASHBYTES('SHA2_256 ',@postData); --hash data
    DECLARE @x_amz_content_sha256 NVARCHAR(MAX) = LOWER(CONVERT([varchar](512), @hexbin,2)) -- get hex of hashed data
    EXEC @ret = sp_OAMethod @token, 'setRequestHeader', NULL, 'content-type', @contentType;
    EXEC @ret = sp_OAMethod @token, 'setRequestHeader', NULL, 'host', 'kinesis.eu-west-2.amazonaws.com';
    EXEC @ret = sp_OAMethod @token, 'setRequestHeader', NULL, 'x-amz-content-sha256', @x_amz_content_sha256;
    EXEC @ret = sp_OAMethod @token, 'setRequestHeader', NULL, 'x-amz-date', @xAmzDate;
    EXEC @ret = sp_OAMethod @token, 'setRequestHeader', NULL, 'x-amz-target', @xAmzTarget;
    EXEC @ret = sp_OAMethod @token, 'send', NULL, @postData;

-- Handle the response.
    EXEC @ret = sp_OAGetProperty @token, 'status', @status OUT;
    EXEC @ret = sp_OAGetProperty @token, 'statusText', @statusText OUT;
    EXEC @ret = sp_OAGetProperty @token, 'responseText', @responseText OUT;

-- Show the response.
    PRINT 'Status: ' + @status + ' (' + @statusText + ')';
    PRINT 'Response text: ' + @responseText;

-- Close the connection.
    EXEC @ret = sp_OADestroy @token;
    IF @ret <> 0 RAISERROR('Unable to close HTTP connection.', 10, 1);

The HMAC function I'm using is this one... https://gist.github.com/rmalayter/3130462
I've verified that the results produced with the SHA2_256 & HMAC functions are correct using https://codebeautify.org/
I'm pretty sure I'm doing everything according to... https://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html and https://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-header-based-auth.html
I'm lost as to what to look try next.

A: I've solved it now. There were a number of problems aside from my lazy hard coding.

*

*CanonicalURI should just be '/'. - thanks @AlwayLearning.

*Changed all string variables to VARCHAR rather than NVARCHAR, this was causing incorrect hashing.

*The date used for the @datekey also needs to be a VARCHAR CONVERT(VARCHAR(MAX),FORMAT(@dateTime, 'yyyyMMdd')) as the FORMAT() function returns a NVARCHAR.

And I found this site which was very helpful http://aws-signature.com.s3-website-us-west-2.amazonaws.com/
Successful function now looks like this...
ALTER FUNCTION [dbo].[CreateAuth]
(
    @awsAccessKey VARCHAR(MAX),
    @awsSecretKey VARCHAR(MAX),
    @content VARCHAR(MAX),
    @dateTime Datetime,
    @awsRegion VARCHAR(MAX),
    @awsService VARCHAR(MAX),
    @CanonicalRequestURI VARCHAR(MAX),
    @host VARCHAR(MAX),
    @xAmzTarget VARCHAR(MAX),
    @contentType VARCHAR(MAX)
)
RETURNS VARCHAR(MAX)
AS
BEGIN
    DECLARE @date VARCHAR(8) = FORMAT(@dateTime, 'yyyyMMdd')
    DECLARE @timeStamp VARCHAR(16) = FORMAT(@dateTime, 'yyyyMMddTHHmmssZ');
    DECLARE @scope VARCHAR(MAX) = @date + '/'+@awsRegion+'/'+@awsService+'/aws4_request'

    DECLARE @x_amz_content_sha256 VARCHAR(MAX);
    DECLARE @hexbin VARBINARY(max) =  HASHBYTES('SHA2_256 ',@content);

    SET @x_amz_content_sha256 = LOWER(CONVERT([varchar](MAX), @hexbin,2))

    -- CANONICAL REQUEST
        DECLARE @CanonicalRequest VARCHAR(MAX) = '';
        -- HTTP verb
        SET @CanonicalRequest += 'POST' + CHAR(10)
        -- URL
        SET @CanonicalRequest += @CanonicalRequestURI + CHAR(10)

        -- QUERYSTRING (must be sorted alphbetically)
        SET @CanonicalRequest += '' + CHAR(10)

        -- HEADERS (must be sorted alphbetically)
        SET @CanonicalRequest += 'content-type:' + @contentType + CHAR(10)
        SET @CanonicalRequest += 'host:' + @host + CHAR(10)
        SET @CanonicalRequest += 'x-amz-content-sha256:' + @x_amz_content_sha256 + CHAR(10)
        SET @CanonicalRequest += 'x-amz-date:' + @timeStamp + CHAR(10)
        SET @CanonicalRequest += 'x-amz-target:' + @xAmzTarget + CHAR(10)
        SET @CanonicalRequest +=  CHAR(10)

        -- SIGNED HEADERS
        DECLARE @signedheaders VARCHAR(MAX) = 'content-type;host;x-amz-content-sha256;x-amz-date;x-amz-target'
        SET @CanonicalRequest += @signedheaders + CHAR(10)

        -- HASHED PAYLOAD
        SET @CanonicalRequest += @x_amz_content_sha256

        DECLARE @CanonicalRequestHexbin VARBINARY(max) = HASHBYTES('SHA2_256 ',@CanonicalRequest);

    -- STRING TO SIGN
        DECLARE @stringToSign VARCHAR(MAX) = '';
        SET @stringToSign += 'AWS4-HMAC-SHA256' + CHAR(10)
        SET @stringToSign += @timeStamp + CHAR(10)
        SET @stringToSign += @scope + CHAR(10)
        SET @stringToSign += LOWER(CONVERT([varchar](MAX), @CanonicalRequestHexbin,2))

    -- CALCULATE SIGNATURE
        DECLARE @DateKey VARBINARY(MAX);
        DECLARE @DateRegionKey VARBINARY(MAX);
        DECLARE @DateRegionServiceKey VARBINARY(MAX);
        DECLARE @SigningKey VARBINARY(MAX);
        DECLARE @Signature VARBINARY(MAX);

        SET @DateKey                = dbo.HMAC('SHA2_256',CONVERT(VARBINARY(MAX), 'AWS4'+@awsSecretKey),CONVERT(VARBINARY(MAX),@date))
        SET @DateRegionKey          = dbo.HMAC('SHA2_256', @DateKey,                CONVERT(VARBINARY(MAX),@awsRegion))
        SET @DateRegionServiceKey   = dbo.HMAC('SHA2_256', @DateRegionKey,          CONVERT(VARBINARY(MAX),@awsService))
        SET @SigningKey             = dbo.HMAC('SHA2_256', @DateRegionServiceKey,   CONVERT(VARBINARY(MAX),'aws4_request'))

        SET @Signature = dbo.HMAC('SHA2_256',@SigningKey,CONVERT(VARBINARY(MAX),@stringToSign));

    --BUILD Authorization
    DECLARE @AuthValue VARCHAR(MAX) = '';
    SET @AuthValue += 'AWS4-HMAC-SHA256 Credential=' + @awsAccessKey + '/'+ @scope
    SET @AuthValue += ',SignedHeaders=' + @signedheaders
    SET @AuthValue += ',Signature=' + LOWER(CONVERT([varchar](MAX), @Signature,2))

    RETURN @AuthValue

END


text:
Q: How to build a interface that displays an image bitmap and it's histogram in Racket? I'm trying to build a GUI where I have the possibility to load an image (and draw it on a canvas) and to make a histogram out of it's pixels when I press a button (I want to display the histogram on the GUI too, but only for the "red" pixels for simplicity).
Initially I put a black background for the image canvas and afterwards the canvas is updated based on what image is loaded (using the load-button). In the same time I also save the pixels into input-buffer.
I couldn't find a way to embedded the plot onto the GUI, so for now I only plot it in the REPL.
I assume that the images are 256x256 (but anything else is fine as it can be modified afterwards). Here's the code of what I've tried so far:
#lang racket/gui
(require plot)

(define SIZE 256)

(define frame
  (new frame%
       [label "BMP"]
       [x 0] [y 0]
       [width 1000] [height 500]))

(define main-panel
  (new horizontal-panel%
       [parent frame]))

;---------------FOR THE IMAGE---------------------

(define input-panel
  (new vertical-panel%
       [parent main-panel]))

;in order to put a black fundal for the bitmap initially
(define input-bitmap (make-bitmap SIZE SIZE))
(define input-dc (send input-bitmap make-dc))
(send input-dc set-background (make-color 0 0 0))
(send input-dc clear)

(define input-canvas
  (new canvas%
       [parent input-panel]
       [paint-callback
        (λ (canvas dc)
          (send dc draw-bitmap input-bitmap 0 0))]))

;update canvas with the new loaded image
;also save the pixels in the input-buffer
(define input-buffer (make-bytes (* SIZE SIZE 4)))
(define load-button
  (new button%
       [parent input-panel]
       [label "Load file"]
       [callback
        (λ (button event)
          (define path (get-file))
          (when path
            (set! input-bitmap (read-bitmap path))
            (send input-canvas on-paint)
            (send input-bitmap get-argb-pixels 0 0 SIZE SIZE input-buffer)))]))

;---------------FOR THE HISTOGRAM---------------------

;builds a list of SIZE elements holding the frequency of each pixels
;e.g.: '((0 100) (1 50) ... (255 75)) ->this is given to the histogram
(define (get-red-pixels buffer)
  (define red-pixels
    (for/list ([i (in-range 1 (* SIZE SIZE 4) 4)])
      (bytes-ref buffer i)))
  (map list (build-list SIZE values)
       (for/list ([i SIZE])
         (length (filter (λ(x) (= i x)) red-pixels)))))

(define (plot-histogram)
  (plot (discrete-histogram (get-red-pixels input-buffer)
                            #:y-max 100
                            #:color 1 #:line-color 1)))

(define histogram-panel
  (new vertical-panel%
       [parent main-panel]))

(define refresh-button
  (new button%
       [parent histogram-panel]
       [label "Refresh"]
       [callback
        (λ (button event)
          ;not plotting when pressed..
          ;also I want the plot to be on the interface
          (plot-histogram))]))

(send frame show #t)

In order for the histogram to be plotted I must explicit call (plot-button) as the refresh-button doesn't plot it. Anyway I am trying to put the plot inside the interface not in a new window, however I'm stuck. Please let me know if anything is unclear.

A: I made some changes in your old code and this seems to work:
(check load-button and get-red-pixels, rest of code should be the same)
#lang racket/gui
(require plot)

(define SIZE 256)

(define frame
  (new frame%
       [label "BMP"]
       [x 0] [y 0]
       [width 1000] [height 500]))

(define main-panel
  (new horizontal-panel%
       [parent frame]))

;---------------FOR THE IMAGE---------------------

(define input-panel
  (new vertical-panel%
       [parent main-panel]))

;in order to put a black fundal for the bitmap initially
(define input-bitmap (make-bitmap SIZE SIZE))
(define input-dc (send input-bitmap make-dc))
(send input-dc set-background (make-color 0 0 0))
(send input-dc clear)

(define input-canvas
  (new canvas%
       [parent input-panel]
       [paint-callback
        (λ (canvas dc)
          (send dc draw-bitmap input-bitmap 0 0))]))

;update canvas with the new loaded image
;also save the pixels in the input-buffer
(define input-buffer (make-bytes (* SIZE SIZE 4)))

(define load-button
  (new button%
       [parent input-panel]
       [label "Load file"]
       [callback
        (λ (button event)
          (let ((path (get-file)))
            (when path
              (set! input-bitmap (make-object bitmap% path))
              (send input-canvas on-paint)
              (send input-bitmap get-argb-pixels 0 0 SIZE SIZE input-buffer)
              (plot/dc (discrete-histogram (get-red-pixels input-buffer)
                                           #:y-max SIZE
                                           #:color 1
                                           #:line-color 1)
                       (send histogram-canvas get-dc)
                       0 0
                       SIZE SIZE))))]))

;---------------FOR THE HISTOGRAM---------------------

;builds a list of SIZE elements holding the frequency of each pixels
;e.g.: '((0 100) (1 50) ... (255 75)) ->this is given to the histogram
(define (get-red-pixels buffer)
  (let ((red-pixels
         (for/list ([i (in-range 1 (* SIZE SIZE 4) 4)])
           (bytes-ref buffer i))))
    (map list
         (build-list SIZE values)
         (for/list ([i SIZE])
           (count (λ(x) (= i x)) red-pixels)))))

(define histogram-panel
  (new vertical-panel%
       [parent main-panel]))

(define histogram-canvas
  (new canvas%
       [parent histogram-panel]))

(send frame show #t)


text:
Q: How to call AlertDialog inside AlertDialog? I have this code:
public class Example
{
 String sp,st;
 SQLiteDatabase database, database2;
 void func()
 {
 new AlertDialog.Builder(view.getContext())
    .setIcon(android.R.drawable.ic_dialog_alert)
    .setTitle("Confirm")
    .setMessage("Are you sure?")
    .setPositiveButton("Yes", new DialogInterface.OnClickListener()
    {
    @Override
    public void onClick(DialogInterface dialog, int which) {
      String st = editTextSt.getText().toString();
      String sp = editTextSp.getText().toString();
      database2 = new SQLiteDbHelper(this);
      database = database2.getWritableDatabase();
      ContentValues values = new ContentValues();
      values.put(SQLiteDbHelper.COLUMN_NAME_SP, sp);
      values.put(SQLiteDbHelper.COLUMN_NAME_ST, st);
      long insertId = database.insert(SQLiteDbHelper.TABLE_NAME, null, values);
      //I would like to call it here
    }})
    .setNegativeButton("No", null)
    .show();

 }

I would like to call this AlertDialog inside the AlertDialog above:
new AlertDialog.Builder(this)
                .setMessage("Saved!")
                .setNeutralButton("OK", null)
                .show();

How can I do it?
If I just put it where I want to, I get error that "The constructor AlertDialog.Builder(new DialogInterface.OnClickListener(){}) is undefined".

A: Try this:
new AlertDialog.Builder(Example.this)
                .setMessage("Saved!")
                .setNeutralButton("OK", null)
                .show();

This will work assuming that the class Example is an Activity.
i.e.:
public class Example extends Activity

Otherwise, use this:
new AlertDialog.Builder(view.getContext())
                .setMessage("Saved!")
                .setNeutralButton("OK", null)
                .show();

A: Once you are inside the ClickListener object this is going to refer to that object rather than the activity like it does outside of there assuming Example is an Activity which it may not be based on your code.
To fix it you just need to use a different way to get the context to pass in to your builder consstructor.
to create the first builder that you use you did it like this:
new AlertDialog.Builder(view.getContext())

using view.getContext() to get the context that you need. You should be able to do it the same way with your second builder.


text:
Q: VueJS: How to render several elements per cycle? I need to render the next list:

some content

some content

  ...

some content

some content

Can I use the "v-for" directive for this?

A: Use a range v-for in combination with a template tag.

  <template v-for="n of 99">
    <li :class="`type-${n}-0`">some content

    <li :class="`type-${n}-1`">some content

  </template>

Here is an example.

console.clear()

new Vue({
  el: "#app"
})

    <template v-for="n of 99">
      <li :class="`type-${n}-0`">{{`type-${n}-0`}}

      <li :class="`type-${n}-1`">{{`type-${n}-1`}}

    </template>

Note: if you need to support IE, you will either need to use the template tag in a string template (or single file component) or use a render function instead.  because template is not supported in IE.


text:
Q: Create 3 random int params with sum of 100 I need to create a player with 3 properties:

*

*Life (must be a random integer from 1 to 100);

*Attack (must be a random integer from 1 to 100);

*Defense (must be a random integer from 1 to 100);
But the total sum of all properties must be 200 (Life + Attack + Defense = 200). No more or less.
I've tried to make something like this:

public function initPlayer(){
        $life = random_int(1, 100);
        $attack = random_int(1, 100);
        $lifeAttack = $life + $attack;
        if($lifeAttack >= 100) {
            $defense = 200 - $lifeAttack;
        } else {
            $defense = random_int(1, 100);
        }
        echo $life . '-' . $attack . '-' . $defense;
    }

But it works correctly only if the sum of two params is equal or more than 100.

A: That's basically because $lifeAttack must be greater than 100 to meet all your conditions. You could recurse when it isn't, like this:
public function initPlayer()
{
    $life = random_int(1, 100);
    $attack = random_int(1, 100);
    $lifeAttack = $life + $attack;
    if($lifeAttack >= 100) {
        $defense = 200 - $lifeAttack;
    } else {
       $this->initPlayer();
       return;
    }
    echo $life . '-' . $attack . '-' . $defense;
}

Of course you can do the same without recursion. Perhaps it would be nice to return these values from the function?

A: If the three values of life + attack + defense are to be real random numbers in the range 1..100, then the total is only 200 with a very low probability.
When the third value is calculated, it is no longer random.
The correct solution is: The 3 values have to be determined again and again until the total is equal 200.
for($sum = 0;$sum !== 200;){
   $life = random_int(1, 100);
   $attack = random_int(1, 100);
   $defense = random_int(1, 100);
   $sum = $life + $attack + $defense;
}

var_dump($life,$attack,$defense,$life + $attack + $defense);

Output example:
int(65) int(77) int(58) int(200)

A: check this algorithm, that produce an array of values in a defined range with a defined sum :
function generate_values($total, $range_min, $range_max, $nb_values) {
    // impossible conditions
    if($total < $range_min*$nb_values || $total > $range_max*$nb_values) {
        return null;
    }

    $values = [];

    for($i=0; $i<$nb_values; $i++) {
        $current_total = $total - array_sum($values);

        // the last value is the remaining total
        $value = $current_total;
        if( $i < ($nb_values-1) ) {
            $current_range_min = max($range_min, $current_total - ($nb_values-$i-1)*$range_max);
            $current_range_max = min($range_max, $current_total - ($nb_values-$i-1)*$range_min);
            $value = rand($current_range_min, $current_range_max);
        }

        array_push($values, $value);
    }

    shuffle($values);
    return $values;
}

// test with your needs
for($i=0; $i<10; $i++) {
    $values = generate_values(200, 1, 100, 3);
    var_dump($values, array_sum($values));
}

A: This would be a case where only 2 numbers would be I inherently random. I would recommend first randomizing life from 1 to 100, and set the upper bound for attack as 100 -$life (I.e. 1 to 100 - $life) . Finally, defense would be pre-determined as 100 - lifeAttack.


text:
Q: .extractText() returns "invalid literal for decimal" I'm coding something which will read PDFs online and return a set of keywords that are found in the document. However I keep running into a problem with the extractText() function from the PyPDF2 package.
Here's my code to open the PDFs and read it:
x = myurl.pdf
if ".pdf" in x:
remoteFile = urlopen(Request(x, headers={"User-Agent": "Magic-Browser"})).read()
memoryFile = StringIO(remoteFile)
pdfFile = PyPDF2.PdfFileReader(memoryFile, strict=False)
num_pages = pdfFile.numPages
count = 0
text = ""
while count < num_pages:
    pageObj = pdfFile.getPage(count)
    count += 1
    text += pageObj.extractText()

The error that I keep running into on the extractText() line goes like this:
Traceback (most recent call last):
  File "errortest.py", line 30, in <module>
    text += pageObj.extractText()
  File "/anaconda2/lib/python2.7/site-packages/PyPDF2/pdf.py", line 2595, in extractText
    content = ContentStream(content, self.pdf)
  File "/anaconda2/lib/python2.7/site-packages/PyPDF2/pdf.py", line 2674, in __init__
    self.__parseContentStream(stream)
  File "/anaconda2/lib/python2.7/site-packages/PyPDF2/pdf.py", line 2706, in __parseContentStream
    operands.append(readObject(stream, None))
  File "/anaconda2/lib/python2.7/site-packages/PyPDF2/generic.py", line 98, in readObject
    return NumberObject.readFromStream(stream)
  File "/anaconda2/lib/python2.7/site-packages/PyPDF2/generic.py", line 271, in readFromStream
    return FloatObject(num)
  File "/anaconda2/lib/python2.7/site-packages/PyPDF2/generic.py", line 231, in __new__
    return decimal.Decimal.__new__(cls, str(value))
  File "/anaconda2/lib/python2.7/decimal.py", line 547, in __new__
    "Invalid literal for Decimal: %r" % value)
  File "/anaconda2/lib/python2.7/decimal.py", line 3872, in _raise_error
    raise error(explanation)
decimal.InvalidOperation: Invalid literal for Decimal: '99.-72'

Would be great if someone could help me out! Thanks!

A: There is too little information to be certain, but PyPDF2 (and now pypdf) improved a lot in 2022. You will probably just need to upgrade to the latest version of pypdf.
If you encounter a bug in pypdf again, please open an issue: https://github.com/py-pdf/pypdf
A good bug ticket contains (1) your pypdf version (2) the code + PDF document that caused the issue.


text: Q: Can we use Tab menu in Widget Android I have created widget for my application and I need to add two tabs one is Favorite another is Recent List. Is there any way to use tab in widget. I searched in google but I cant any tutorials.


text:
Q: Getting different results with arithmetic problems by following different approaches? The below question is from where my doubt had arisen.
1st Problem:
Question: A, B, C can do a job in 10, 20, and 40 days respectively. In how many days A can complete the job if he is assisted by B and C on every third day?
Answer:
A's one-day work = 1/10
B's one-day work = 1/20
C's one-day work =1/40
(A+B+C)'s one day work = 1/10 + 1/20 + 1/40 = 7/40
Work done in three days will be the sum of A's two-day work and (A+B+C)'s one day work.
A's two-day work = 1/10 * 2 = 1/5
Therefore, the work is done in three days = 1/5 + 7/40 = 3/8
3/8 part of the job is done in 3 days.
The entire job will be done by A in  = 3 * 8/3 = 8 days.
I decided to follow the same approach from the above question to another same kind of my own problem.
2nd Problem:
My Question: A, B can do a job in 11, 11/3 days respectively. In how many days A can complete the job if he is assisted by B on every second day?
My Own approach to this Question [Correct me if I'm wrong]:
A's one day of work = 1/11
B's one day of work = 3/11
So,
On 1st day, 1/11 work is done
On 2nd day, 4/11 work is done [Since B's work is also added on 2nd day]
On 3rd day, 6/11 work is done totally [Since 1st day's work(1/11) + 2nd day's work(4/11) + 3rd day's work(1/11)]
On 4th day, 10/11 work is done totally [Since 1st day's work(1/11) + 2nd day's work(4/11) + 3rd day's work(1/11) + 4th day's work(4/11)]
On 5th day, 11/11 work is done totally [Since 1st day's work(1/11) + 2nd day's work(4/11) + 3rd day's work(1/11) + 4th day's work(4/11) + 5th day's work(1/11)]
So from this, we can know that it takes 5 days to complete the work by A. Simple right?
But when I follow the previous method from the first problem to this problem, it gives me different answers. I'll show it below,
A's one-day work = 1/11
B's one-day work = 3/11
(A+B)'s one day work = 1/11 + 3/11 = 4/11
Work done in two days will be the sum of A's one-day work and (A+B)'s one day work.
A's one-day work = 1/11
Therefore, the work is done in two days = 1/11 + 4/11 = 5/11
So, 5/11 part of the job is done in 2 days.
The entire job will be done by A in  = 2 * 11/5 = 22/5 days.
When I follow my own method I get 5 days which I think is the correct answer to my problem which is 5 days. But when I follow the previously given method, I get a different answer which is 22/5 days.
But both the 1st problem and the 2nd problem is of similar type except the numbers and some minor things are different.
My doubt is If my own answer which is 5 days from the 2nd problem is right means then, Is the 1st problem wrong or the approach to the first problem is wrong?
But the 1st problem's solution is quite famous all over the internet.

A: As @JMoravitz suggests in the comments the provided approach for question $1$ is not usually valid. The method assumes that the work done during any given day is constant and is given by the average work done during the period after which the working pattern repeats. But this not true as you found using the valid method you suggest. The suggested method is only valid if it's the case that after an integer multiple of this working period the job is done. This is because the average work done over every day considered would be equal to the periodic average in this case.


text:
Q: How to customize web-app (pages and UI) for different customers We have an ASP.NET web-application which has become difficult to maintain, and I'm looking for ideas on how to redesign it. It's an employee administration system which can be highly customized for each of our customers. Let me explain how it works now:
On the default page we have a menu where a user can select a task, such as Create Employee or View Timesheet. I'll use Create Employee as an example.
When a user selects Create Employee from the menu, an ASPX page is loaded which contains a dynamically loaded usercontrol for the selected menuitem, e.g. for Create Employee this would be AddEmployee.ascx
If the user clicks Save on the control, it navigates to the default page.
Some menuitems involve multiple steps, so if the user clicks Next on a multi-step flow then it will navigate to the next page in the flow, and so on until it reaches the final step, where clicking Save navigates to the default page.
Some customers may require an extra step in the Create Employee flow (e.g. SecurityClearance.ascx) but others may not.
Different customers may use the same ASCX usercontrol, so in the AddEmployee.OnInit we can customize the fields for that customer, i.e. making certain fields hidden or readonly or mandatory.
The following things are customizable per customer:

*

*Menu items

*Steps in each flow (ascx control names)

*Hidden fields in each ascx

*Mandatory fields in each ascx

*Rules relating to each ascx, which allows certain logic to be used in the code for that customer

The customizations are held in a huge XML file per customer, which could be 7500 lines long.
Is there any framework or rules-engine that we could use to customize our application in this way? How do other applications manage customizations per customer?

A: If your regular data is held in a database I'm not entirely sure why you'd want to have all of that customer specific information in an xml file.  Move it into the database.
Next, there are many different kinds of rules engines out there.  Considering you're using asp.net you might want to look at Windows Workflow for at least some of this.  You might read the following: http://karlreinsch.com/2010/02/05/microsoft-rule-engines/
A long time ago I used a product called Haley Rules to drive a c# web app.  It controlled everything from the screens that were available right down to the fields that appeared and whether they were required or not.  It took awhile to get the team on board with how it worked, but once that happened bringing on a new client was extremely simple.  Haley was since gobbled up by Oracle, but was probably the absolute best one out there.
Others you might be interested in are NxBRE and even nCalc.  NxBRE is an actual rules engine which is a port of one built for java.  nCalc on the other hand isn't a rules engine per se.  However, if you can express your logic in simple boolean statements then it is extremely fast.  I'm currently using this to drive page flow in one of our applications.
Some commercial ones include: FlexRule, iLog

A: Your existing rule engine tool supports your web application, which means it meets your needs already. You can use other "Rule Engine" like MS work flow, but IMO it can also end with a hard to maitain situation.
Let's say there is registration portal. It collects general user infomation and save them into database. Simple. we build one protal for one client with several ASCXs and Rules.Then for another client,we add more rules and more controls to these ASCXs. Working in this way, sooner or later we will reach the final straw client. At that time the code base is hard to maitain and devs lost themselves in lots of rules. It is what happened to me.
So to me, it is not about which Rule engine to use.
Then How?
I have raised a question, and one of the answer makes sense to me( thought not a picked answer). In this answer, the guy mentioned what kind of company you are. In your question it is more like which department you are or do you want to seperate your dev teams.
If you are in a archetect teams, build a framework with a rule engine. Create a basic registraion portal as a sample portal.Make DAO,BO decoupled with UI (Seperate layers).
If you are in a customise teams, create customised user control (dont reuse these user control in basic version). What you will recreate is just UI, you can still use DAO,BO as they are not defined in user control, they are at other layers. In this way you get the freedom to define your client specified rules without worring about contaminating other clients rules or introducing new bugs to other client's registrations.
Just realise it is not like an answer to your question. Anyway it is my thoughts after limited xp of working on a engine rule based ,multi-clients web application.

A: When the individual customer needs are so wildly different that shared functionality represents less than 50% of the features for a given customers needs, then there are really only two major ways to handle this:
Writing a custom page for each individual client
This tends to sometimes be an unsavory option for both technical folk as well as business and sales folk.  It can also be unsavory if the client realizes that you are performing a lot of custom development to meet their needs.
Technical considerations
As a developer, high maintainability is one of the central goals that we should strive to accomplish, so writing custom pages for individual customers is counter to this goal.  Assume that a common feature must be added that should affect all customers, now this change must be manually implemented for all clients and tested for each client that has a seperate implementation for that page.  If you have a number of clients then this can simply be untenable over time.
Business considerations
From the business perspective as an ISV, we like to build a product, which is typically more involved than just the software itself.  Selling a software product implies that as a vendor, we have a single package that can fulfill all of the customers needs with minimal to no customization to the core of the product itself.
When product customizations need to occur to accomodate a client, then the product may be a poor fit, or may have just been poorly planned.  It may be that the solution that is being sold cannot actually be considered a product at all, but is simply being marketed that way.  The software business can be tricky like this and is why product owners and sales people make the big bucks because this winning formula for success in selling software can be extraordinarily tricky.  If you don't market it right, or form a product idea correctly then you may not sell or you may sell and be unable to deliver on promises.
Client considerations
All clients like to feel that they are getting a good deal, and when they buy a software product they want to believe that all of their needs are being met out of box.  This is why software products sell more readily and easily than just custom software development, even when the client needs are so inherently specific that no such product could ever exist off the shelf.
If the client finds that you are performing a good deal of custom software development for their needs alone then they lose faith that your product ever had the ability to deliver and that they will end up paying dearly for it in the long run to cover those custom development costs.
When is this a good idea
If the software is in a niche market with a small amount of customers and limited opportunity for growth, then custom web page development for specific features is probably the best choice.
XML based layout and rules engine
Basically you would identify core functionality to be built into pages, and anything customer specific should be defined through a custom layout and rules engine that allows client needs to be customized outside of the code base.
The technical design considerations for this are that
Technical considerations
The client needs at this point become a schema change through XML rather than en expensive maintainability nightmare of a code change.  Controlling layouts through XML to define your view, XML to tie in your model, and rules to define your controller will allow for a solid architecture that will scale as your business grows and also maintain loose coupling, high cohesion, and high maintainability.  These XML documents can be easily maintained through a NoSQL or even traditional RDBMS systems.
Business considerations
Limiting targeted releases to accomodate customers bolsters the strength and scalability of the product as a whole, and leaves the business confident that they have the ability to grow rapidly in a wild and volatile market.  Some disadvantages are the increased complexity of the application and product itself, and the considerations towards increased initial development time and the higher costs associated with this.
Client considerations
Clients can feel confident that their needs are being met through the product without significant cutomization and that their requests and changes can be rapidly accomodated.

A: Having said that over-flexibility is the cause of many over-complications in software, can you imagine a framework so flexible as to allow you to offer infinite flexibility to your customers?
That said, I would suggest writing a DSL, rather than using XML, for a customisation rules engine.
You can use ANTLR to create a DSL from scratch, or you can write a DSL on top of Boo, which means you don't have to make trivial decisions like code-formatting and operator precedence, you just get to work with what's unique to your domain problem.
This should simplify your current rules engine dramatically and also be more extensible in the future. As an added advantage, if you get it right, it will be more reader-friendly for the end-user, so that they can view their own customisation rules and confirm their correctness.

A: 7500 lines of code (XML) is alarming - I think you have to ask yourself how much benefit your users get from the customisation and how much it costs you to provide it. Personally I'd start by trying to reduce the customisation as much as possible.
Next I'd move whatever customisation is left into a database as very simple data (something similar to name value pairs but for each customer and perhaps allowing a type field and a sequence number). Provide a nice simple web interface to this and check that all values entered are valid. The aim being to make it so easy to change that eventually your customers will be able to do it. You could also put system defaults into this structure so you can change the default behaviour via the database.
create table CustomerSettings(
   customerId         int,
   type               varchar(20),
   name               varchar(20),
   value              varchar(20),
   sequence           int null
);

insert CustomerSettings ( 0, "FORMAT", "emp_no", "^[0-9]+$" ); // default

insert CustomerSettings ( 123, "MENU","main_menu","hire people",1

insert CustomerSettings ( 123, "MENU","main_menu","fire people",2

insert CustomerSettings ( 123, "HIDE","salary",null, null );

insert CustomerSettings ( 123, "FORMAT","emp_no","^[A_E][0-9]+$", null );

etc, etc
The web app would first load all the values for a customer or, if no value is present, it would load the default. A new customer would then just run just using the defaults. You could add settings on the fly until the customer is happy.
The data per customer should hopefully be much smaller. Using defaults where possible.
Mike
PS please forgive the formatting, I couldn't make head nor tail out of the info on how to show code in a post.


text:
Q: Android-ActionBar-PullToRefresh-Type R is already defined error I'm currently facing this issue when I add ActionBar-PullToRefresh library in Eclipse. The error I get is The Type R is already defined.
Steps how I added the library:

*

*Got all files from git.

*Since I'm targeting Android 2.3.* I need appcompat library too. So    I've imported actionbarcompat from the extras folder.

*Next I imported the library. The library is dependent on    SmoothProgressBar, so I imported that too.

*The actionbarcompat which I imported in step 2 needed the library    (Step 3) and support-v7-appcompat library. I added both as    dependency.

*Next in My Project I added actionbarcompat as a dependency and    cleaned project.

This is when I started getting the error. In the gen folder I've the R.java for the following libraries:
android.support.v7.appcompat
fr.castorflex.android.smoothprogressbar
uk.co.senab.actionbarpulltorefresh.extras.actionbarcompat
uk.co.senab.actionbarpulltorefresh.library

I'm facing the error in R.java of  uk.co.senab.actionbarpulltorefresh.library. Did I go wrong in adding any of the libraries?
P.S: I can resolve this error by disabling Java Builder but by doing that I'm getting a new problem for which I've raised another question Here (I asked that question first, then one of the members asked me to raise question for this issue as well).
Any help is appreciated!

A: this error seems to appear because u might be building a library more than once , check this SO Answer I hope this will help


text:
Q: Fetch X-GM-THRID X-GM-MSGID for all unseen messages using python when i try to fetch X-GM-THRID and X-GM-MSGID for each mail using uid via for loop it fetch only 1st unseen mail X-GM-THRID and X-GM-MSGID rest are none. why and how to fetch the X-GM-THRID and X-GM-MSGID of all unseen mail one by one.

mail.select("inbox") # connect to inbox.
result, data = mail.search(None, "UNSEEN")
ids = data[0] # data is a list.
id_list = ids.split() # ids is a space separated string
print(id_list)
for uid in id_list:
result, data = mail.uid('fetch',uid, '(X-GM-MSGID)')
print(data)
pattern= re.compile(r'\d{19}')
pattern=pattern.search (str(data[0]))
MSG_ID=('X-GM-MSGID: %s'%pattern)
print(MSG_ID)

result, data = mail.uid('fetch',uid,'(X-GM-THRID)')
pattern= re.compile(r'\d{19}')
pattern=pattern.search(str(data[0]))
THR_ID=('X-GM-THRID: %s'%pattern)
print(THR_ID)
output:
[b'23 (X-GM-MSGID 1661402455636098002 UID 85)']
X-GM-MSGID: <re.Match object; span=(17, 36), match='1661402455636098002'>
X-GM-THRID: <re.Match object; span=(17, 36), match='1661402455636098002'>
[None]
X-GM-MSGID: None
X-GM-THRID: None
[None]
X-GM-MSGID: None
X-GM-THRID: None
[None]
X-GM-MSGID: None
X-GM-THRID: None
[None]
X-GM-MSGID: None
X-GM-THRID: None

rather than none i need msgid and thrid of each mail sepreately.
how to achieve this.


text:
Q: looping through columns passed to an existing macro in DBT I have a macro that creates a boolean field with the values 0 and 1. The 0 and 1 are generated due to the fact that I am comparing values from two columns i.e s1, s2

*

*s1 - represents a column name that needs to be compared of a given column passed as parameter 1 column

*s2 - represents the second column that needs to be compared

s1 columns: x, y ,z
s2 columns: x2, y2, z2
x column is compared with x2 column, similarly y column with y2 column and z with z2 column.
column

*

*8 values are passed to both s1 and s2 to make the comparison hence, the below macro is being called 8 times:

macro:
{% macro create_value(s1, s2) -%}
if(ifnull({{s1}} != {{s2}},true) is true,1,0) as {{ s1 | replace('xx','new') }}
{% endmacro %}

Calling the macro:
compute_value as (
select *,
    {{ create_value('xx_col1','xx_col2') }},
    {{ create_value('xx_col3','xx_col4') }},
    {{ create_value('xx_col5','xx_col6') }},
    {{ create_value('xx_col7','xx_col8') }},
    {{ create_value('xx_col9','xx_col10') }},
    ...
    {{ create_value('xx_col15','xxcol_16') }},
from
table
)

running the above macro will create the 8 new columns that are:

*

*new_col1

*new_col3

*new_col5

*new_col7

*new_col9

*new_col11

*new_col13

*new_col15

Once I have these 8 columns, I have to calculate the sum of the values
Till this point I have everything. Currently, I am doing it manually by writing all the column names generated from the first macro and summing them up (see below):
select
*,
    new_col1 + new_col3 + new_col5 + new_col7 ....... + new_col15 AS new_value

from compute_value

Technically, I am getting my answers right, what I would like to automate is the calculation of the column new_value.
My first macro creates 8 columns and then I have to manually write the names of all 8 columns and sum them up. Is there a way that the sum of these columns can be automated as well i.e removing this part:
    new_col1 + new_col3 + new_col5 + new_col7 ....... + new_col5 AS new_value

currently, the complete code looks like this:
compute_value as (
select *,
    {{ create_value('xx_col1','xx_col2') }},
    {{ create_value('xx_col3','xx_col4') }},
    {{ create_value('xx_col5','xx_col6') }},
    {{ create_value('xx_col7','xx_col8') }},
    {{ create_value('xx_col9','xx_col10') }},
    ...
    {{ create_value('xx_col15','xxcol_16') }},
from
table
),

select
*,
    new_col1 + new_col2 + new_col3 + new_col4 + new_col5 + new_col6 + new_col7 + new_col8 AS new_value

from compute_value

I need the 8 boolean values as well as the total sum of those values as the output

A: You could DRY this up a little by creating a jinja list, storing the names of the columns in that list, and looping over it twice. With only 8 columns, this might not save you much typing, and would arguably be harder to read, but it would look like this:
{% set cols = [("xxcol1", "col2"), ("xxcol3", "col4"), ("xxcol5", "col6"), ("xxcol7", "col8"), ...] %}
select
    {% for col1, col2 in cols %}
    {{ create_value(col1, col2) }},
    {% endfor %}
    {% for col1, _ in cols -%}
    {{ col1 | replace('xx','new_') }}{% if not loop.last %} +{% endif %}
    {%- endfor %} as new_value,
...

Compiles to:
select
    {{ create_value(xxcol1, col2) }},
    {{ create_value(xxcol3, col4) }},
    {{ create_value(xxcol5, col6) }},
    {{ create_value(xxcol7, col8) }},
    new_col1 + new_col3 + new_col5 + new_col7 as new_value,
...

If you RDBMS does not support lateral column aliases, you have to rework your macro to pull out the aliasing:
{% macro create_value(s1, s2) -%}
if(ifnull({{s1}} != {{s2}},true) is true,1,0)
{% endmacro %}

and then just call the macro in each loop:
{% set cols = [("xxcol1", "col2"), ("xxcol3", "col4"), ("xxcol5", "col6"), ("xxcol7", "col8"), ...] %}
select
    {% for col1, col2 in cols %}
    {{ create_value(col1, col2) }} as {{ col1 | replace('xx','new_') }},
    {% endfor %}
    {% for col1, col2 in cols -%}
    {{ create_value(col1, col2) }}{% if not loop.last %} +{% endif %}
    {%- endfor %} as new_value,
...


text:
Q: Converting store procedure data to a csv. I am trying to figure out how to use the commas and quotations for the fields that are empty sb.AppendLine("Employee Id,First Name,Last Name,Email,Username,Password,Role,Group Name,Country Code, Supervisor Id, Hire Date, Birth Date");

for (int i = 0; i < dt.Rows.Count; i++)
{
    String[] empid = dt.Rows[i]["EmpId"].ToString().Split(new Char[] { '-' });
    sb.AppendLine(Convert.ToInt32(empid[0]).ToString("000000") + "," + dt.Rows[i]["FirstName"] + "," + dt.Rows[i]["LastName"].ToString().Replace(",", " ") +
         ",," + dt.Rows[i]["Email"] + ",reward," + dt.Rows[i]["Role"] + ",CCCC," + ",," + ",," + dt.Rows[i]["EmployeeHireDate"] + "," + dt.Rows[i]["EmployeeBirthDate"]);
}

email field needs to be empty,
username needs to be the email,
country code needs to be empty,
supervisor id needs to be empty,

A: Replace this segement:
+ ",CCCC," + ",," + ",," +

with this:
+ ",CCCC,,," +

But you'll really do MUCH better with a dedicated csv library, of which there are several good options on NuGet.
Additionally, if you're using StringBuilder because you heard it's faster, remember that faster is relative. StringBuilder is faster than string concatenation for this kind of work, but if you're ultimately going to writing to a network stream, file, or web response you'll do even better using a StreamWriter


text:
Q: `execvp()` seems to not be completing the path search TL;DR -- what sorts of things might cause an execvp call to not fully function/ search the path properly?
I'm on the tail end of building a rudimentary shell with some quality of life features that I've added over time e.g. history, alias's, and completions. I built those features on top of a functional shell that had a working $PATH search for execution e.g. typing in "ls -la" produced the desired behavior. As you might imagine, I accomplished this just using execvp. (This is written in C if it's not already clear)
I have not changed any of my tokenizing logic and have ensured that the file name is correct; in particular, execvp was producing the desired behavior before I had added these features to my REPL. echo "hello" still produces a tokenized char **xyz and the first token is indeed echo, null-terminated, and so on. That is, my call still looks like, with variables filled-in, ... execvp("echo", argv); after which I call perror, which should only trigger when something has gone awry. Each time I just run the above command, though, since I've added in these features, it returns a failure with the no such file or directory --- before I added these features in though, the behavior was as desired. I'll note, though, that running /bin/echo "hello" runs as expected. Examples are WLOG.
I'm not sure where I should even start looking for errors, and my Google-fu has been mostly fruitless: any suggestions?
I'm initially going to omit code because it totals to several hundred lines and a MWE would not be particularly minimal in addition to my desires to keep this general rather than very particular to my code, though I'm not sure what's causing this. My repository is public and up-to-date, and I'm happy to post any code here.
EDIT:
I knew I wasn't explicitly editing the PATH variable, etc., but this block of code was the problem:
  // Grab $PATH from env
  char *pathvar = getenv("PATH");

  if (pathvar) {
    char *path;
    int i;

    // tokenize on colon to get paths
    // then use that immediately to
    // scandir, and add everything in
    // there to the completions system

    path = strtok(pathvar, ":");
    while (path) {
      struct dirent **fListTemp;
      int num_files = scandir(path, &fListTemp, NULL, alphasort);
      // only adding the names that are completely composed of
      // lower case letters; completions are done using a naive
      // Trie Node structure that only supports lowercase letters
      // for now... e.g. g++ does not work, and the '+' leads to
      // a seg-fault. Same holds for . and ..
      for (i = 0; i < num_files; i++) {
        char *curr = fListTemp[i]->d_name;
        if (strcmp(curr, ".")==0 || strcmp(curr, "..")==0){
          continue;
        } else if (notalpha(curr)) {
          continue;
        } else {
          str_tolower(curr);
          tn_insert(completions, curr);
        }
      }
      for (i = 0; i < num_files; i++) {
        free(fListTemp[i]);
      }
      free (fListTemp);
      path = strtok(NULL, ":");
    }
  } else {
    fprintf(stderr, "{wsh @ init} -- $PATH variable could not be found?");
  }

A: Note that

   The getenv() function returns a pointer to the value in the
   environment, or NULL if there is no match.

so my original code was indeed tampering with the PATH variable. The solution I came up with quickly was just to create a copy of that string and use that to parse through the PATH instead:
  // Grab $PATH from env
  char *pathvar = getenv("PATH");
  char *pathvar_cpy = strcpy(pathvar_cpy, pathvar);

  if (pathvar_cpy) {
    char *path;
    int i;
    path = strtok(pathvar_cpy, ":");
    while (path) {
      // Scan directory
      struct dirent **fListTemp;
      int num_files = scandir(path, &fListTemp, NULL, alphasort);

      for (i = 0; i < num_files; i++) {
        char *curr = fListTemp[i]->d_name;
        if (strcmp(curr, ".")==0 || strcmp(curr, "..")==0){
          continue;
        } else if (notalpha(curr)) {
          continue;
        } else {
          str_tolower(curr);
          tn_insert(completions, curr);
        }
      }
      for (i = 0; i < num_files; i++) {
        free(fListTemp[i]);
      }
      free (fListTemp);
      path = strtok(NULL, ":");
    }
  } else {
    fprintf(stderr, "{wsh @ init} -- $PATH variable could not be found?");
  }


text:
Q: How nodejs handles global module being used in multiple applications running in parallel? I have created very simple nodejs hello application.
//hello.js
#!/usr/bin/env node

var config = require('./config');

console.log(config.getConfig());
config.setConfig(Math.floor(Math.random() * 6) + 1 );
console.log(config.getConfig());

var readconfig = require('./readconfig');

console.log("Hi !! I am glad to see you again");

//config.js
var config;

exports.getConfig = function(){
    return config;
}

exports.setConfig = function(c){
    config = c;
}

//package.json
"bin": {
    "hello": "hello.js"
  }

//readconfig.js
var config = require('./config');

console.log(config.getConfig());
config.setConfig(Math.floor(Math.random() * 6) + 1 );
console.log(config.getConfig());

I had installed my sample module globally. And when I run 'hello' command from different folders, or multiple times from the same folder, I ever get;
undefined
2 //some random number
2 //some random number
4 //some random number
Hi !! I am glad to see you again

From the above response it looks like, nodejs cache a local module but maintain different copy for each application context. However I am not sure.
Can somebody plz explain how exactly nodejs handles global modules and separate their variables from all the applications using it?

A: Each node application is completely independent of the others.  They are separate processes, completely separate modules, each loading independently, sharing no data.
Within a given application, a module loaded with require() is cached.  The first time the module is loaded with require() it is loaded from disk and initialized.  From then on, any subsequent requests to load that module just return the same module handle that was previously loaded - it doesn't load it again or run it again.
The require() module loader maintains a cache.  Once a module is loaded it is then in the cache and any subsequent requests to load it (from with that specific application) just return the cached module handle.


text:
Q: Electronic data interchange development over the years I am writing a bachelor thesis on EDI and I would like to mention ebXML over there too, but it seems there's very small amount of information over the internet, is it still used these days?
Also part of the question I have to address is how technologies like (RPC, WebServices, ebXML and EDI) developed the data interchange.

A: You may be using the wrong search terms. Look for ebMS (ebXML messaging services), AS2 and AS4.


text:
Q: Can we interrupt our service if we use CI/CD I am a consultant for a large organization. I work with CI/CD. Now sometimes the organization actually interrupts its services for upgrading the systems - I never do that with my own apps (where I use travis-ci and google appengine). I have ten years uninterrupted service with my own app. Is it alright to name our function "continuous" when we actually interrupt our services?

A: Yes. The 'Continuous' refers to the automation of the processes rather than zero downtime.
Having said that. I would assume that:

*

*If there is significant downtime they wont want to continuously deploy. (it would cause lots of outages)

*There is still a manual step somewhere (a fully automated process is usually fast

You can imagine a working CD setup with downtime if the downtime is very short and doesn't affect the gross functionality of the overall product


text:
Q: Chisel: How to wait for signal assertion in ChiselScalatestTester? I want to create a testbench for my Chisel-based module. So I'm using ChiselScalatestTester to create the testbench. My module use a custom protocol to communicate with the outside world. So inside the test class I have to wait for some signals to be asserted from DUT. Here is an example from my test class:
...
while (dut.io.outBusy) {
    dut.clock.step()
}
...

Would someone please help me implement this?

A: Looks like you almost have it. Try
...
while (dut.io.outBusy.peek().litToBoolean) {
  dut.clock.step()
}
...


text:
Q: Clearing or Deleting a Ruby PStore I've been experimenting with PStore to hold relatively large numbers of hash values using:
 require "pstore"
 store = PStore.new("data.pstore")

Seeing as this is stored in a file full of now-useless data, how do I clear or delete the "store" programatically? Obviously I could just delete the store.pstore file, but what i'm looking for is the PStore equivalent of:
DELETE FROM store WHERE 1=1;

A: What you're looking for is delete:
store.transaction { store.delete(key) }

store = PStore.new("data.pstore")
#=> #<PStore:0x007fd67f35a040 @abort=false, @filename="data.pstore", @lock=#<Thread::Mutex:0x007fd67f359f28>, @thread_safe=false, @ultra_safe=false>
store.transaction { store[:foo] = :bar }
# => #<PStore:0x007fd67f35a040 @abort=false, @filename="data.pstore", @lock=#<Thread::Mutex:0x007fd67f359f28>, @rdonly=false, @table={:foo=>:bar}, @thread_safe=false, @ultra_safe=false>
store.transaction { store.delete(:foo) }
#=> :bar
store
#=> #<PStore:0x007fd67f35a040 @abort=false, @filename="data.pstore", @lock=#<Thread::Mutex:0x007fd67f359f28>, @thread_safe=false, @ultra_safe=false

If you want to truncate the store you can iterate over the roots and delete them in a transaction:
store.transaction do
  store.roots.each do |root|
    store.delete(root)
  end
end


text:
Q: My sword is swinging not the way I want it to go? I just added a sword swinging script to my sword, and it works fine. But I just want my sword to go forwards. It goes side to side, and random ways to when I turn. Is there any way I can fix this? Thank you.
using UnityEngine;
using System.Collections;

public class Sword : MonoBehaviour {

private float swingDuration = 0.5f;
private float swingSpeed = 0.22f;

private float swingTimer = 0f;
private bool swinging = false;
private Vector3 startRot;

void Start () {
    startRot = transform.eulerAngles;
}

// Update is called once per frame
void Update () {
    if (Input.GetMouseButtonDown(0) && !swinging) {
        swinging = true;
    }

    if (swinging) {
        swingTimer += Time.deltaTime;

        if (swingTimer < (swingDuration / 2)) {
            transform.eulerAngles = Vector3.Lerp(startRot, new Vector3(0, 0, 1), swingSpeed);
        }

        if (swingTimer > (swingDuration / 2)) {
            transform.eulerAngles = Vector3.Lerp(transform.eulerAngles, startRot, swingSpeed);
        }

        if (swingTimer > swingDuration) {
            swingTimer = 0f;
            swinging = false;
        }
    }
  }
}

A: Vector3.Lerp has this signature:
public static function Lerp(from: Vector3, to: Vector3, t: float): Vector3;

Where t is within [0..1], For t=0 you get from for t=0 you get to ad a result. I.e.the "swing" effect comes from the third argument which is constant in your case. a reasonable argument would be something like
swingTimer *2 / swingDuration

or (for the "back swing")
(swingTimer-swingDuration/2) *2 / swingDuration

Another problem is that you change the fromangle (1 argument) instead of the 3rd argument:
 transform.eulerAngles = Vector3.Lerp(transform.eulerAngles, startRot, swingSpeed);

This causes the "random" effect, which you experienced.


text:
Q: a template declaration cannot appear at block scope (template class in main) here is my code:
#include <iostream>
using namespace std;
template<typename T>
class List
{
    public:
        List(T);
};
template<typename T>
class A: public List<T>
{
    public:
};
int main()
{   //my problem is here...!
    A a(10);
}

I don't know how to declare this class in main and use it.
In this case, I have this error:

missing template arguments before 'a'

and when I write:
template(typename T)
   A a(10);

I give this error:

g++ -std=c++11 -c main.cpp
   error: a template declaration cannot appear at block scope
       template
       ^~~~~~~~

A: Since u didn't write a constructor for A, I supposed u want to use the inherited one, hence u have to provide the following line in A
using List<T>::List;

And since u used c++11, u have to provide the template arg, as follows
A<int> a(10);

If u want to make the compiler figure it out, use c++17 or c++20 and provide the following guide
template<class T> A(T)-> A<T>;

Now the full code with c++17 will be
template<typename T>
class List
{
public:
    List(T) {}
};
template<typename T>
class A: public List<T>
{
public:
    using List<T>::List;
};
template<class T> A(T)-> A<T>;
int main()
{   //No problem here...!
    A a(10);
}

And with c++11 will be
template<typename T>
class List
{
public:
    List(T) {}
};
template<typename T>
class A: public List<T>
{
public:
    using List<T>::List;
};

int main()
{   //No problem here...!
    A<int> a(10);
}

A: std::vector

is templated, so you call it as std::vector<int> for example. As such, your declaration should be A<int> a(10);


text:
Q: How to get the number of satellites using GNSS Status in Kotlin? private  lateinit mGnssStatus: GnssStatus
private  lateinit mGnssStatusCallback: GnssStatus.Callback
private  lateinit mGnssStatusBuild: GnssStatus.Builder
//Gnss initialization to display the number of the satellite
val mgnssStatus=// how can I initialize GnssStatus correctly to get satellite number
val Satellitetxt=findViewById<TextView(R.id.Satellitetxt)
Satellitetxt.text = mgnssStatus.satelliteCount.toString()

I am trying to use "satelliteCount"; however I don't know how to initialize GnssStatus. Any help please?

A: You need to create GnssStatus with GnssStatus.Builder, and then you call your object with getSatelliteCount()


text:
Q: Merge field watermark - Microsoft Word 2013 I want to add a conditional Watermark in a word document using merge field. Is there any way to accomplish this? Is there any way to use merge field condition like below to add "DRAFT" watermark? or any other way to use a condition to make a watermark visible on the document? I am using Microsoft Word 2013. Thanks in advance for your help guys.
{ IF"{MERGEFIELD SampleField}"="Yes" "DRAFT" "" }

A: Yes, it's possible, with the caveat that you can't use Word's built-in Insert/Watermark functionality. An "If" conditional can work only with textual content. Word's built-in Watermarks are "WordArt" - which places an object in the document.
But you can use the Text Box drawing tool (as in Insert/Text Box/Draw Text box) to create the "container" for the watermark text in the document Header. It can be positioned anywhere on the page; make sure you set the text wrap formatting to "Behind text".
Insert the If field into that, with the nested mergefield and conditional statement. You need to type the watermark text and format it the way you want to have it.

A: The correct format:
{ IF { MERGEFIELD PrintCopy = 1 "ORIGINAL" "COPY" }}
Add spaces before and after the equal sign
Make sure the entire row (text above) is highlighted in grey when you click on it in the word document, otherwise it is only text once merged.


text:
Q: polars apply lambda with list comprehension like pandas: Any other better way? pandas
df['sentences'] = df['content'].str.split(pattern2)
df['normal_text'] = df['sentences'].apply(lambda x: [re.sub(pattern3, ' ', sentence) for sentence in x])

polars
df = df.with_column(pl.col('content').apply(lambda x: re.split(pattern2, x)).alias('sentences'))
df = df.with_column(pl.col('sentences').apply(lambda x: [re.sub(pattern3, ' ', sentence) for sentence in x]).alias('normal_text'))

Amy more elegant way than this?

A: You can use the .str methods instead of .apply()
.str.split() doesn't currently support regex
You should be able to emulate the behaviour with .extract_all() and .replace_all()
pattern2 = r"HI+"
pattern3 = r"\s"
replacement = ""

df = pl.DataFrame({
   "content": [
      "o neHItw oHIIIIIth ree",
      "fo urHIIfi veHIIIIs ix"
   ]
})

df.with_column(
   pl.col("content")
     .str.extract_all(rf".*?({pattern2}|$)")
     .alias("sentences")
)
shape: (2, 2)
┌────────────────────────┬─────────────────────────────────────┐
│ content                | sentences                           │
│ ---                    | ---                                 │
│ str                    | list[str]                           │
╞════════════════════════╪═════════════════════════════════════╡
│ o neHItw oHIIIIIth ree | ["o neHI", "tw oHIIIII", "th ree... │
├────────────────────────┼─────────────────────────────────────┤
│ fo urHIIfi veHIIIIs ix | ["fo urHII", "fi veHIIII", "s ix... │
└────────────────────────┴─────────────────────────────────────┘

You can use .arr.eval() to process each item in the list.
df.with_column(
   pl.col("content").alias("normal_text")
     .str.extract_all(rf".*?({pattern2}|$)")
     .arr.eval(
        pl.all()
          .str.replace_all(pattern2, "")
          .str.replace_all(pattern3, replacement),
        parallel=True)
)
shape: (2, 2)
┌────────────────────────┬─────────────────────────┐
│ content                | normal_text             │
│ ---                    | ---                     │
│ str                    | list[str]               │
╞════════════════════════╪═════════════════════════╡
│ o neHItw oHIIIIIth ree | ["one", "two", "three"] │
├────────────────────────┼─────────────────────────┤
│ fo urHIIfi veHIIIIs ix | ["four", "five", "six"] │
└────────────────────────┴─────────────────────────┘

If you want to keep the sentence column - you can split it up into 2 steps:
df.with_column(
   pl.col("content")
     .str.extract_all(rf".*?({pattern2}|$)")
     .arr.eval(
        pl.all().str.replace_all(pattern2, ""),
        parallel=True)
   .alias("sentences")
).with_column(
   pl.col("sentences").arr.eval(
      pl.all().str.replace_all(pattern3, replacement),
      parallel=True)
   .alias("normal_text")
)
shape: (2, 3)
┌────────────────────────┬────────────────────────────┬─────────────────────────┐
│ content                | sentences                  | normal_text             │
│ ---                    | ---                        | ---                     │
│ str                    | list[str]                  | list[str]               │
╞════════════════════════╪════════════════════════════╪═════════════════════════╡
│ o neHItw oHIIIIIth ree | ["o ne", "tw o", "th ree"] | ["one", "two", "three"] │
├────────────────────────┼────────────────────────────┼─────────────────────────┤
│ fo urHIIfi veHIIIIs ix | ["fo ur", "fi ve", "s ix"] | ["four", "five", "six"] │
└────────────────────────┴────────────────────────────┴─────────────────────────┘

Performance comparison

Create larger strings for a basic comparison.
N = 1000
df = pl.DataFrame({
   "content": [
      "o neHItw oHIIIIIth ree" * N,
      "fo urHIIfi veHIIIIs ix" * N] * N
})

.apply()
%%time
(df.with_column(pl.col('content').apply(
      lambda x: re.split(pattern2, x)).alias('sentences'))
   .with_column(pl.col('sentences').apply(
      lambda x: [re.sub(pattern3, replacement, sentence) for sentence in x])
   .alias('normal_text')))
CPU times: user 22.8 s, sys: 94.2 ms, total: 22.9 s
Wall time: 22.9 s
shape: (2000, 3)

.str
%%time
df.with_column(
   pl.col("content")
     .str.extract_all(rf".*?({pattern2}|$)")
     .arr.eval(
        pl.all().str.replace_all(pattern2, ""),
        parallel=True)
   .alias("sentences")
).with_column(
   pl.col("sentences").arr.eval(
      pl.all().str.replace_all(pattern3, replacement),
      parallel=True)
   .alias("normal_text")
)
CPU times: user 4.69 s, sys: 68.2 ms, total: 4.76 s
Wall time: 1.28 s
shape: (2000, 3)

Method
Time

.str
1.28s

.apply()
22.9s


text:
Q: How do I print from the Reader app on Windows 8? I was delighted to discover that the Reader app that comes with Windows 8 could open PDF files. However, I cannot find a way to print from that app. When I right-click there is nothing on the bottom bar that lets me print a document.
How do I print a PDF file from the Reader app?

A: To print from a Modern UI app that supports printing:

*

*open the Charms bar on the right side of the screen by pointing to the very top right or bottom right corner (or press Windows+C), then select Devices:

*click your printer:

*choose whichever options you require and click Print:

A: Just type Ctrl + P with your keyboard and the following print dialog appears on the right side.
Or swipe to the right side and select your printer under devices (thanks cable729).

A: Detailed steps with a tablet also in the article below.
http://windows8depot.blogspot.co.uk/2015/05/print-in-reader-windows-8.html


text:
Q: Environment variables undefined using dotenv I have a file which connects to Contentful using my specific space and accessToken. Recently, I decided to hide the keys into an .env file using the dotenv package. This is what my file looks like :
import {createClient} from 'contentful';
require('dotenv').config();
//console.log('space = ', process.env.CONTENTFUL_SPACE);

const client = createClient({
  space: process.env.CONTENTFUL_SPACE,
  accessToken: process.env.CONTENTFUL_TOKEN
});

export default client;

For some reason, the env variables are coming out as undefined. Currently, my .env file is under the root dir. This is the file structure of my project :
project
 client
  src
   service
    client.js <-- The file I pasted above
 node_modules
 .env
 package-lock.json
 package.json

Things I've tried :

*

*Uninstalled dotenv and reinstalled it

*Deleted node_modules folder and reinstalled all dependencies

*Moved .env file under service folder where the client file exists

*Used the REACT_APP_* prefix for my env variables in .env file

*Specified the path in the config call

All of these solutions came from other stackoverflow questions. I've been stuck on this for a few days circling through the solutions listed and looking for others but still haven't figured out why I'm not able to access my env variables!

A: So I tried structuring a sample project the same way you've structured it, and it didn't work. I moved the .env file under /service folder, it worked.
My guess is, requiring the dot env file should be on the main file that wraps your project (main file in the root), along with .env file.

A: Try setting a path to your .env file in the config.
const dotenv = require('dotenv');
dotenv.config({ path: '../../../.env' });

edit: config path

A: const dotenv = require('dotenv');
dotenv.config({ path: '../../.env' });

This solved my problem.

A: require("dotenv").config({
  path: path.resolve(__dirname, '../../../.env')
});

This will resolver your issue