text:
Q: Git: include part of a project into another project I have a quite difficult situation: in one project (git repo) I have a file, and I need it in another project (another git repo). Is there any clear and (as it possible) simple way to put it into my project?
It's looks like:
git-repo-1:
    lib/foo
    lib/ololo

git-repo-2:
    lib/*foo* (from repo-1)
    lib/bar
    lib/baz

My question is: 1. How can I do it? 2. How can I update the file (inc. from git-repo-1) into my repo (git-repo-2)?
p.s. Yes, a saw many pages about subtrees, but... it still not so clear for me. Any suggestions? Even instruction ;-) I'll be so appreciate for anything.
UPD: What I want: http://git-scm.com/book/en/Git-Tools-Subtree-Merging BUT! I want to get only a part of "rack" repository into my project repo.
The question is: how to split off the file I need from one repo and merge it to another?

A: extract lib/foo into a new project called common.
then include the full common project in both project 1 and 2

A: I think you have two separate questions here. The first is how to include one repo in another (which the modules or subtree features are for). The second is how to only use PART of a git repo.
I am not a git expert, but have been told by some of them that it is not really possible to only utilize portions of a repository -- because of how git works, where a lot of history and changes are stored as "deltas" (so only the portions of files that changed from one version to another are stored in a newer version... or something like that).
So... I think your best bet here is to bring down project 2 in a totally separate directory, then copy just the files you need out of there into your project 1. (Or set up some kind of symlink / alias thing so you don't have to copy them).

A: I fear you can't include only a part of another repository in yours.
To deal with that problem, I have a small script that checks out the latest version of the file I need into the current working directory.
If you use "git archive", you can retrieve the latest version from upstream :
For example :
git archive --format=tar --remote ssh://git@gitserver:7999/infra/scripts.git HEAD supplier.csv | tar xf -

git add ./supplier.csv ;

git commit -m 'Update suppliers from upstream'

A: I do not recommend to go deeply in git. In my opinion, your project must be as clear as possible.
You can do the job you need manually or using script:
cp path/to/git-repo-1/lib/foo path/to/git-repo-2/lib/
git add .
git commit -a -m 'updated lib/foo'


text:
Q: WCF not sending all data I have set up my WCF client to go through a Fiddler proxy so i can capture and analyze traffic. It turns out, my WCF client is not sending all the parameters that i have initialized.
Some of the parameter that i've initialized are not being sent. One being an example and very crucial to me is the lineOfBusiness in the lineOfBusinessList array.
I've divided the following code into 3 sections, my WCF client, the soap message that Fiddler intercepted and the soap message that i expect my WCF client to send.
My WCF Client
class Program
    {
        static void Main(string[] args)
        {

            GetProductAvailability();
        }

        public static void GetProductAvailability()
        {
            ProductAvailabilityResponseType response;
            using (ProductAvailabilityServicePortTypeClient client = new ProductAvailabilityServicePortTypeClient("ProductAvailabilityServicePortQSPort"))
            {
                client.ClientCredentials.UserName.UserName = "username";
                client.ClientCredentials.UserName.Password = "password";
                 ProductAvailabilityRequestType request = new ProductAvailabilityRequestType
                {
                    requestHeader = GetRequestHeader(),
                    serviceAddress = GetServiceAddress(),
                    responseFilterCriteria = GetFilterCriteria()
                };

                response = client.getProductAvailability(request);
            }

            if (response != null)
            {

            }
            //return null;
        }

        private static RequestHeaderType GetRequestHeader()
        {
            return new RequestHeaderType
            {
                customerInteractionType = ChannelType.WebSelfServe,
                serviceRequestUserId = "55555", //not sure, ask stevenson
                serviceConsumer = ServiceConsumerToolType.Emily,
                serviceRequestTimestamp = DateTime.Now,
                language = LanguageType.English,
                referenceID = "A24T34H3" //ask stevenson if this is necessary
            };
        }

        private static ServiceAddressSearchType GetServiceAddress()
        {
            return new ServiceAddressSearchType
            {
                addressID = "000622060",
                address = new AddressType
                {
                    provinceOrState = new ProvinceOrStateType { type = ProvinceOrStateValueType.ON }
                }
            };
        }
        private static ProductAvailabilityFilterType GetFilterCriteria()
        {
            return new ProductAvailabilityFilterType
            {
                serviceSupportInfoOnly = false,
                customerSegment = CustomerSegmentType.Residential,
                channelList = new ChannelType[1] { ChannelType.WebSelfServe },
                lineOfBusinessList = new LineOfBusinessProductType[1] {
                     new LineOfBusinessProductType{ lineOfBusiness = LineOfBusinessType.Internet }
                 },
                oneBillOffers = false,
                satelliteTechnicianRequired = false,
            };
        }
    }

What's actually being sent:
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Header>
    <ActivityId CorrelationId="ab64c2a1-7e32-448c-8d64-80fead66e566" xmlns="http://schemas.microsoft.com/2004/09/ServiceModel/Diagnostics">cb08f434-ec5e-409e-a550-a0826739aa94</ActivityId>
  </s:Header>
  <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <getProductAvailability xmlns="ca/bell/oms/autotype/productavailability">
      <requestHeader>
        <customerInteractionType xmlns="ca/bell/oms/autotype/omscommonrequest">WebSelfServe</customerInteractionType>
        <serviceRequestUserId xmlns="ca/bell/oms/autotype/omscommonrequest">55555</serviceRequestUserId>
        <serviceConsumer xmlns="ca/bell/oms/autotype/omscommonrequest">Emily</serviceConsumer>
        <serviceRequestTimestamp xmlns="ca/bell/oms/autotype/omscommonrequest">2011-06-02T16:26:13.4639736-04:00</serviceRequestTimestamp>
        <language xmlns="ca/bell/oms/autotype/omscommonrequest">English</language>
        <referenceID xmlns="ca/bell/oms/autotype/omscommonrequest">A24T34H3</referenceID>
      </requestHeader>
      <serviceAddress>
        <addressID>000622060</addressID>
        <address>
          <provinceOrState xmlns="ca/bell/oms/autotype/omscommon"/>
        </address>
      </serviceAddress>
      <responseFilterCriteria>
        <serviceSupportInfoOnly>false</serviceSupportInfoOnly>
        <channelList>
          <channel>WebSelfServe</channel>
        </channelList>
        <lineOfBusinessList>
          <lineOfBusinessProduct/>
        </lineOfBusinessList>
      </responseFilterCriteria>
    </getProductAvailability>
  </s:Body>
</s:Envelope>

The SOAP messasge I'm expecting my WCF client to send:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:prod="ca/bell/oms/autotype/productavailability" xmlns:oms="ca/bell/oms/autotype/omscommonrequest" xmlns:oms1="ca/bell/oms/autotype/omscommon">
   <soapenv:Header/>
   <soapenv:Body>
      <prod:getProductAvailability>
            <oms:requestHeader>
                <oms:customerInteractionType xmlns:n2 = "ca/bell/oms/autotype/omscommonrequest">WebSelfServe</oms:customerInteractionType>
                <oms:serviceRequestUserId xmlns:n3 = "ca/bell/oms/autotype/omscommonrequest">55555</oms:serviceRequestUserId>
                <oms:serviceConsumer xmlns:n4 = "ca/bell/oms/autotype/omscommonrequest">Emily</oms:serviceConsumer>
                <oms:serviceRequestTimestamp xmlns:n5 = "ca/bell/oms/autotype/omscommonrequest">2010-11-30T11:27:08.431-05:00</oms:serviceRequestTimestamp>
                <oms:language xmlns:n6 = "ca/bell/oms/autotype/omscommonrequest">English</oms:language>
                <oms:referenceID xmlns:n7 = "ca/bell/oms/autotype/omscommonrequest"></oms:referenceID>
            </oms:requestHeader>
         <prod:serviceAddress>
            <prod:addressID>000622060</prod:addressID>
            <prod:address>
               <oms1:provinceOrState>
                  <oms1:type>ON</oms1:type>
               </oms1:provinceOrState>
            </prod:address>
         </prod:serviceAddress>
         <prod:responseFilterCriteria>
            <prod:serviceSupportInfoOnly>false</prod:serviceSupportInfoOnly>
            <prod:customerSegment>Residential</prod:customerSegment>
            <prod:channelList>
               <prod:channel>WebSelfServe</prod:channel>
            </prod:channelList>
            <prod:lineOfBusinessList>
               <prod:lineOfBusinessProduct>
                  <prod:lineOfBusiness>Internet</prod:lineOfBusiness>
               </prod:lineOfBusinessProduct>
            </prod:lineOfBusinessList>
            <prod:oneBillOffers>false</prod:oneBillOffers>
        <prod:satelliteTechnicianRequired>false</prod:satelliteTechnicianRequired>
         </prod:responseFilterCriteria>
      </prod:getProductAvailability>
   </soapenv:Body>
</soapenv:Envelope>

A: At a guess, you are missing the DataMember attribute on some of your DataContract properties.

redpajama_set_name: RedPajamaStackExchange


text:
Q: HTML JavaScript Canvas color changing I have a small project i'm working on, and I'm completely new to HTML as well as any scripting inside.  I have some code that logically (to me) makes sense, but for some reason It's not working.  I'm using some code I found to make a drawing tool using canvas, but I'm having trouble with changing the colors with a drop down menu.  I have this code so far.

Select Tool: <select id = "selectedTool">
    <option value="rectangle">Rectangle</option>
    <option value="pencil">Pencil</option>
    <option value="line">Line</option>
</select>

Color: <select id="selectedColor">
    <option value="red">Red</option>
    <option value="blue">Blue</option>
    <option value="green">Green</option>
</select>

for my drawing function method I have:
var color_select = document.getElementById('selectedColor');
this.mousemove = function (ev) {
  if (tool.started){
    context.lineTo(ev._x, ev._y);
    var color_select = document.getElementById('selectedColor');
    if(color_select == red)
        context.strokeStyle = 'red';
    else if(color_select == blue)
        context.strokeStyle = 'blue';
    else if(color_select == green)
        context.strokeStyle = 'green';
    context.stroke();
  }
};

This completely kills the drawing tool.  below I'll post the full code just in case it's something unrelated to what I have above.
<!DOCTYPE html>

<meta charset="utf-8">
<title>Simmons Stitching v1.0.0</title>

Stitching Tool: <select id="selectedTool">
<option value="rectangle">Rectangle</option>
<option value="pencil">Pencil</option>
<option value="line">Line</option>
</select>

Color: <select id="selectedColor">
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="green">Green</option>
</select>

<canvas id="imageView" width="400" height="300">

Wrong browser for this application sucka!  Get a browser worth having!

Try one of these: Opera, Firefox, Safari, and Konqueror.

</canvas>

A: Some small changes are needed in the code. While choosing the color value you are using the following line,
      var color_select = document.getElementById('selectedColor');

Basically it will return an HTMLElementObject not the color. To get the color from the html element you need to retrieve the value of that element. Use,
 var color_select = document.getElementById('selectedColor').value;

Use this color checking for all the three tools. Use the updated code pasted below. Cheers!
<!DOCTYPE html>

<meta charset="utf-8">
<title>Simmons Stitching v1.0.0</title>

    Stitching Tool: <select id="selectedTool">
            <option value="rectangle">Rectangle</option>
            <option value="pencil">Pencil</option>
            <option value="line">Line</option>
    </select>

    Color: <select id="selectedColor">
            <option value="red">Red</option>
            <option value="blue">Blue</option>
            <option value="green">Green</option>
    </select>

    <canvas id="imageView" width="400" height="300">

Wrong browser for this application sucka!  Get a browser worth having!

Try one of these: Opera, Firefox, Safari, and                 Konqueror.

</canvas>


text:
Q: Small differences in SHA1 hashes A project I am working on uses Apache Shiro as a security framework. Passwords are SHA1 hashed (no salt, no iterations). Login is SSL secured. However, the remaining part of the application is not SSL secured. In this context (no SSL) there should be a form where a user can change the password.
Since it wouldn't be a good idea to transmit it plainly it should be hashed on the client and then transmitted to the server. As the client is GWT (2.3) based, I am trying this library http://code.google.com/p/gwt-crypto, which uses code from bouncycastle.
However, in many cases (not all) the hashes generated by both frameworks differ in 1-4(?) characters.
For instance "happa3" is hashed to
"fe7f3cffd8a5f0512a5f1120f1369f48cd6f47c2"

by both implementations, whereas just "happa" is hashed to
"fb3c3a741b4e07a87d9cb68f3db020d6fbfed00a"

by the Shiro implementation and to
"fb3c3a741b4e07a87d9cb63f3db020d6fbfed00a"

by the gwt-crypto implementation (23rd character differs).
I wonder whether there is a "correct"/standard SHA1 hashing and whether there is a bug in one of the libraries or maybe my usage of them is flawed.
One of my first thoughts was related to different encodings or strange conversions due to different transport mechanisms (RPC vs. Post). To my knowledge though (and what puzzles me most), SHA1 hashes should differ completely with a high probability if there is just a difference of a single bit. So different encodings shouldn't be the issue here.
I am using this code on the client (GWT) for hashing:
String hashed = toHex(createSHA1Hash("password"));
...
private String createSHA1Hash(String passwordString){
    SHA1Digest sha1 = new SHA1Digest();
    byte[] bytes;
    byte[] result = new byte[sha1.getDigestSize()];
    try {
        bytes = passwordString.getBytes();
        sha1.update(bytes, 0, bytes.length);
        int val = sha1.doFinal(result, 0);
    } catch (UnsupportedEncodingException e) {}
    return new String(result);
}

public String toHex(String arg) {
    return new BigInteger(1, arg.getBytes()).toString(16);
}

And this on the server (Shiro):
 String hashed = new Sha1Hash("password").toHex()

which afaics does something very similar behind the scenes (had a quick view on the source code).
Did I miss something obvious here?
EDIT: Seems like the GWT code does not run natively for some reason (i.e. just in development mode) and silently fails (it does compile, though). Have to find out why...
Edit(2): "int val = sha1.doFinal(result, 0);" is the line that makes trouble, i.e. if present, the whole code does not run natively (JS) but only in dev-mode (with wrong results)

A: You could test this version:
public class SHA1 {

    public static native String calcSHA1(String s) /*-{
        //
        // A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
        // in FIPS 180-1
        // Version 2.2 Copyright Paul Johnston 2000 - 2009.
        // Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
        // Distributed under the BSD License
        // See http://pajhome.org.uk/crypt/md5 for details.
        //

        //
        // Configurable variables. You may need to tweak these to be compatible with
        // the server-side, but the defaults work in most cases.
        //
        var hexcase = 0;  // hex output format. 0 - lowercase; 1 - uppercase
        var b64pad  = ""; // base-64 pad character. "=" for strict RFC compliance

        //
        // These are the functions you'll usually want to call
        // They take string arguments and return either hex or base-64 encoded strings
        //

        function b64_sha1(s)    { return rstr2b64(rstr_sha1(str2rstr_utf8(s))); }
        function any_sha1(s, e) { return rstr2any(rstr_sha1(str2rstr_utf8(s)), e); }
        function hex_hmac_sha1(k, d)
          { return rstr2hex(rstr_hmac_sha1(str2rstr_utf8(k), str2rstr_utf8(d))); }
        function b64_hmac_sha1(k, d)
          { return rstr2b64(rstr_hmac_sha1(str2rstr_utf8(k), str2rstr_utf8(d))); }
        function any_hmac_sha1(k, d, e)
          { return rstr2any(rstr_hmac_sha1(str2rstr_utf8(k), str2rstr_utf8(d)), e); }

        //
        // Perform a simple self-test to see if the VM is working
        //
        function sha1_vm_test()
        {
          return hex_sha1("abc").toLowerCase() == "a9993e364706816aba3e25717850c26c9cd0d89d";
        }

        //
        // Calculate the SHA1 of a raw string
        //
        function rstr_sha1(s)
        {
          return binb2rstr(binb_sha1(rstr2binb(s), s.length * 8));
        }

        //
        // Calculate the HMAC-SHA1 of a key and some data (raw strings)
        //
        function rstr_hmac_sha1(key, data)
        {
          var bkey = rstr2binb(key);
          if(bkey.length > 16) bkey = binb_sha1(bkey, key.length * 8);

          var ipad = Array(16), opad = Array(16);
          for(var i = 0; i < 16; i++)
          {
            ipad[i] = bkey[i] ^ 0x36363636;
            opad[i] = bkey[i] ^ 0x5C5C5C5C;
          }

          var hash = binb_sha1(ipad.concat(rstr2binb(data)), 512 + data.length * 8);
          return binb2rstr(binb_sha1(opad.concat(hash), 512 + 160));
        }

        //
        // Convert a raw string to a hex string
        //
        function rstr2hex(input)
        {
          try { hexcase } catch(e) { hexcase=0; }
          var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
          var output = "";
          var x;
          for(var i = 0; i < input.length; i++)
          {
            x = input.charCodeAt(i);
            output += hex_tab.charAt((x >>> 4) & 0x0F)
                   +  hex_tab.charAt( x        & 0x0F);
          }
          return output;
        }

        //
        // Convert a raw string to a base-64 string
        //
        function rstr2b64(input)
        {
          try { b64pad } catch(e) { b64pad=''; }
          var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
          var output = "";
          var len = input.length;
          for(var i = 0; i < len; i += 3)
          {
            var triplet = (input.charCodeAt(i) << 16)
                        | (i + 1 < len ? input.charCodeAt(i+1) << 8 : 0)
                        | (i + 2 < len ? input.charCodeAt(i+2)      : 0);
            for(var j = 0; j < 4; j++)
            {
              if(i * 8 + j * 6 > input.length * 8) output += b64pad;
              else output += tab.charAt((triplet >>> 6*(3-j)) & 0x3F);
            }
          }
          return output;
        }

        //
        // Convert a raw string to an arbitrary string encoding
        //
        function rstr2any(input, encoding)
        {
          var divisor = encoding.length;
          var remainders = Array();
          var i, q, x, quotient;

          // Convert to an array of 16-bit big-endian values, forming the dividend
          var dividend = Array(Math.ceil(input.length / 2));
          for(i = 0; i < dividend.length; i++)
          {
            dividend[i] = (input.charCodeAt(i * 2) << 8) | input.charCodeAt(i * 2 + 1);
          }

          //
          // Repeatedly perform a long division. The binary array forms the dividend,
          // the length of the encoding is the divisor. Once computed, the quotient
          // forms the dividend for the next step. We stop when the dividend is zero.
          // All remainders are stored for later use.
          //
          while(dividend.length > 0)
          {
            quotient = Array();
            x = 0;
            for(i = 0; i < dividend.length; i++)
            {
              x = (x << 16) + dividend[i];
              q = Math.floor(x / divisor);
              x -= q * divisor;
              if(quotient.length > 0 || q > 0)
                quotient[quotient.length] = q;
            }
            remainders[remainders.length] = x;
            dividend = quotient;
          }

          // Convert the remainders to the output string
          var output = "";
          for(i = remainders.length - 1; i >= 0; i--)
            output += encoding.charAt(remainders[i]);

          // Append leading zero equivalents
          var full_length = Math.ceil(input.length * 8 /
                                            (Math.log(encoding.length) / Math.log(2)))
          for(i = output.length; i < full_length; i++)
            output = encoding[0] + output;

          return output;
        }

        //
        // Encode a string as utf-8.
        // For efficiency, this assumes the input is valid utf-16.
        //
        function str2rstr_utf8(input)
        {
          var output = "";
          var i = -1;
          var x, y;

          while(++i < input.length)
          {
              // Decode utf-16 surrogate pairs
            x = input.charCodeAt(i);
            y = i + 1 < input.length ? input.charCodeAt(i + 1) : 0;
            if(0xD800 <= x && x <= 0xDBFF && 0xDC00 <= y && y <= 0xDFFF)
            {
              x = 0x10000 + ((x & 0x03FF) << 10) + (y & 0x03FF);
              i++;
            }

            // Encode output as utf-8
            if(x <= 0x7F)
              output += String.fromCharCode(x);
            else if(x <= 0x7FF)
              output += String.fromCharCode(0xC0 | ((x >>> 6 ) & 0x1F),
                                            0x80 | ( x         & 0x3F));
            else if(x <= 0xFFFF)
              output += String.fromCharCode(0xE0 | ((x >>> 12) & 0x0F),
                                            0x80 | ((x >>> 6 ) & 0x3F),
                                            0x80 | ( x         & 0x3F));
            else if(x <= 0x1FFFFF)
              output += String.fromCharCode(0xF0 | ((x >>> 18) & 0x07),
                                            0x80 | ((x >>> 12) & 0x3F),
                                            0x80 | ((x >>> 6 ) & 0x3F),
                                            0x80 | ( x         & 0x3F));
          }
          return output;
        }

        //
        // Encode a string as utf-16
        //
        function str2rstr_utf16le(input)
        {
          var output = "";
          for(var i = 0; i < input.length; i++)
            output += String.fromCharCode( input.charCodeAt(i)        & 0xFF,
                                          (input.charCodeAt(i) >>> 8) & 0xFF);
          return output;
        }

        function str2rstr_utf16be(input)
        {
          var output = "";
          for(var i = 0; i < input.length; i++)
            output += String.fromCharCode((input.charCodeAt(i) >>> 8) & 0xFF,
                                           input.charCodeAt(i)        & 0xFF);
          return output;
        }

        //
        // Convert a raw string to an array of big-endian words
        // Characters >255 have their high-byte silently ignored.
        //
        function rstr2binb(input)
        {
          var output = Array(input.length >> 2);
          for(var i = 0; i < output.length; i++)
            output[i] = 0;
          for(var i = 0; i < input.length * 8; i += 8)
            output[i>>5] |= (input.charCodeAt(i / 8) & 0xFF) << (24 - i % 32);
          return output;
        }

        //
        // Convert an array of big-endian words to a string
        //
        function binb2rstr(input)
        {
          var output = "";
          for(var i = 0; i < input.length * 32; i += 8)
            output += String.fromCharCode((input[i>>5] >>> (24 - i % 32)) & 0xFF);
          return output;
        }

        //
        // Calculate the SHA-1 of an array of big-endian words, and a bit length
        //
        function binb_sha1(x, len)
        {
            // append padding
          x[len >> 5] |= 0x80 << (24 - len % 32);
          x[((len + 64 >> 9) << 4) + 15] = len;

          var w = Array(80);
          var a =  1732584193;
          var b = -271733879;
          var c = -1732584194;
          var d =  271733878;
          var e = -1009589776;

          for(var i = 0; i < x.length; i += 16)
          {
            var olda = a;
            var oldb = b;
            var oldc = c;
            var oldd = d;
            var olde = e;

            for(var j = 0; j < 80; j++)
            {
              if(j < 16) w[j] = x[i + j];
              else w[j] = bit_rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1);
              var t = safe_add(safe_add(bit_rol(a, 5), sha1_ft(j, b, c, d)),
                               safe_add(safe_add(e, w[j]), sha1_kt(j)));
              e = d;
              d = c;
              c = bit_rol(b, 30);
              b = a;
              a = t;
            }

            a = safe_add(a, olda);
            b = safe_add(b, oldb);
            c = safe_add(c, oldc);
            d = safe_add(d, oldd);
            e = safe_add(e, olde);
          }
          return Array(a, b, c, d, e);

        }

        //
        // Perform the appropriate triplet combination function for the current
        // iteration
        //
        function sha1_ft(t, b, c, d)
        {
          if(t < 20) return (b & c) | ((~b) & d);
          if(t < 40) return b ^ c ^ d;
          if(t < 60) return (b & c) | (b & d) | (c & d);
          return b ^ c ^ d;
        }

        //
        // Determine the appropriate additive constant for the current iteration
        //
        function sha1_kt(t)
        {
          return (t < 20) ?  1518500249 : (t < 40) ?  1859775393 :
                 (t < 60) ? -1894007588 : -899497514;
        }

        //
        // Add integers, wrapping at 2^32. This uses 16-bit operations internally
        // to work around bugs in some JS interpreters.
        //
        function safe_add(x, y)
        {
          var lsw = (x & 0xFFFF) + (y & 0xFFFF);
          var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
          return (msw << 16) | (lsw & 0xFFFF);
        }

        //
        // Bitwise rotate a 32-bit number to the left.
        //
        function bit_rol(num, cnt)
        {
          return (num << cnt) | (num >>> (32 - cnt));
        }

        return rstr2hex(rstr_sha1(str2rstr_utf8(s)));
    }-*/;
}

I'm using it in my client side sha generation and it worked well.


text:
Q: Ignore globals in a Python function I love IPython Notebook and I use it a lot for exploratory data analysis, where I try tons of different things until something works. However, quite often I end up doing the same mistake.. Let me idiotize an example:
I usually start doing tests in IPython like this:
a = 10
print a + 5

Until I get the desired result. Once I got it working, I tend to reformulate the code as a function:
def add5(b):
    return b + 5

Which would be the proper redefinition.. however, as the code is sometimes quite complex (and large), I end up with renaming errors and instead  write:
def add5(b):
    return a + 5

Note the a instead of the renamed b. This function will return a value as long as a exists in the workspace (which does). This mistake is quite annoying, sometimes takes a long time to realise what's wrong, and sometimes is even impossible to realise that something is wrong due to the complex nature of the function.
Is there any cell magic, decorator or something else to force a function to ignore global variables?
I would love something like:
@ignore_globals   ## or %%ignore_globals
def add5(b):
    return a + 5

so that the above would prompt an error if a is not defined inside the function (either at definition or at runtime). Assuming that a does exist in the workspace (globals()).
This introduces another problem in practice, which is that imported modules and other used defined functions and classes are also in globals (and should be accessible)..


text:
Q: Escaping the close-bracket character in a bash v3 heredoc I have a need to embed a fragment of a shell script in a heredoc as part of the creation of a cloud-init script to provision an Ubuntu 14.04 LTE machine. A simplified version of the script demonstrating the problem is as follows:
#!/bin/bash

cloudconfig=$(cat <<EOF
    if host \$NAMESERVER 1>/dev/null 2>&1; then
    case \$reason in
    BOUND|RENEW|REBIND|REBOOT) nsupdate -k /var/lib/dhcp/nsupdate.key << EOX
    server \$NAMESERVER
    update delete \$HOST_NAME A
    update add \$HOST_NAME \$TTL A \$HOST_ADDR
    send
    EOX
    ;;
    esac
    fi
EOF
)

echo "${cloudconfig}"

Running the above script fails as follows:
Little-Net:orchestration minfrin$ bash /tmp/test.sh
could not read key from /var/lib/dhcp/nsupdate.{private,key}: file not found
couldn't get address for '$NAMESERVER': not found

The problematic character is the closing bracket to the right of "REBOOT", and the obvious solution is to escape the character:
BOUND|RENEW|REBIND|REBOOT\) nsupdate -k /var/lib/dhcp/nsupdate.key << EOX

This backslash character however ends up in the final cloudconfig variable, which in turn breaks the output:
Little-Net:orchestration minfrin$ bash /tmp/test.sh
    if host $NAMESERVER 1>/dev/null 2>&1; then
    case $reason in
    BOUND|RENEW|REBIND|REBOOT\) nsupdate -k /var/lib/dhcp/nsupdate.key << EOX
    server $NAMESERVER
    update delete $HOST_NAME A
    update add $HOST_NAME $TTL A $HOST_ADDR
    send
    EOX
    ;;
    esac
    fi

This particular fragment above is part of a larger file that is being written that relies on variable interpolation, so quoting there heredoc with >>"EOF" is going to break the rest of our script.
How do I escape the ")" character without the escape character leaking through the heredoc?

A: As this seems to be a bash 3.x parsing issue (as it works in bash 4.x as can be seen here) you would need to avoid the parser getting confused. This seems to work for me:
#!/bin/bash

rp=")"
cloudconfig=$(cat <<EOF
    if host \$NAMESERVER 1>/dev/null 2>&1; then
    case \$reason in
    BOUND|RENEW|REBIND|REBOOT${rp} nsupdate -k /var/lib/dhcp/nsupdate.key << EOX
    server \$NAMESERVER
    update delete \$HOST_NAME A
    update add \$HOST_NAME \$TTL A \$HOST_ADDR
    send
    EOX
    ;;
    esac
    fi
EOF
)

echo "${cloudconfig}"

A: Since you don't have any parameters you actually want to expand inside the here document, I would just quote the entire thing (which saves you a lot of explicit backslashes):
#!/bin/bash

cloudconfig=$(cat <<'EOF'
    if host $NAMESERVER 1>/dev/null 2>&1; then
    case $reason in
    BOUND|RENEW|REBIND|REBOOT) nsupdate -k /var/lib/dhcp/nsupdate.key << EOX
    server $NAMESERVER
    update delete $HOST_NAME A
    update add $HOST_NAME $TTL A $HOST_ADDR
    send
EOX
    ;;
    esac
    fi
EOF
)

echo "${cloudconfig}"

Note that you cannot indent EOX either, or else that here document will not be correctly terminated when you go to use it.
Even easier, though, is to not use a here document at all; just use embedded newlines in the parameter assignment.
#!/bin/bash

cloudconfig='
if host $NAMESERVER 1>/dev/null 2>&1; then
  case $reason in
    BOUND|RENEW|REBIND|REBOOT) nsupdate -k /var/lib/dhcp/nsupdate.key << EOX
    server $NAMESERVER
    update delete $HOST_NAME A
    update add $HOST_NAME $TTL A $HOST_ADDR
    send
EOX
    ;;
  esac
fi'

echo "${cloudconfig}"

If you need to allow some parameter expansion, you can still use the multiline string with some modifications. Whenever you need an interpolation, close the single quote and immediately open the double quote. After the expansion is complete, close the double and reopen the single.
cloudconfig='
    if [[ $SOMEVARIABLE =='"$value"' ]]; then
    ...
'

A: I solved it by escaping the parenths manually inside the HEREDOC and then follow it with a sed statement to remove the backslashes.
long_string=$(cat << 'HEREDOC'
This is a string with \( escaped \) parenthesis.
HEREDOC
)

long_string=$(echo $long_string | sed -e 's:\\(:(:g' -e 's:\\):):g')

Using bash 4+ would be better, but then I have to get everyone on my team using mac's to also get bash 4+.


text:
Q: How to close the menu when I click outside? I created a menu with Bootstrap 4. Here is the HTML code :
{% block head %}

          {% if container_navbar %}

          {% endif %}

            {% if page.navigation_collapsible_first %}

                  {{ page.navigation_collapsible_first }}

            {% endif %}

            {{ page.navigation_menu_first }}
            {{ page.navigation_notification_first }}
            {{ page.navigation_logo }}
            {{ page.navigation_notification_second }}
            {{ page.navigation_menu_second }}

            {% if page.navigation_collapsible_second %}

                  {{ page.navigation_collapsible_second }}

            {% endif %}

          {% if container_navbar %}

          {% endif %}

{% endblock %}

I want the menu to close when I click outside. It works with the JS code below, but it also closes when I click in it. It must close only if I click outside :
  $(document).click(function (event) {
    if (!$(event.target).closest('#CollapsingNavbarFirst').length) {
      $('.navbar-collapse').collapse('hide');
    }
    if (!$(event.target).closest('#CollapsingNavbarSecond').length) {
      $('.navbar-collapse').collapse('hide');
    }
  });

Here is a page of my site to test. In the menu at the top right (the filter box), when you select an option from the drop-down menu, it closes. If you click a white space in the menu, it closes.

A: Keep it simple: if you want to close .navbar-collapse when you click outside .navbar-collapse just write that.
/// When you click everywhere in the document
$(document).click(function (event) {

  /// If *navbar-collapse* is not among targets of event
  if (!$(event.target).is('.navbar-collapse *')) {

    /// Collapse every *navbar-collapse*
    $('.navbar-collapse').collapse('hide');

  }
});

You don't even need to use IDs

A:

document.addEventListener("click", function(e){
   x = e.clientX;
    y = e.clientY;
    var elementMouseIsOver = document.elementFromPoint(x, y);
    if(elementMouseIsOver.id=="menu"){
      console.log("menu");
    }
    else{
      console.log("not menu");
    }
});
#menu{
width:100px;
height:100px;
background-color:red;
}
.test{
width:300px;
height:300px;
background-color:blue;
}


text:
Q: What does the comma mean in the graphoid axioms? I have been trying to understand the graphoid axioms, one of which--Decomposition--claims that
$$ (X \bot Y,W |Z) \implies (X \bot Y|Z).$$
In Pearl's book Causality, he writes $\bot$ with two vertical lines, and omits the comma.  The list is just after equation 1.29 in that text.
Axiom C4 in this lecture by Steffen Lauritzen, uses the comma. Wikipedia seems to claim that it is a logical and uses a different notation:
$$I(X,Z,Y)\ \text{ means that }\ (X \bot Y |Z).$$
There are several answers to questions like this, but as far as I can tell none of them actually give a definition of the comma.  Neither do any writings by Pearl or any other online sources I have read, except where they contradict each other.  I can't prove the statement if I can't tell what it is saying!
Now before you just say, "It's an and" or some such, I will point out that multiple people have claimed that it is a set intersection, a set union, a logical and--meaning that it isn't one statement but rather two to begin with? and I don't know what else. I tried my best guess and found a counterexample, so clearly I don't know what it is trying to say.
I want to know what is the definition of the claim.  Exactly.  No hand waving.  If you can carefully distinguish sets from random variables from probabilities that would also be a big help.
If I ever figure this out I promise to share my understanding as clearly as possible with others.

A: Concatenation means and in Pearl's independence axioms.  So Pearl's Decomposition $(X\bot YW \;| Z)$ should be read as "$X$ is independent of $(Y\&W)$ given $Z$."
Pearl uses comma for and in probability statements.  This seems clear given (1.28)and (1.29), which are pretty standard defintions of conditional independence and regular probabilistic independence.
With this understanding, you can derive Decomposition from the definition of conditional independence in (1.28) [p. 11 in 2nd ed.].
Intersection (the set-theoretic operation, not the graph axiom) is the set-theoretic version of and.  They're equivalent because you can convert statements to sets in which they hold, and vice versa.
Comma is and in the probability statements in Wikipedia.  In $I(X,Y,Z)$ the commas distinguish arguments to the predicate $I$, which means "$X$ is independent of $Y$ given $Z$" as stated on the page.
Lauritzen seems to use comma for and, though I haven't checked carefully.  That looks right, though, and he uses $\cup$ (union, or) in other places.


text:
Q: Overwrite variable from makefile In my makefile I have a variable FOO:
FOO = /path/to/bar

Is it possible to overwrite this variable during the makefile call? Somthing like the following:
FOO=/path/to/foo make all

A: Specify them as Var=Value before you specify the target, like make FOO=/path/to/foo all.
$ cat Makefile
Foo = asdf

all:
    echo $(Foo)

$ make all
echo asdf
asdf
$ make Foo=bar all
echo bar
bar

A: The ways that variables get assigned values is specified in the How Variables Get Their Values section of the GNU make Manual.

Variables can get values in several different ways:

*

*You can specify an overriding value when you run make. See Overriding Variables.

*You can specify a value in the makefile, either with an assignment (see Setting Variables) or with a verbatim definition (see Defining Multi-Line Variables).

*Variables in the environment become make variables. See Variables from the Environment.

*Several automatic variables are given new values for each rule. Each of these has a single conventional use. See Automatic Variables.

*Several variables have constant initial values. See Variables Used by Implicit Rules.

So, as Colonel Thirty Two indicates, you can override variables set in the makefile on the command line.
You can also, if you expect this to be a variable that you want to set persistently, use the ?= assignment and then environment values for that variable will be used.


text:
Q: Continuous call to repaint using thread.start() not working I am new to Java swing. I want to create 2 cars that move from one end of the screen to another and for now I am testing it out with one.
But after three movements(indicated by "In paint component" printed 3 times) there is no movement.
I have attached the complete code below.
import javax.swing.SwingUtilities;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Polygon;

public class Application {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {

                JFrame f = new JFrame("Demo");
                Car car = new Car();
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                f.add(car);
                f.pack();
                f.setVisible(true);

                Thread thread = new Thread(car);
                thread.start();

            }
        });
    }

}

class Car extends JPanel implements Runnable {

    private int xBase = 0, yBase = 50;

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(250, 200);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        System.out.println("In paint component");
        xBase = xBase + 20;

        // Draw two wheels
        g.setColor(Color.BLACK);
        g.fillOval(xBase + 10, yBase - 10, 10, 10);
        g.fillOval(xBase + 30, yBase - 10, 10, 10);

        // Draw the car body
        g.setColor(Color.BLUE);
        g.fillRect(xBase, yBase - 20, 50, 10);

        // Draw the top
        g.setColor(Color.DARK_GRAY);
        Polygon polygon = new Polygon();
        polygon.addPoint(xBase + 10, yBase - 20);
        polygon.addPoint(xBase + 20, yBase - 30);
        polygon.addPoint(xBase + 30, yBase - 30);
        polygon.addPoint(xBase + 40, yBase - 20);
        g.fillPolygon(polygon);
    }

    @Override
    public void run() {
        try {
            validate();
            repaint();
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
            System.out.println(ex.getMessage());
        }
    }
}

What am I doing wrong.?

A: You need to call the repaint() method in a loop in order for the car to continue moving after you start the thread.
For example:
@Override
public void run() {
    int limit = 10;
    try {
        while (limit > 0) {
            limit--;
            repaint();
            Thread.sleep(1000);
        }
    } catch (InterruptedException ex) {
        System.out.println(ex.getMessage());
    }
}

Currently the repaint() method gets called three time but you don't see any movement because the repaint takes place before the Car object is completely visible.
In response to your comment: You can create a method to draw the car like so:
private void drawCar(Graphics g, int x, int y) {
    g.fillOval(x, y, 10, 10);
    g.fillOval(x + 20, y, 10, 10);
    // Draw the car body
    g.setColor(Color.BLUE);
    g.fillRect(x - 10, y - 10, 50, 10);
    // Draw the top
    g.setColor(Color.DARK_GRAY);
    Polygon polygon = new Polygon();
    polygon.addPoint(x, y - 10);
    polygon.addPoint(x + 10, y - 20);
    polygon.addPoint(x + 20, y - 20);
    polygon.addPoint(x + 30, y - 10);
    g.fillPolygon(polygon);
}

and call it in the paintComponent(...) method multiple times:
@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    System.out.println("In paint component");
    xBase = xBase + 20;
    drawCar(g, xBase, yBase);// draw the first car
    drawCar(g, xBase + 80, yBase);// draw the second car 80 pixels ahead
    drawCar(g, xBase, yBase + 100); // draw the third car 100 pixels lower

    g.dispose();
}


text:
Q: ¿Como agregar un objeto a un arreglo sin que se modifiquen los demás objetos? Tengo un arreglo y un objeto que contiene modelos.
Quiero agregar el objeto al arreglo con la función push(), pero al hacerlo cambia todos los valores existente en el arreglo haciendo referencia al objeto.
Ejemplo de mi código

var app = new Vue({
  el: '#app',
  data: function () {
    return {
      dato: {
        nombre: '',
        apellido: ''
      },
      array: []
    }
  },
  methods: {
    add: function() {
      this.array.push(this.dato)
    }
  }
})

  <input type="text" placeholder="Nombre" v-model="dato.nombre" />
  <input type="text" placeholder="Apellido" v-model="dato.apellido" />
  <button v-on:click="add">PUSH</button>

      {{ n }}

Sería genial que alguien sepa como hacer que el arreglo sea estático

A: Podrías simplemente copiar el objeto y guarda la copia en el arreglo.
Para esto podrías usar Object.assign()
Demo:

var app = new Vue({
  el: '#app',
  data: function () {
    return {
      dato: {
        nombre: '',
        apellido: ''
      },
      array: []
    }
  },
  methods: {
    add: function() {
      // AQUI creamos una copia
      var copia = Object.assign({}, this.dato);
      this.array.push(copia)
    }
  }
})

  <input type="text" placeholder="Nombre" v-model="dato.nombre" />
  <input type="text" placeholder="Apellido" v-model="dato.apellido" />
  <button v-on:click="add">PUSH</button>

      {{ n }}


text:
Q: Are there constants for infinity? I notice that Rascal supports big integers.  But I cannot find constants for infinity.  Do they exist?  If not, I would suggest add them since the sometimes they are quite useful.  Currently, my workaround is to define something like int pInf = 1024, but it may fail for extreme cases.

A: Rational numbers in Rascal actually support infinity (in the form of a zero denominator), but that's more a side effect of the implementation than a real design choice, so you may not want to count on it. I also can't guarantee that all corner cases are handled correctly.
For example,
rascal>1r0
rat: 1r0

rascal>1r0*2
rat: 1r0

rascal>-1r0
rat: -1r0

rascal>-1r0*(-2)
rat: 1r0

rascal>1 / 1r0
rat: 0r

rascal>12345678901234567890 > 1r0
bool: false

rascal>25r0
rat: 1r0

rascal>25 / 0
|stdin:///|(5,1,<1,5>,<1,6>): ArithmeticException("/ by zero")

rascal>25 / 0r
rat: 1r0

A: No support for infinity in Rascal.
The "Rascal" way of dealing with such variability is to introduce an algebraic data-type, as in:
data Arity = inf() | fixed(int size)

Then you can use pattern matching or is or whatever to deal with the differences.
if (arity is inf) {...}
int foo(fixed(int size)) = ...;
int foo(inf()) = ...;


text:
Q: Finding the maximum area in given binary data I have a problem with describing algorithm for finding maximum rectangular area of binary data, where 1 occurs k-times more often than 0. Data is always n^2 bits like this:
For example data for n = 4 looks like:
   1 0 1 0
   0 0 1 1
   0 1 1 1
   1 1 0 1
Value of k can be 1 .. j (k = 1 means, that number of 0 and 1 is equal).
For above example of data and for k = 1 solution is:
1 0 1 0   <- 4 x '0' and 4 x '1'
0 0 1 1
   0 1 1 1
   1 1 0 1
But in this example:
1 1 1 0
0 1 0 0
0 0 0 0
0 1 1 1
Solution would be:
1 1 1 0
0 1 0 0
0 0 0 0
0 1 1 1
I tried with few brute force algorithms but for n > 20 it is getting too slow. Can you advise me how I should solve this problem?

As RBerteig proposed - the problem can be also described like that: "In a given square bitmap with cells set to 1 or 0 by some arbitrary process, find the largest rectangular area where the 1's and 0's occur in a specified ratio, k."

A: Bruteforce should do just fine here for n < 100, if properly implemented: solution below has O(n^4) time and O(n^2) memory complexity. 10^8 operations should be well under 1 second on modern PC (especially considering that each operation is very cheap: few additions and subtractions).
Some observations

*

*There're O(n^4) sub-rectangles to consider and each of them can be a solution.

*If we can find number of 1's and 0's in each sub-rectangle in O(1) (constant time), we'll solve problem in O(n^4) time.

*If we know number of 1's in some sub-rectangle, we can find number of zeroes (through area).

So, the problem is reduced to following: create data structure allowing to find number of 1's in each sub-rectangle in constant time.
Now, imagine we have sub-rectangle [i0..i1]x[j0..j1]. I.e., it occupies rows between i0 and i1 and columns between j0 and j1. And let count_ones be the function to count number of 1's in subrectangle.
This is the main observation:
count_ones([i0..i1]x[j0..j1]) = count_ones([0..i1]x[0..j1]) - count_ones([0..i0 - 1]x[0..j1]) - count_ones([0..i1]x[0..j0 - 1]) + count_ones([0..i0 - 1]x[0..j0 - 1])

Same observation with practical example:
AAAABBB
AAAABBB
CCCCDDD
CCCCDDD
CCCCDDD
CCCCDDD

If we need to find number of 1's in D sub-rectangle (3x4), we can do it by taking number of 1's in the whole rectangle (A + B + C + D), subtracting number of 1's in (A + B) rectangle, subtracting number of 1's in (A + C) rectangle, and adding number of 1's in (A) rectangle. (A + B + C + D) - (A + B) - (A + C) + (A) = D
Thus, we need table sums, for each i and j containing number of 1's in sub-rectangle [0..i][0..j].
You can create this table in O(n^2), but even the direct way to fill it (for each i and j iterate all elements of [0..i][0..j] area) will be O(n^4).
Having this table,
count_ones([i0..i1]x[j0..j1]) = sums[i1][j1] - sums[i0 - 1][j1] - sums[i1][j0 - 1] + sums[i0 - 1][j0 - 1]

Therefore, time complexity O(n^4) reached.

A: This is still brute force, but something you should note is that you don't have to recompute everything from scratch for a new i*j rectangle. Instead, for each possible rectangle size, you can move the rectangle across the n*n grid one step at a time, decrementing the counts for the bits no longer within the rectangle and incrementing the counts for the bits that newly entered the rectangle. You could potentially combine this with varying the rectangle size, and try to find an optimal pattern for moving and resizing the rectangle.

A: Just some hints..
You could impose better restrictions on the values. The requirement leads to condition
N1*(k+1) == S*k, where N1 is number of ones in an area, and S=dx*dy is its surface.
It can be rewritten in better form:
N1/k == S/(k+1).
Because the greatest common divisor of numbers n and n+1 is always 1, then N1 have to be multiple of k and dx*dy to be multiple of k+1. It reduces greatly the possible space of solutions, the larger is k, the better (for dx*dy case you'll need to play with prime divisors of k+1).
Now, because you need just the surface of the largest area with such property, it would be wise to start from largest areas and move to smaller ones. By trying dx*dy from n^2 downto k+1 that would satisfy the divisor and the bounding conditions, you'll find quite fast the solution, muuuch faster than O(n^4), because of a special reason: except cases when the array was specially constructed, if we assume a random input, the probability that there are N1 ones out of S values in the (n-dx+1)*(n-dy+1) areas that have the surface S will constantly grow with decrease of S. (large values of k will make the probability smaller, but in the same time they will make the filter for dx and dy pairs stronger).
Also, this problem: http://ioinformatics.org/locations/ioi99/contest/land/land.shtml , looks somehow similar, maybe you'll find some ideas in their solution.


text: Q: Google maps GroundOverlay's image dimensions I cannot find any resource for the standard dimensions of GroundOverlay images (e.g. pixels per meter). How should I calculate it in a way it is efficient but doesn't compromise the quality?


text:
Q: how do I handle sockets which is readable but recv nothing? Recently I've been writing a http/https proxy using socket on python, and I use select to decide whether a socket is ready to recv or send, something like this:
inputs = [sock1, sock2...]
outputs = [sock1, sock2...]
while True:
    readable, writable, exceptional = select.select(inputs, outputs, inputs)
    for s in readable:
        do something with s.recv()
    for s in writable:
        do something with s.send()

and I notice that sometimes a socket is readable but when I do s.recv() it returns empty. And since I have a while True loop outside so it gets nothing again and again. I tried to close the socket at first:
data = s.recv(4096)
if not data:
    inputs.remove(s)
    s.close()

but after a while some socket comes alive and they can't send msg to me because I've already closed it.
Does that mean I shouldn't close it? So what should I do with that?

A: When a socket in the receive list returns zero bytes on recv, it means that the socket has been closed from the other side. It will never receive data again and should be shutdown and closed on your side too.
You way "some socket comes alive" - its not the socket on the other side of this connection, that one has already shutdown.


text:
Q: windows phone check from web browser/javascript on web end if app is installed If I click on a url on some 3rd party app A to open another app B (my app), it takes me to a web browser before redirecting to the app B.Is there any way to determine if the app B is installed on the windows phone device through javascript on the web end before trying to redirect to app B, given we have appId, device Id and Uri scheme name ?

A: Nop. It is not allowed by the OS.


text:
Q: Downloading Large Number of Files in Frontend using jszip Unable to zip all the files using jszip. JS zip is reading all 402 files as shown in snapshot from the console from around 143 requests but zipping only 143 files. I am using parallelimit to process multiple async requests simultaneously and cleanly. I am How can we get all the 403 files in the result?
private downloadUntouchedFiles = () => {

let requestObjectInfo = [];
let index = 0;
this._eventEmitter.emit(Constants.LOADER_CHANGE, { show: true });

this._eligibilitySubmissionInstance.getUntouchedFiles(this.state.filterObject).then((requests) => {
  debugger;
  if (!(!requests)) {
    if (requests.length > 0) {

      var zip = new JSZip();
      var zipFileName = "ES_Unviewed_Files";
      var promises = [];
      this._eventEmitter.emit(Constants.LOADER_CHANGE, { show: true });

      const downloadSubPromises = [];
      let i =0;
          requests.forEach((req) => {
            req.Folder.Files.forEach(f => {
              f.Name = this.state.initials + '_' + this.state.userId + '_' + f.Name;
              console.log(f.Name);
              i++;
              console.log(i);
              downloadSubPromises.push((submit: any) => {
                JSZipUtils.getBinaryContent(f.ServerRelativeUrl, (err, data) => {
                  try {
                    if (err) {
                      throw err;
                    }
                    zip.file(f.Name, data, { binary: true });

                    submit(null, true);

                  } catch (err) {
                    submit(err, true);
                    this._eventEmitter.emit(Constants.LOADER_CHANGE, { show: false });
                    this._loggerInstance.logException(Constants.SISCC_ES_EXCEPTIONS, {
                      Component: this._canonicalName,
                      Message: ErrorMessages.COM007,
                      UserName: !(!DataSingleton.getCurrentUser()) ? DataSingleton.getCurrentUser() : '',
                      Group: '',
                      Notes: err,
                      Source: Constants.EXCEPTION_UI_SOURCE,
                      ExceptionID: Guid.create().toString()
                    } as ExceptionObject).then(() => {
                    });
                  }
                });

              });
            });
            requestObjectInfo.push(req);
          });
          parallelLimit(downloadSubPromises, Constants.DOWNLOAD_BATCH_MAX_FILE_LIMIT,
            (err, results) => {
              try {
                console.log(results);
                debugger;
                zip
                  .generateInternalStream({ type: "blob" })
                  .accumulate()
                  .then((content) => {
                    saveAs(content, zipFileName + ".zip");
                  });
              }
              catch (err) {
                this._eventEmitter.emit(Constants.LOADER_CHANGE, { show: false });
                this._loggerInstance.logException(Constants.SISCC_ES_EXCEPTIONS, {
                  Component: this._canonicalName,
                  Message: ErrorMessages.COM007,
                  UserName: !(!DataSingleton.getCurrentUser()) ? DataSingleton.getCurrentUser() : '',
                  Group: '',
                  Notes: err,
                  Source: Constants.EXCEPTION_UI_SOURCE,
                  ExceptionID: Guid.create().toString()
                } as ExceptionObject).then(() => {
                });
              }});

      while (index < requestObjectInfo.length) {
        this.setState({ requestObject: requestObjectInfo[index] });
        if (this.state.requestObject.Status !== Constants.ES_DOWNLOADREQUEST_STATUS) {
          this.updateESRequestStatus(Constants.ES_DOWNLOADREQUEST_STATUS);
        }
        index++;
      }
      this._eventEmitter.emit(Constants.LOADER_CHANGE, { show: false });
    }
  }
});

}

In this case only 55-75MB on JS Heap is used.

A: You can use async and await to make the code easier to understand and avoid deep nesting:
const ZIP_FILE_NAME = "ES_Unviewed_Files.zip"

const downloadUntouchedFiles = async () => {
    const zip = new JSZip()
    const untouched = this._eligibilitySubmissionInstance.getUntouchedFiles(this.state.filterObject)
    if (!untouched?.length) return

    const files = untouched.reduce((acc, { Folder: { Files } }) =>
        Files.forEach(f => acc.push({ name: `${this.state.userId}+${f.Name}`, ...f })), [])

    const downloads = files.map(({name, ServerRelativeUrl}) =>
        async () => ({ name, data: await fetchBinary(ServerRelativeUrl)}))

    const responses = await batched(downloads, Constants.DOWNLOAD_BATCH_MAX_FILE_LIMIT)

    responses.forEach(({ status, value: { name, data } }) =>
        status === 'fulfilled' && zip.file(name, data, { binary: true }))

    const content = await zip.generateInternalStream({ type: "blob" }).accumulate()
    await saveAs(content, ZIP_FILE_NAME)
}

const fetchBinary = (file) => new Promise((resolve) =>
    JSZipUtils.getBinaryContent(url, (err, data) => err ? reject(err) : resolve(data)))

async function batched(fns, batchSize = 2) {
    const results = []
    for(let start = 0, end = batchSize; start < fns.length; start += batchSize, end = start+batchSize) {
        const slice = fns.slice(start, end)
        const promises = slice.map((fn) => fn())
        results.push([...await Promise.allSettled(promises)])
    }
    return results.flat()
}

A: This will work
private downloadUntouchedFiles = () => {
this._eventEmitter.emit(Constants.LOADER_CHANGE, { show: true });
let statusUpdatePromises = [];
this._eligibilitySubmissionInstance.getUntouchedFiles(this.state.filterObject).then((requests) => {
  if (!(!requests)) {
    if (requests.length > 0) {
      var zip = new JSZip();
      var zipFileName = "ES_Unviewed_Files";
      const downloadSubPromises = [];
      requests.forEach((req: any) => {
        req.Folder.Files.forEach((f: any) => {
          f.Name = this.state.userId + '_' + f.Name;
          downloadSubPromises.push((submit: any) => {
            JSZipUtils.getBinaryContent(`${new Constants().BASE_URL}${encodeURIComponent(f.ServerRelativeUrl).replace('%2F', '/')}`, (err, data) => {
              try {
                if (err) {
                  submit(null, true);
                } else {
                  zip.file(f.Name, data, { binary: true });
                  submit(null, true);
                }
              } catch (err) {
                this._eventEmitter.emit(Constants.LOADER_CHANGE, { show: false });
                this._loggerInstance.logException(Constants.SISCC_ES_EXCEPTIONS, {
                  Component: this._canonicalName,
                  Message: ErrorMessages.COM007,
                  UserName: !(!DataSingleton.getCurrentUser()) ? DataSingleton.getCurrentUser() : '',
                  Group: '',
                  Notes: err,
                  Source: Constants.EXCEPTION_UI_SOURCE,
                  ExceptionID: Guid.create().toString()
                } as ExceptionObject).then(() => {
                });
                submit(null, false);
              }
            });

          });
        });
        statusUpdatePromises.push((submit: any) => {
          this.setState({ requestObject: req }, () => {
            if (this.state.requestObject.Status !== Constants.ES_DOWNLOADREQUEST_STATUS) {
              this.updateESRequestStatus(Constants.ES_DOWNLOADREQUEST_STATUS).then(res => {
                submit(true);
              });
            } else {
              submit(true);
            }
          });
        });
      });
      parallelLimit(downloadSubPromises, Constants.UPLOAD_BATCH_MAX_FILE_LIMIT,
        (err: any, results: any) => {
          parallelLimit(statusUpdatePromises, Constants.UPLOAD_BATCH_MAX_FILE_LIMIT,
            (subErr: any, subResults: any) => {
              try {
                zip
                  .generateInternalStream({ type: "blob" })
                  .accumulate()
                  .then((content) => {
                    this._eventEmitter.emit(Constants.LOADER_CHANGE, { show: false });
                    saveAs(content, zipFileName + ".zip");
                  });
              }
              catch (err) {
                this._eventEmitter.emit(Constants.LOADER_CHANGE, { show: false });
                this._loggerInstance.logException(Constants.SISCC_ES_EXCEPTIONS, {
                  Component: this._canonicalName,
                  Message: ErrorMessages.COM007,
                  UserName: !(!DataSingleton.getCurrentUser()) ? DataSingleton.getCurrentUser() : '',
                  Group: '',
                  Notes: err,
                  Source: Constants.EXCEPTION_UI_SOURCE,
                  ExceptionID: Guid.create().toString()
                } as ExceptionObject).then(() => {
                });
              }
            });
        });
    }
  }
});

}


text:
Q: How to use a forloop to determine number characters that have been input? So i'm still working on my calculator that can do algebraic equations, but I've ran into a bit of a snag. I'm wanting to set the program up to where if you input more than 4 different numbers, it will print a notice on the screen & give you a second chance to do it. However, my forloop isn't working. if 5 characters are input, it asks what type you want to do(the type meaning do you want 4 positive 4 negativee numbers, etc), and then the program resets. Here's what the code looks like(if more information is required I will update the thread as requested):
else if (type == "foil")
{
    cout << "Please input the value of X1, X2, Y1, and Y2 (Example: 8 9 4 9)\n";
    cin >> X1 >> X2 >> Y1 >> Y2;
    int nCount = 0;
    for (nCount == cin.beg; nCount != cin.end; nCount++)
    {
        if (nCount > 4)
        {
            printf("Please input 4 diffent numbers.\n");
            Sleep(1000);
            return main();
        }
        else
        {
            break;
        }
    }
//after forloop is when you're given a chance to input the different
//combinations foil can have, 2 negative 2 positive, 4 negative, 4 positive, etc.
}

A: Okay i guess there are several things to you problem.
First of all you loop will always break in the first iteration, becouse your if statement will take the else branch ALWAYS.
The statement nCount > 4 will always be false while entering the for loop.
The second problem is nCount == cin.beg; nCount != cin.end; nCount++
i would guess the extraction operator removes the bytes from the stream, can't find any refrence atm. So you can't determine the size with it for sure.
I would recommend to do something like this to verify user input.
char accepted = 'n';
do {
    accepted = 'n'
    cout << "Please input the value of X1, X2, Y1, and Y2 (Example: 8 9 4 9)\n";
    cin >> X1 >> X2 >> Y1 >> Y2;
    cin.clear();

    //Print out values
    cout << "Are those values corrent? y/n"
    cin >> accepted;
    cin.clear();
} while (accepted != 'y');

A: I suggest you use a std::vector to hold your variables:
std::vector<int> values(4);
cout << "Please input the value of X1, X2, Y1, and Y2 (Example: 8 9 4 9)\n";
for (unsigned int i = 0;
    (cin.good()) && (i < 4);
    ++i)
{
    cin >> values[i];
}
if (values.size() < 4)
{
  // handle error
}

By your variable naming convention, your program would be better if you package your values as Points, Coordinates or pairs.
struct Coordinate
{
  int x;
  int y;
  friend istream& operator>>(istream& inp, Coordinate& p);
};

istream& operator>>(istream& inp, Coordinate& p)
{
  inp >> p.x >> p.y;
  return inp;
}

int main(void)
{
  Coordinate p1;
  Coordinate p2;
  cout << "Please input point 1:";
  if (!(cin >> p1))
  {
    cerr << "Error inputting point 1.\n";
    return EXIT_FAILURE;
  }
  cout << "\nPlease input point 2:";
  if (!(cin >> p2))
  {
    cerr << "Error inputting point 2.\n";
    return EXIT_FAILURE;
  }
  // ...
  return EXIT_SUCCESS;
}


text:
Q: Python How to change text of already created tab in tkinter Notebook I have no idea how to change and access already created ttk.Notebook tab. I don't know how to access specific tab and even "current" doesn't work. Here is my code:
from tkinter import *
from tkinter import ttk

app = Tk()

tabs = ttk.Notebook(app)                        # Create Tab Control

options_tab = ttk.Frame(tabs)                   # Create a tab
tabs.add(options_tab, text='Options')           # Add the tab

tabs.pack(expand=1, fill="both")                 # Pack to make visible

lang_dct = {
    "en": 0,
    "af": 1
}

my_lang = lang_dct['en']
print(my_lang)

# New language chosen here
lang_l = Label(options_tab)
lang_l.config(text=["Choose language",
                    "Kies taal"][my_lang])
lang_l.grid(row=0, column=0)

def on_select(event=None):
    print('----------------------------')
    if event: # <-- this works only with bind because `command=` doesn't send event
        print("event.widget:", event.widget.get())

    global my_lang
    cb = event.widget.get()
    if cb == "English":
        my_lang = 0
    elif cb == "Afrikaans":
        my_lang = 1
    print(my_lang)
    change_lang()

def change_lang():
    lang_l.config(text=["Choose language",
                        "Kies taal"][my_lang])
    print(tabs)
    print(tabs.tab("current"))
    tabs.tab("current")['text'] = ["Options",
                                   "Opsies"][my_lang]

language_cb = ttk.Combobox(options_tab, values=("English", "Afrikaans"))
language_cb.grid(row=1, column=0)
language_cb.bind('<<ComboboxSelected>>', on_select)

app.mainloop()

I can print current tab but I can't change it in any way. How can I change text in a ttk tkinter Notepad tab?

A: ttk widgets sometimes work a little differently than tk widgets. In the case of notebook tabs, you set the option of a tab with the tab method. If you don't provide any arguments other than a tab index, this method will return a dictionary representing the options. Your code is changing the dictionary, changing the dictionary doesn't change the actual widget.
To change an option, give the option name and new value as arguments to the tab method. For example:
tabs.tab("current", text=["Options", "Opsies"][my_lang])


text:
Q: Using ASIHTTPRequest and json-framework on the iPhone I'm planning on using both these libraries (or wrappers?) in my upcoming iPhone app. I see one of the top reason applications get refused, is due to using private frameworks/API calls. Is ASIHTTPRequest and json-framework considered such, or can I safely use these?

A: when people say "private frameworks" they mean pieces of Apple's iPhone OS that are undocumented.  Due to the way Objective C works, you can call undocumented OS methods by name, and Apple tends to frown on that.
Using 3rd party libraries like ASIHTTPRequest is not a problem, unless, like Joe Hewitt's Three20 library, the library itself uses undocumented OS calls.


text: Q: Acces Azuresite from other device I develop an Azuresite on my computer and debug it on my local machine. I want to test the site on mobile devices too, but I can't access the page from one of my testphones. How can I achieve this?


text:
Q: Preimage of submanifold under an embedding Suppose we have two smooth manifolds $M_1$ and $M_2$ and a smooth
map $i:M_1 \rightarrow M_2$ that is an embedding of $M_1$ into
$M_2$. Moreover we have another submanifold $N \subset M_2$ that has a
non empty intersection with the embedding $i(M_1)$. Then,in what situation is the
preimage set $i^{-1}(N)$ a submanifold of $M_1$?
Or in other words, what do we have to assume so that the preimage set is a submanifold?

A: One hypothesis that works is that $N$ is transverse to the image of $i$, but this is not a necessary condition. For example, the preimage under the inclusion of the $x$ axis into $\mathbb R^2$ of the parabola $\{(t,t^2):t\in\mathbb R\}$ is a submanifold...


text:
Q: How to avoid the multi-line text view shift up and obstacle the above edit text view while typing in the edit text view? I'm recently learning Android app development. And after I added a multi-line scrollable text view to display the output (based on the input from the user from the EditText), this text view will shift up and obstacle the edit text view which is above it while I'm trying to type something in the edit text view.
Is there any way to stop the shift up of this multi-line text view?
Before typing:

While typing in the edit text view...

Following is my xml code for the layout:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="174dp"
        android:layout_height="42dp"
        android:layout_marginTop="45dp"
        android:text="My New App"
        android:textAlignment="center"
        android:textColor="@color/colorPrimary"
        android:textSize="25sp"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.50"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button"
        android:layout_width="135dp"
        android:layout_height="72dp"
        android:layout_marginTop="42dp"
        android:layout_marginEnd="25dp"
        android:background="@android:color/holo_green_light"
        android:onClick="doPress"
        android:text="Press me"
        android:textAlignment="center"
        android:textColor="@android:color/background_light"
        android:textSize="24sp"
        app:layout_constraintEnd_toStartOf="@+id/guideline2"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="45dp"
        android:layout_marginEnd="16dp"
        android:text="Student ID: "
        android:textSize="23sp"
        app:layout_constraintEnd_toStartOf="@+id/guideline2"
        app:layout_constraintTop_toBottomOf="@+id/button" />

    <EditText
        android:id="@+id/inputText"
        android:layout_width="163dp"
        android:layout_height="38dp"
        android:layout_marginStart="16dp"
        android:background="@android:color/holo_orange_light"
        android:ems="10"
        android:inputType="text"
        android:textSize="23sp"
        app:layout_constraintBaseline_toBaselineOf="@+id/textView2"
        app:layout_constraintStart_toStartOf="@+id/guideline2" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.5" />

    <TextView
        android:id="@+id/outputContent"
        android:layout_width="312dp"
        android:layout_height="236dp"
        android:background="#99C369"
        android:textAlignment="center"
        android:textColor="@color/colorPrimary"
        android:textSize="26sp"
        android:textStyle="bold|italic"
        android:scrollbars="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/inputText" />

    <Button
        android:id="@+id/button2"
        android:layout_width="150dp"
        android:layout_height="71dp"
        android:layout_marginStart="25dp"
        android:background="#F3BABA"
        android:onClick="doClear"
        android:text="Clear"
        android:textColor="#DD6363"
        android:textSize="24sp"
        app:layout_constraintBaseline_toBaselineOf="@+id/button"
        app:layout_constraintStart_toStartOf="@+id/guideline2" />
</androidx.constraintlayout.widget.ConstraintLayout>

A: Do it like this:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    >

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="45dp"
        android:text="My New App"
        android:textAlignment="center"
        android:textColor="@color/colorPrimary"
        android:textSize="25sp"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.5"
        />

    <Button
        android:id="@+id/button"
        android:layout_width="135dp"
        android:layout_height="72dp"
        android:layout_marginTop="24dp"
        android:background="@android:color/holo_green_light"
        android:text="Press me"
        android:textAlignment="center"
        android:textColor="@android:color/background_light"
        android:textSize="24sp"
        app:layout_constraintEnd_toStartOf="@+id/guideline2"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView"
        />

    <Button
        android:id="@+id/button2"
        android:layout_width="150dp"
        android:layout_height="71dp"
        android:layout_marginTop="24dp"
        android:background="#F3BABA"
        android:text="Clear"
        android:textColor="#DD6363"
        android:textSize="24sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="@+id/guideline2"
        app:layout_constraintTop_toBottomOf="@+id/textView"
        />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp"
        android:layout_marginEnd="24dp"
        android:text="Student ID: "
        android:textSize="23sp"
        app:layout_constraintEnd_toStartOf="@+id/guideline2"
        app:layout_constraintTop_toBottomOf="@+id/button"
        />

    <EditText
        android:id="@+id/inputText"
        android:layout_width="163dp"
        android:layout_height="38dp"
        android:background="@android:color/holo_orange_light"
        android:ems="10"
        android:inputType="text"
        android:textSize="23sp"
        app:layout_constraintBottom_toBottomOf="@+id/textView2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="@+id/guideline2"
        app:layout_constraintTop_toTopOf="@+id/textView2"
        />

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_margin="64dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/inputText"
        >

        <TextView
            android:id="@+id/outputContent"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center"
            android:background="#99C369"
            android:scrollbars="vertical"
            android:text="@string/long_string"
            android:textAlignment="center"
            android:textColor="@color/colorPrimary"
            android:textSize="26sp"
            android:textStyle="bold|italic"
            />

    </FrameLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

The thing that was making Your layout like this was android:scrollbars="vertical". So I up it in the frame and now it is not interrupting Your Views.
Result (before and after clicking EditText):

And don't forget to add:
((TextView) findViewById(R.id.outputContent)).setMovementMethod(new ScrollingMovementMethod());

in Your activity class to enable scrolling in output TextView.

You don't even need FrameLayout and You can just add this TextView:
<TextView
    android:id="@+id/outputContent"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_gravity="center"
    android:layout_margin="64dp"
    android:background="#99C369"
    android:scrollbars="vertical"
    android:text="@string/long_string"
    android:textAlignment="center"
    android:textColor="@color/colorPrimary"
    android:textSize="26sp"
    android:textStyle="bold|italic"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/inputText"
    />

The only thing that You have to set is height. It has to be 0dp and constrained to bottom and top. Then You can apply margins that You want


text:
Q: Hello, I want to change this time stamp from human readable to a simple date So, im am not a programer but I inspected WP job manager files so I could change "Posted %s ago" to a normal date time format like day/month/year as my native language is not english and I think translating it would be much easier as its my first time dabbling with this.
So here is the code:
/**
 * Displays the published date of the job listing.
 *
 * @since 1.25.3
 * @param int|WP_Post $post (default: null).
 */
function the_job_publish_date( $post = null ) {
    $date_format = get_option( 'job_manager_date_format' );

    if ( 'default' === $date_format ) {
        $display_date = esc_html__( 'Posted on ', 'wp-job-manager' ) . wp_date( get_option( 'date_format' ), get_post_timestamp( $post ) );
    } else {
        // translators: Placeholder %s is the relative, human readable time since the job listing was posted.
        $display_date = sprintf( esc_html__( 'Posted %s ago', 'wp-job-manager' ), human_time_diff( get_post_timestamp( $post ), time() ) );
    }

    echo '<time datetime="' . esc_attr( get_post_datetime( $post )->format( 'Y-m-d' ) ) . '">' . wp_kses_post( $display_date ) . '</time>';
}

/**
 * Gets the published date of the job listing.
 *
 * @since 1.25.3
 * @param int|WP_Post $post (default: null).
 * @return string|int|false
 */
function get_the_job_publish_date( $post = null ) {
    $date_format = get_option( 'job_manager_date_format' );

    if ( 'default' === $date_format ) {
        return wp_date( get_option( 'date_format' ), get_post_datetime()->getTimestamp() );
    } else {
        // translators: Placeholder %s is the relative, human readable time since the job listing was posted.
        return sprintf( __( 'Posted %s ago', 'wp-job-manager' ), human_time_diff( get_post_timestamp(), time() ) );
    }
}

When I replace "Posted %s ago" with anithing, it changes to website as well.
I want just a simple date time from when the job was posted
(Also first time asking here for help)


text:
Q: base64 decode a mysql column before performing a WHERE Basically - its a long story - but I have a field in a database that is encoded as a base64 string.
EG: this is stored in the database:
YToyOntzOjIwOiJUeXBlX29mX29yZ2FuaXNhdGlvbiI7czoyMDoiTWVtYmVyIG9mIFBhcmxpYW1lbnQiO3M6ODoiUG9zdGNvZGUiO3M6NzoiUEUxIDFKQSI7fQ==

Which equals this:
a:2:{s:20:"Type_of_organisation";s:20:"Member of Parliament";s:8:"Postcode";s:7:"#postcode#";}

What I want to be able to do is select where this string LIKE '%Member of Parliament%'. Is there any way to base64 decode a mysql column before performing a WHERE?
eg: SELECT * FROM table WHERE base64_decode(column) LIKE '%Member of Parliament%'
Thanks

A: If you're using MySQL 5.6.1 or higher you can use the FROM_BASE64() function:

Takes a string encoded with the base-64 encoded rules used by TO_BASE64() and returns the decoded result as a binary string. The result is NULL if the argument is NULL or not a valid base-64 string. See the description of TO_BASE64() for details about the encoding and decoding rules.
This function was added in MySQL 5.6.1.
mysql> SELECT TO_BASE64('abc'), FROM_BASE64(TO_BASE64('abc'));
          -> 'JWJj', 'abc'

*

*http://dev.mysql.com/doc/refman/5.6/en/string-functions.html#function_from-base64
Otherwise you can use the User Defined Function from: https://github.com/y-ken/mysql-udf-base64


text:
Q: Event handler not working in external JS file? This works: (Keeping it all in one file)

    //content-wrapper --> ajax loaded

This doesn't: I'm not getting any errors, but the event handler doesn't fire; console stays empty

func_rows.js:
$(document).ajaxComplete(function(event, xhr, settings) {
    var a_row_id = 0;
    $('body').on('click', '.ready-create-rename-row', function() {
        a_row_id = $(this).data('row-id');
        console.log('Attempting to rename row ' + a_row_id);
    });
    //Other events here get fired however
});

Ajax loaded content:

    <button type="button" class="flat circle ready-create-rename-row"
                 data-row-id=<?php echo $r->id; ?>
                 data-label-id='row_rename_<?php echo $r->id; ?>'
                 data-toggle="modal"
                 data-target="#rename-row-modal">

    </button>

                Rename Row

                    Row name
                    <input type="text" id="create-new-row-name" required>

          <button type="button" class="btn btn-default flat" data-dismiss="modal">cancel</button>
          <button type="button" class="btn btn-default flat" id="create-rename-row">rename</button>

What's confusing me is that the other event handlers in ajaxComplete in func_rows.js get fired even when they're bound to ajax-loaded elements. What I'm expecting is that when you click on the button with .ready-create-rename-row a message will pop up in the console, but nothing happens. But when I put the event handler in the same html file (serving as the template), it works.

A: Turns out the culprit is another method in the ajaxComplete handler:
$('body').off().on('click', '.rename-row' function()
{
   //stuff

    $.ajax({
     //Stuff
    });
 });

The .off() was basically disabling all the events that came before it, so I had to put it at the top and just changed the 'body' to the class .rename-row' to be much safer.


text:
Q: SharedSizeGroup Naming Rules I have a question about naming SharedSizeGroups in WPF grids mostly out of curiosity. I noticed on MSDN that they list restrictions for the group's string name:

The SharedSizeGroup property value must satisfy the following rules:

*

*Must not be empty.

*Must only consist of letters, digits, and underscore characters.

*Must not start with a numeric value.

I have some groups that I named numerically ("1", "2", "3", etc.) and have never had a problem with them. Just for kicks I renamed some groups to something like ",-[]" and they still worked too. So these rules are not enforced and seemingly not necessary. Does anybody know the reason for the rules in the documentation? Is it possible for the names to conflict with something that WPF is doing internally?
Edit: Okay, so WPF does enforce it after all, validation just doesn't fire in my non-compiled templates.

A: Interesting, I took a look at the DefinitionBase class in reflector and the SharedSizeGroup property.
It creates a dependency property with a validation callback defined as the following:
SharedSizeGroupProperty = DependencyProperty.Register("SharedSizeGroup", typeof(string), typeof(DefinitionBase), new FrameworkPropertyMetadata(new PropertyChangedCallback(DefinitionBase.OnSharedSizeGroupPropertyChanged)), new ValidateValueCallback(DefinitionBase.SharedSizeGroupPropertyValueValid));

private static bool SharedSizeGroupPropertyValueValid(object value)
    {
        if (value == null)
        {
            return true;
        }
        string str = (string)value;
        if (str != string.Empty)
        {
            int num = -1;
            while (++num < str.Length)
            {
                bool flag = char.IsDigit(str[num]);
                if (((num == 0) && flag) || ((!flag && !char.IsLetter(str[num])) && ('_' != str[num])))
                {
                    break;
                }
            }
            if (num == str.Length)
            {
                return true;
            }
        }
        return false;
    }

I tested this, and it does in fact return false for anything containing non-numeric, non-alpha, non-underscore characters. It also returns false for any group starting with a number. So it seems to follow general variable name rules..
My guess is this would most likely throw some sort of exception, but perhaps it is being handled. Have you checked the output window?
I tried an invalid name, and I got an XAMLParseException.


text:
Q: li and parent div size mismatch practicing on css dropdown. In the following code, I have set the li as block display type. Now I want the size of the li (the green dropdown ones inside the grey colored parent div .dropdown) to be exactly the same horizontal size as of their parent div .dropdown . In the current case, their horizontal size is smaller (please see the screenshot below to understand better)

Kindly please provide a solution.

html,body {
    margin: 0px;
    height: 100%;
    width: 100%;
    left: 0px;
    top: 0px;
    background-color: rgba(0,0,0,1);
    padding: 0px;
    }

*{
    box-sizing:border-box;
}

a {
 color: rgba(0,0,0,1);
 text-decoration: none;
 /* [disabled]background-color: rgba(255,0,0,1); */
 display: block;
}

li {
 display: block;
 width: 100%;
 background-color: rgba(0,255,0,1);
 border: thin solid rgba(0,0,0,1);
 position: relative;
 margin-right: auto;
 margin-left: auto;
 left: 0px;
 top: 0px;
}

.dropdown a {
 /* [disabled]color: rgba(0,255,0,1); */
 display: block;
 text-decoration: none;
 list-style-type: none;
 /* [disabled]background-color: rgba(204,51,153,1); */
 width: 100%;
}

a:hover {
    color: rgba(0,0,255,1);
}

.wrapper {
    height: 600px;
    max-width: 960px;
    margin-left: auto;
    left: 0px;
    top: 0px;
    background-color: rgba(204,204,204,1);
    margin-right: auto;
    position: relative;
    padding: 0px;
    margin-top: 0px;
}

.content {
    position: relative;
    box-sizing: border-box;
    height: 100%;
    max-height: 200px;
    max-width: 600px;
    background-color: #FFF;
    margin-right: auto;
    margin-left: auto;
    margin-top: 0px;
    left: 0px;
    right: 0px;
    font-size: 32px;
    text-align: center;
    border: 3px solid rgba(0,0,0,1);
    border-radius: 15px 15px 0px 0px;
    width: 100%;
}

.content-small {
    max-width: 100px;
    height: 100%;
    max-height: 50px;
    background-color: rgba(0,255,204,1);
    position: relative;
    margin-right: auto;
    margin-left: auto;
    border: 3px solid rgba(0,0,0,1);
    top: 5px;
  margin-top:10px;
}

.content-small:hover + .dropdown{
    visibility: visible;
}

.dropdown:hover{
 visibility: visible;
}

.dropdown {
 background-color: rgba(214,214,214,1);
 max-width: 200px;
 height: 100%;
 max-height: 100px;
 position: relative;
 margin-right: auto;
 margin-left: auto;
 top: 0px;
 margin-top: 5px;
 visibility: hidden;
 list-style-type: none;
 text-align: center;
}

  Home

Home1

Home2

A: Adding padding:0 to your dropdown

html,
body {
  margin: 0px;
  height: 100%;
  width: 100%;
  left: 0px;
  top: 0px;
  background-color: rgba(0, 0, 0, 1);
  padding: 0px;
}
* {
  box-sizing: border-box;
}
a {
  color: rgba(0, 0, 0, 1);
  text-decoration: none;
  /* [disabled]background-color: rgba(255,0,0,1); */
  display: block;
}
li {
  display: block;
  width: 100%;
  background-color: rgba(0, 255, 0, 1);
  border: thin solid rgba(0, 0, 0, 1);
  position: relative;
  margin-right: auto;
  margin-left: auto;
  left: 0px;
  top: 0px;
}
.dropdown a {
  /* [disabled]color: rgba(0,255,0,1); */
  display: block;
  text-decoration: none;
  list-style-type: none;
  /* [disabled]background-color: rgba(204,51,153,1); */
  width: 100%;
}
a:hover {
  color: rgba(0, 0, 255, 1);
}
.wrapper {
  height: 600px;
  max-width: 960px;
  margin-left: auto;
  left: 0px;
  top: 0px;
  background-color: rgba(204, 204, 204, 1);
  margin-right: auto;
  position: relative;
  padding: 0px;
  margin-top: 0px;
}
.content {
  position: relative;
  box-sizing: border-box;
  height: 100%;
  max-height: 200px;
  max-width: 600px;
  background-color: #FFF;
  margin-right: auto;
  margin-left: auto;
  margin-top: 0px;
  left: 0px;
  right: 0px;
  font-size: 32px;
  text-align: center;
  border: 3px solid rgba(0, 0, 0, 1);
  border-radius: 15px 15px 0px 0px;
  width: 100%;
}
.content-small {
  max-width: 100px;
  height: 100%;
  max-height: 50px;
  background-color: rgba(0, 255, 204, 1);
  position: relative;
  margin-right: auto;
  margin-left: auto;
  border: 3px solid rgba(0, 0, 0, 1);
  top: 5px;
  margin-top: 10px;
}
.content-small:hover + .dropdown {
  visibility: visible;
}
.dropdown:hover {
  visibility: visible;
}
.dropdown {
  background-color: rgba(214, 214, 214, 1);
  max-width: 200px;
  height: 100%;
  max-height: 100px;
  position: relative;
  margin-right: auto;
  margin-left: auto;
  top: 0px;
  margin-top: 5px;
  visibility: hidden;
  list-style-type: none;
  text-align: center;
  padding:0;
}

      Home

Home1

Home2

The gray below the list items comes from the height you set on the

A: Your
 has some default studying for a
 tag in it, in this case padding-left:40px; and then the height attribute you gave it. try the following CSS:
.dropdown {
padding-left:0;
height:initial;
}

You can also just remove the height attribute

A: Did you try a  CSS reset for margins and/or padding?  The UL is one of the HTML elements that has margins applied in the default browser CSS.
For a quick fix try:
ul { margin: 0; padding: 0; }


text:
Q: Ember data DS.JSONAPIAdapter pagination I am working on a project using EmberJS 2.1 and EmberData 2.1.
Everything is good but seems I am not able to understand how can I paginate results from the API.
Current response that I get from the API:
{
  "data": [
    {
      "type": "user",
      "attributes": {
        "firstName": "John",
        "lastName": "Doe",
        "company": "Google",
        "id": "1",
        "title": "Mr.",
        "email": "john@doe.com"
      },
      "id": "1"
    },
    {
      "type": "user",
      "attributes": {
        "firstName": "John",
        "lastName": "Doe",
        "company": "Google",
        "id": "2",
        "title": "Mr.",
        "email": "john@doe.com"
      },
      "id": "2"
    },
    {
      "type": "user",
      "attributes": {
        "firstName": "John",
        "lastName": "Doe",
        "company": "Google",
        "id": "3",
        "title": "Mr.",
        "email": "john@doe.com"
      },
      "id": "3"
    },
    {
      "type": "user",
      "attributes": {
        "firstName": "John",
        "lastName": "Doe",
        "company": "Google",
        "id": "4",
        "title": "Mr.",
        "email": "john@doe.com"
      },
      "id": "4"
    }
  ]
}

and my route looks like this:
import Ember from 'ember';
import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';

export default Ember.Route.extend(AuthenticatedRouteMixin, {
    model: function(){
        return this.store.findAll('user');
    }
});

Is there any resource where I can learn how to implement pagination? I've found a lot of tutorials, but they're for DS.RESTAdapter.
The API was built with Spring MVC.
Thank you

A: One way to implement pagination is to make sure your API is returning metadata relating to the request. You need the count of results returned in the response, and the total number of resource available. It also needs to be able to respond to query paramaters for page[offset] and page[limit] so it knows which results to send back to you.
Ember side - you will need to have a query parameter for pageLimit and pageOffset, the offset needs to be calculated by you depending on how many records are in your store and sent to the server as part of the request so it knows from where to start giving you back data. The limit is just the number of results you want back each time.

A: We are using same libraries and there are 2 alternatives that may come immediatelly handy:

*

*take advantage of already implemented solutions, say ember-addons supporting pagination, quick link:
https://www.emberaddons.com/?query=pagination

*implement it on your own, if what you need is a too custom solution. In this case I would recommend creating a query object as you need and pass it to the store.query("user", query), which, supporting out-of-the-box, parses meta-data that could be used for example: to distinguish whether there is anything more to be loaded.
I wrote a small rough snippet, please excuse any typos:
// users controller
modelName: "user",

pageSize: 10,

// pageLimit: 50, pageOffset: 0, ...
queryObject: Ember.computed("pageSize",/* more props ,*/ function(){
 const queryObject = {};
 const pageSize = this.get("pageSize");

//... validate pageSize and currentPage values, are they numbers, positive numbers, whatever.....

 queryObject.page = {
  page: pageSize
 };

 return queryObject;
}),

....

actions{
 fetchPage(pageIndex){
  // check pageIndex....

  // retrieve actual queryObject
  const queryObject = this.get("queryObject");

  // set which batch we are going to load now, "cursor" is just an example, depends what your backend expects
  queryObject.page.cursor = pageIndex;

  // query records
  return this.store.query(this.get("modelName"), queryObject)
   .then(/*...do sth with fetched records, update model, retrieve metadata...*/)
   .catch(/*...take care of error...*/);
 }
}


text:
Q: JavaScript looping issue in the middle of looping Hey guys I m trying to loop over the array of numbers, and what i want my function to do is whenever it is position of a number in array is EVEN number I want a program to return me 'Yan' word in stead of number. but when the position of a number is ODD number i want it to return just a number.
But for some reason in the middle of the array I am getting 'Yan' word instead of getting a number.

const valid1 = [4, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8]
const reversValid1 = valid1.reverse()

const myArray = []

const validateCard = (arr) =>{
    for(let i = 0; i < arr.length; i++){
        if(arr.indexOf(reversValid1[i])%2 == 1){
            console.log('Yan')
        }
        else{
            console.log(arr[i])
        }
    }
}

validateCard(reversValid1)

I m getting the following response:

8
Yan
8
Yan
1
Yan
8
Yan
9
Yan
Yan
Yan
9
Yan
5
Yan

You can see i m getting 3 Yan consecutively.

A: Why instead of use indexOf don't use directly i ?

const valid1 = [4, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8]
const reversValid1 = valid1.reverse()

const myArray = []

const validateCard = (arr) => {
  for (let i = 0; i < arr.length; i++) {
    if (i % 2 == 1) {
      console.log('Yan')
    } else {
      console.log(arr[i])
    }
  }
}

validateCard(reversValid1)

The problem is indexOf will find multiple index of same number.
Example:

const valid1 = [4, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8]
const reversValid1 = valid1.reverse()
for (let i = 0; i < reversValid1.length; i++) {
  console.log(reversValid1[i], reversValid1.indexOf(reversValid1[i]))
}

As you can see the same number have same index instead of index of array.

A: You can use Array.forEach:

const valid1 = [4, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8];
const reversValid1 = valid1.slice().reverse();

const validateCard = (arr) => {
  arr.forEach((v,i)=>{
    if (i%2 == 0) {
      console.log('Yan');
    } else {
      console.log(v);
    }
  });
};

validateCard(reversValid1);

A: This might be what you want:

const valid1 = [4, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8];
const reversValid1 = valid1.reverse();

const myArray = []

const validateCard = (arr) => {
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] % 2 === 0) {
            console.log('Yan');
        }
        else {
            console.log(arr[i]);
        }
    }
}

validateCard(reversValid1);

Or this:

const valid1 = [4, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8];
const reversValid1 = valid1.reverse();

const validateCard2 = (arr) => {
    for (let i = 0; i < arr.length; i++) {
        if (i % 2 === 0) {
            console.log('Yan');
        }
        else {
            console.log(arr[i]);
        }
    }
}

validateCard2(reversValid1);


text:
Q: R bfast: Error in stl(Yt, "periodic") : series is not periodic or has less than two periods I am trying to run bfast::bfast() for time series analysis of a dataset for the year 2003 with 365 observations. Unfortunately I always get the same Error message. I would be grateful for your help!
mydata_2003 <- mydata[1:365, ]
# to extract the data for the year 2003 from a dataframe
# (each row one observation)

mydata_2003_ts <- ts(data = mydata_2003$area, start = c(2003, 1),
                     end = c(2003, 12), frequency = 365)
# convert the data for the year 2003 into a ts-object

mydata_2003_bfast <- bfast(Yt = mydata_2003_ts, season = "dummy",
                           max.iter = 1)

Error in stl(Yt, "periodic") :
      series is not periodic or has less than two periods