问:
Facebook Messenger Verify X-Hub-Signature of Shared Location
I'm adding X-Hub verification to my messenger app. I learned about it here: https://developers.facebook.com/docs/messenger-platform/webhook-reference

I've successfully gotten verification to work with simple text messages, but when I send a location instead of a text message, verification fails because the hash I generate and the hash Facebook gives me in the header do not match. Here is my verification code:

```<code>module.exports.requestIsValid = function(event) {
    if (event['headers']['X-Hub-Signature']) {
        var sha     = event['headers']['X-Hub-Signature']
        var body    = JSON.stringify(event.body);
        return sha == `sha1=${crypto.createHmac('sha1', config.APP_SECRET).update(body).digest('hex')}`;
    }

    return false;   // this return is never called, I know that the first return is the one returning false when it should be true
 }
</code>```

Here is an example of a regular text message payload:

```<code>{"body":{"object":"page","entry":[{"id":"1366222643461024","time":1499114399253,"messaging":[{"sender":{"id":"1582085681843981"},"recipient":{"id":"1366222643461024"},"timestamp":1499114399084,"message":{"mid":"mid.$cAASAZhi0_wRjO3OtbFdCi5lV2qe4","seq":52192,"text":"Test"}}]}]},"method":"POST","principalId":"offlineContext_authorizer_principalId","headers":{"X-Real-Ip":"173.252.88.182","X-Forwarded-For":"173.252.88.182","Host":"test.localtunnel.me","X-Forwarded-Proto":"https","X-Nginx-Proxy":"true","Connection":"close","Content-Length":"270","Accept":"*/*","Accept-Encoding":"deflate, gzip","Content-Type":"application/json","X-Hub-Signature":"sha1=0f51d788fe5f1111846097ad016728cdcd06029f"},"query":{},"path":{},"identity":{"accountId":"offlineContext_accountId","apiKey":"offlineContext_apiKey","caller":"offlineContext_caller","cognitoAuthenticationProvider":"offlineContext_cognitoAuthenticationProvider","cognitoAuthenticationType":"offlineContext_cognitoAuthenticationType","sourceIp":"127.0.0.1","user":"offlineContext_user","userAgent":"","userArn":"offlineContext_userArn"},"stageVariables":{},"isOffline":true}
</code>```

And here is an example of a payload with a location:

```<code>{"body":{"object":"page","entry":[{"id":"1366222643461024","time":1499114451619,"messaging":[{"sender":{"id":"1582085681843981"},"recipient":{"id":"1366222643461024"},"timestamp":1499114451469,"message":{"mid":"mid.$cAASAZhi0_wRjO3R6DVdCi8v9yqk0","seq":52196,"attachments":[{"title":"Brandon's Location","url":"https://l.facebook.com/l.php?u=https%3A%2F%2Fwww.bing.com%2Fmaps%2Fdefault.aspx%3Fv%3D2%26pc%3DFACEBK%26mid%3D8100%26where1%3D35.142236316764%252C%2B-106.53531087607%26FORM%3DFBKPL1%26mkt%3Den-US&h=ATOu8uYrLDiFl6wG8RVfhXvwkMl7uB_l2MHqB_uKLhk8qC9p1ua0EOLpGkznVX7Y8YfxSXP7vDuAR7swPmDCw1esH2bwKhNNsZKxVPC2ViC2AFMO_g&s=1&enc=AZMYxff8btvCZWHtzUR4oFL7K2Mg6nXM_O_tRXXL-L8z508UAOauiSRztoRvWdlGCWU1dNRdNK1ls2CGulM8lvzR","type":"location","payload":{"coordinates":{"lat":35.142236316764,"long":-106.53531087607}}}]}}]}]},"method":"POST","principalId":"offlineContext_authorizer_principalId","headers":{"X-Real-Ip":"173.252.90.239","X-Forwarded-For":"173.252.90.239","Host":"test.localtunnel.me","X-Forwarded-Proto":"https","X-Nginx-Proxy":"true","Connection":"close","Content-Length":"911","Accept":"*/*","Accept-Encoding":"deflate, gzip","Content-Type":"application/json","X-Hub-Signature":"sha1=34f23436b2744b9b0cc8776922e7386c454786db"},"query":{},"path":{},"identity":{"accountId":"offlineContext_accountId","apiKey":"offlineContext_apiKey","caller":"offlineContext_caller","cognitoAuthenticationProvider":"offlineContext_cognitoAuthenticationProvider","cognitoAuthenticationType":"offlineContext_cognitoAuthenticationType","sourceIp":"127.0.0.1","user":"offlineContext_user","userAgent":"","userArn":"offlineContext_userArn"},"stageVariables":{},"isOffline":true}
</code>```

Happy to provide extra info if needed.

UPDATE:
Upon furthere inspection it appears that the verifcation only fails when there is an "attatchments" field in the payload. So if also fails when I send a picture or gif or something like that.

答: You should apply the SHA1 algorithm to the 'raw request body'. If you parse body and convert it back to json; it may not work.</p>

Body:
I'm adding X-Hub verification to my messenger app. I learned about it here: https://developers.facebook.com/docs/messenger-platform/webhook-reference

I've successfully gotten verification to work with simple text messages, but when I send a location instead of a text message, verification fails because the hash I generate and the hash Facebook gives me in the header do not match. Here is my verification code:

module.exports.requestIsValid = function(event) {
    if (event['headers']['X-Hub-Signature']) {
        var sha     = event['headers']['X-Hub-Signature']
        var body    = JSON.stringify(event.body);
        return sha == `sha1=${crypto.createHmac('sha1', config.APP_SECRET).update(body).digest('hex')}`;
    }

    return false;   // this return is never called, I know that the first return is the one returning false when it should be true
 }

Here is an example of a regular text message payload:

{"body":{"object":"page","entry":[{"id":"1366222643461024","time":1499114399253,"messaging":[{"sender":{"id":"1582085681843981"},"recipient":{"id":"1366222643461024"},"timestamp":1499114399084,"message":{"mid":"mid.$cAASAZhi0_wRjO3OtbFdCi5lV2qe4","seq":52192,"text":"Test"}}]}]},"method":"POST","principalId":"offlineContext_authorizer_principalId","headers":{"X-Real-Ip":"173.252.88.182","X-Forwarded-For":"173.252.88.182","Host":"test.localtunnel.me","X-Forwarded-Proto":"https","X-Nginx-Proxy":"true","Connection":"close","Content-Length":"270","Accept":"*/*","Accept-Encoding":"deflate, gzip","Content-Type":"application/json","X-Hub-Signature":"sha1=0f51d788fe5f1111846097ad016728cdcd06029f"},"query":{},"path":{},"identity":{"accountId":"offlineContext_accountId","apiKey":"offlineContext_apiKey","caller":"offlineContext_caller","cognitoAuthenticationProvider":"offlineContext_cognitoAuthenticationProvider","cognitoAuthenticationType":"offlineContext_cognitoAuthenticationType","sourceIp":"127.0.0.1","user":"offlineContext_user","userAgent":"","userArn":"offlineContext_userArn"},"stageVariables":{},"isOffline":true}

And here is an example of a payload with a location:

{"body":{"object":"page","entry":[{"id":"1366222643461024","time":1499114451619,"messaging":[{"sender":{"id":"1582085681843981"},"recipient":{"id":"1366222643461024"},"timestamp":1499114451469,"message":{"mid":"mid.$cAASAZhi0_wRjO3R6DVdCi8v9yqk0","seq":52196,"attachments":[{"title":"Brandon's Location","url":"https://l.facebook.com/l.php?u=https%3A%2F%2Fwww.bing.com%2Fmaps%2Fdefault.aspx%3Fv%3D2%26pc%3DFACEBK%26mid%3D8100%26where1%3D35.142236316764%252C%2B-106.53531087607%26FORM%3DFBKPL1%26mkt%3Den-US&h=ATOu8uYrLDiFl6wG8RVfhXvwkMl7uB_l2MHqB_uKLhk8qC9p1ua0EOLpGkznVX7Y8YfxSXP7vDuAR7swPmDCw1esH2bwKhNNsZKxVPC2ViC2AFMO_g&s=1&enc=AZMYxff8btvCZWHtzUR4oFL7K2Mg6nXM_O_tRXXL-L8z508UAOauiSRztoRvWdlGCWU1dNRdNK1ls2CGulM8lvzR","type":"location","payload":{"coordinates":{"lat":35.142236316764,"long":-106.53531087607}}}]}}]}]},"method":"POST","principalId":"offlineContext_authorizer_principalId","headers":{"X-Real-Ip":"173.252.90.239","X-Forwarded-For":"173.252.90.239","Host":"test.localtunnel.me","X-Forwarded-Proto":"https","X-Nginx-Proxy":"true","Connection":"close","Content-Length":"911","Accept":"*/*","Accept-Encoding":"deflate, gzip","Content-Type":"application/json","X-Hub-Signature":"sha1=34f23436b2744b9b0cc8776922e7386c454786db"},"query":{},"path":{},"identity":{"accountId":"offlineContext_accountId","apiKey":"offlineContext_apiKey","caller":"offlineContext_caller","cognitoAuthenticationProvider":"offlineContext_cognitoAuthenticationProvider","cognitoAuthenticationType":"offlineContext_cognitoAuthenticationType","sourceIp":"127.0.0.1","user":"offlineContext_user","userAgent":"","userArn":"offlineContext_userArn"},"stageVariables":{},"isOffline":true}

Happy to provide extra info if needed.

UPDATE:
Upon furthere inspection it appears that the verifcation only fails when there is an "attatchments" field in the payload. So if also fails when I send a picture or gif or something like that.


来源: stackexchange

问:
Crontab to run a bash script that runs multiple python scripts
I'm a beginner in linux. I want run multiple python scripts every 30 second and I'm planning to do this using a bash script ( to run multiple python scripts simultaneously) and crontab (to schedule the scripts to run every 30 sec).

This is how my bash script:

```<code>#!/bin/bash
# This script is used to run multiple python script to query all types and all modes of GTFSR data

#Set working directory
cd "${0%/*}"

#BUS Query Real Time
python gtfsrdb_tfnsw.py -p 'https://api.transport.nsw.gov.au/v1/gtfs/vehiclepos/buses' --database="postgresql://localhost/test" —apikey="XXX" -m "buses" -c -1 &
python gtfsrdb_tfnsw.py -t 'https://api.transport.nsw.gov.au/v1/gtfs/realtime/buses' --database="postgresql://localhost/test" --apikey="XXX" -m "buses" -c -1 &
python gtfsrdb_tfnsw.py -a 'https://api.transport.nsw.gov.au/v1/gtfs/alerts/buses' --database="postgresql://localhost/test" --apikey="XXX" -m "buses" -c -1 &

#Sydney Train Real Time
python gtfsrdb_tfnsw.py -p 'https://api.transport.nsw.gov.au/v1/gtfs/vehiclepos/sydneytrains' --database="postgresql://localhost/test" --apikey="XXX" -m "sydneytrains" -c -1 &
python gtfsrdb_tfnsw.py -t 'https://api.transport.nsw.gov.au/v1/gtfs/realtime/sydneytrains' --database="postgresql://localhost/test" --apikey="XXX" -m "sydneytrains" -c -1 &
python gtfsrdb_tfnsw.py -a 'https://api.transport.nsw.gov.au/v1/gtfs/alerts/sydneytrains' --database="postgresql://localhost/test" --apikey="XXX" -m "sydneytrains" -c -1 &

#Ferries Real Time
python gtfsrdb_tfnsw.py -p 'https://api.transport.nsw.gov.au/v1/gtfs/vehiclepos/ferries' --database="postgresql://localhost/test" --apikey="XXX" -m "ferries" -c -1 &
python gtfsrdb_tfnsw.py -t 'https://api.transport.nsw.gov.au/v1/gtfs/realtime/ferries' --database="postgresql://localhost/test" --apikey="XXX" -m "ferries" -c -1 &
python gtfsrdb_tfnsw.py -a 'https://api.transport.nsw.gov.au/v1/gtfs/alerts/ferries' --database="postgresql://localhost/test" --apikey="XXX" -m "ferries" -c -1 &

#lightrail Real Time
python gtfsrdb_tfnsw.py -p 'https://api.transport.nsw.gov.au/v1/gtfs/vehiclepos/lightrail' --database="postgresql://localhost/test" --apikey="XXX" -m "lightrail" -c -1 &
python gtfsrdb_tfnsw.py -t 'https://api.transport.nsw.gov.au/v1/gtfs/realtime/lightrail' --database="postgresql://localhost/test" --apikey="XXX" -m "lightrail" -c -1 &
python gtfsrdb_tfnsw.py -a 'https://api.transport.nsw.gov.au/v1/gtfs/alerts/lightrail' --database="postgresql://localhost/test" --apikey="XXX" -m "lightrail" -c -1 &

#nswtrains Real Time
python gtfsrdb_tfnsw.py -p 'https://api.transport.nsw.gov.au/v1/gtfs/vehiclepos/nswtrains' --database="postgresql://localhost/test" --apikey="XXX" -m "nswtrains" -c -1 &
python gtfsrdb_tfnsw.py -t 'https://api.transport.nsw.gov.au/v1/gtfs/realtime/nswtrains' --database="postgresql://localhost/test" --apikey="XXX" -m "nswtrains" -c -1 &
python gtfsrdb_tfnsw.py -a 'https://api.transport.nsw.gov.au/v1/gtfs/alerts/nswtrains' --database="postgresql://localhost/test" --apikey="XXX" -m "nswtrains" -c -1 &
</code>```

This is what I put in crontab:

```<code># GTFSR to Database
* * * * * ( /bin/bash /home/amarinS/projects/TfNSW_GTFSRDB/GTFSR_call)
* * * * * ( sleep 30 ; /bin/bash /home/amarinS/projects/TfNSW_GTFSRDB/GTFSR_call)
</code>```

If I run /bin/bash /home/amarinS/projects/TfNSW_GTFSRDB/GTFSR_call manually, the bash script works fine. However nothing happens when the job is run via CRONTAB.

Please help.

Cheers!

答:
Make sure you are creating the cron entries as root. I have had that get me in the past.

Verify your env variables and the python interpreter.

Make sure all the scripts are executable.

ContentLicense: CC BY-SA 3.0

Body:
I'm a beginner in linux. I want run multiple python scripts every 30 second and I'm planning to do this using a bash script ( to run multiple python scripts simultaneously) and crontab (to schedule the scripts to run every 30 sec).

This is how my bash script:

#!/bin/bash
# This script is used to run multiple python script to query all types and all modes of GTFSR data

#Set working directory
cd "${0%/*}"

#BUS Query Real Time
python gtfsrdb_tfnsw.py -p 'https://api.transport.nsw.gov.au/v1/gtfs/vehiclepos/buses' --database="postgresql://localhost/test" —apikey="XXX" -m "buses" -c -1 &
python gtfsrdb_tfnsw.py -t 'https://api.transport.nsw.gov.au/v1/gtfs/realtime/buses' --database="postgresql://localhost/test" --apikey="XXX" -m "buses" -c -1 &
python gtfsrdb_tfnsw.py -a 'https://api.transport.nsw.gov.au/v1/gtfs/alerts/buses' --database="postgresql://localhost/test" --apikey="XXX" -m "buses" -c -1 &

#Sydney Train Real Time
python gtfsrdb_tfnsw.py -p 'https://api.transport.nsw.gov.au/v1/gtfs/vehiclepos/sydneytrains' --database="postgresql://localhost/test" --apikey="XXX" -m "sydneytrains" -c -1 &
python gtfsrdb_tfnsw.py -t 'https://api.transport.nsw.gov.au/v1/gtfs/realtime/sydneytrains' --database="postgresql://localhost/test" --apikey="XXX" -m "sydneytrains" -c -1 &
python gtfsrdb_tfnsw.py -a 'https://api.transport.nsw.gov.au/v1/gtfs/alerts/sydneytrains' --database="postgresql://localhost/test" --apikey="XXX" -m "sydneytrains" -c -1 &

#Ferries Real Time
python gtfsrdb_tfnsw.py -p 'https://api.transport.nsw.gov.au/v1/gtfs/vehiclepos/ferries' --database="postgresql://localhost/test" --apikey="XXX" -m "ferries" -c -1 &
python gtfsrdb_tfnsw.py -t 'https://api.transport.nsw.gov.au/v1/gtfs/realtime/ferries' --database="postgresql://localhost/test" --apikey="XXX" -m "ferries" -c -1 &
python gtfsrdb_tfnsw.py -a 'https://api.transport.nsw.gov.au/v1/gtfs/alerts/ferries' --database="postgresql://localhost/test" --apikey="XXX" -m "ferries" -c -1 &

#lightrail Real Time
python gtfsrdb_tfnsw.py -p 'https://api.transport.nsw.gov.au/v1/gtfs/vehiclepos/lightrail' --database="postgresql://localhost/test" --apikey="XXX" -m "lightrail" -c -1 &
python gtfsrdb_tfnsw.py -t 'https://api.transport.nsw.gov.au/v1/gtfs/realtime/lightrail' --database="postgresql://localhost/test" --apikey="XXX" -m "lightrail" -c -1 &
python gtfsrdb_tfnsw.py -a 'https://api.transport.nsw.gov.au/v1/gtfs/alerts/lightrail' --database="postgresql://localhost/test" --apikey="XXX" -m "lightrail" -c -1 &

#nswtrains Real Time
python gtfsrdb_tfnsw.py -p 'https://api.transport.nsw.gov.au/v1/gtfs/vehiclepos/nswtrains' --database="postgresql://localhost/test" --apikey="XXX" -m "nswtrains" -c -1 &
python gtfsrdb_tfnsw.py -t 'https://api.transport.nsw.gov.au/v1/gtfs/realtime/nswtrains' --database="postgresql://localhost/test" --apikey="XXX" -m "nswtrains" -c -1 &
python gtfsrdb_tfnsw.py -a 'https://api.transport.nsw.gov.au/v1/gtfs/alerts/nswtrains' --database="postgresql://localhost/test" --apikey="XXX" -m "nswtrains" -c -1 &

This is what I put in crontab:

# GTFSR to Database
* * * * * ( /bin/bash /home/amarinS/projects/TfNSW_GTFSRDB/GTFSR_call)
* * * * * ( sleep 30 ; /bin/bash /home/amarinS/projects/TfNSW_GTFSRDB/GTFSR_call)

If I run /bin/bash /home/amarinS/projects/TfNSW_GTFSRDB/GTFSR_call manually, the bash script works fine. However nothing happens when the job is run via CRONTAB.

Please help.

Cheers!


问:
Change image with javascript mouse position?
I am trying to achieve an effect like what is shown on this site: https://ca.warbyparker.com/eyeglasses/women/louise/elderflower-crystal

When you move your mouse position (or thumb for mobile) the image shown will change depending on the horizontal position of the mouse.

I have been trying to get it to work in react and I am having some trouble, even with getting a working jquery or vanilla javascript solution I can't seem to get it.

What i've got so far:

HTML:

```<code><div class="product-hero">

        <div class="hero-container">
          <img class="product-hero-image left" src="http://placehold.it/708x1282/000000?text=%3C%E2%80%93+left" alt="" />
          <img class="product-hero-image middle" src="http://placehold.it/708x1282/000000?text=middle" alt="" />
          <img class="product-hero-image right" src="http://placehold.it/708x1282/000000?text=right+--%3E" alt="" />

        </div>
      </div>
</code>```

Javascript:

```<code>$(window).mousemove(getMousePosition);

    function getMousePosition(event) {
      let imageTop = $('.product-hero-image').offset().top;
      let imageLeft = $('.product-hero-image').offset().left;
      let imageBottom = imageTop + $('.product-hero-image').height();
      let imageRight = imageLeft + $('.product-hero-image').width();

      var mouseX = event.pageX;
      var mouseY = event.pageY;

      if (mouseX > imageLeft && mouseX < imageRight && mouseY < imageTop) {
        $('.product-hero-image.middle').toggle();
        console.log('top right');
      } else if (mouseX < imageLeft && mouseY < imageTop) {
        $('.product-hero-image.left').toggle();
        console.log('top left');
      } else if (mouseX < imageLeft && mouseY > imageTop && mouseY < imageBottom) {
        $('.product-hero-image.left').toggle();
        console.log('bottom left');
      } else if (mouseX < imageLeft && mouseY > imageBottom) {
        $('.product-hero-image.left').toggle();
        console.log('left');
      } else if (mouseX > imageLeft && mouseX < imageRight && mouseY > imageBottom) {
        $('.product-hero-image.middle').toggle();
        console.log('middle');
      } else if (mouseX > imageRight && mouseY > imageBottom) {
        $('.product-hero-image.right').toggle();
        console.log('right');
      } else if (mouseX > imageRight && mouseY > imageTop && mouseY < imageBottom) {
        $('.product-hero-image.right').toggle();
        console.log('bottom right');
      } else if (mouseX > imageRight && mouseY < imageTop) {
        $('.product-hero-image.right').toggle();
        console.log('top right');
      } else {
        $('.product-hero-image.middle').toggle();
        console.log('middle');
      }
    }

    $('.product-hero-image').css('z-index', '0');
</code>```

https://codepen.io/H0BB5/pen/rwqwPP

Any help is much appreciated! :)

答:
You did too much logic decisions in your code.

You have to get things easier :D. I did a fork of your code and I simplify it and it works. Check this out.

```<code>$(".product-hero").mousemove(getMousePosition);

function getMousePosition(event) {
  let elementVisible = $('.product-hero-image:visible');
  let imageTop = elementVisible.offset().top;
  let imageLeft = elementVisible.offset().left;
  let imageBottom = imageTop + elementVisible.height();
  let imageRight = imageLeft + elementVisible.width();

  var mouseX = event.pageX;
  var mouseY = event.pageY;

  if (mouseY < imageTop || mouseY > imageBottom) {
    return;
  }
  console.log(mouseY);
  elementVisible.hide();

  if (mouseX > imageLeft && mouseX < imageRight){
    $('.product-hero-image.middle').show();
  }
  else if (mouseX < imageLeft) {
    $('.product-hero-image.left').show();
  }
  else {
    $('.product-hero-image.right').show();
  }
}

$('.product-hero-image').css('z-index', '0');
</code>```

Body:
I am trying to achieve an effect like what is shown on this site: https://ca.warbyparker.com/eyeglasses/women/louise/elderflower-crystal

When you move your mouse position (or thumb for mobile) the image shown will change depending on the horizontal position of the mouse.

I have been trying to get it to work in react and I am having some trouble, even with getting a working jquery or vanilla javascript solution I can't seem to get it.

What i've got so far:

HTML:

Javascript:

$(window).mousemove(getMousePosition);

    function getMousePosition(event) {
      let imageTop = $('.product-hero-image').offset().top;
      let imageLeft = $('.product-hero-image').offset().left;
      let imageBottom = imageTop + $('.product-hero-image').height();
      let imageRight = imageLeft + $('.product-hero-image').width();

      var mouseX = event.pageX;
      var mouseY = event.pageY;

      if (mouseX > imageLeft && mouseX < imageRight && mouseY < imageTop) {
        $('.product-hero-image.middle').toggle();
        console.log('top right');
      } else if (mouseX < imageLeft && mouseY < imageTop) {
        $('.product-hero-image.left').toggle();
        console.log('top left');
      } else if (mouseX < imageLeft && mouseY > imageTop && mouseY < imageBottom) {
        $('.product-hero-image.left').toggle();
        console.log('bottom left');
      } else if (mouseX < imageLeft && mouseY > imageBottom) {
        $('.product-hero-image.left').toggle();
        console.log('left');
      } else if (mouseX > imageLeft && mouseX < imageRight && mouseY > imageBottom) {
        $('.product-hero-image.middle').toggle();
        console.log('middle');
      } else if (mouseX > imageRight && mouseY > imageBottom) {
        $('.product-hero-image.right').toggle();
        console.log('right');
      } else if (mouseX > imageRight && mouseY > imageTop && mouseY < imageBottom) {
        $('.product-hero-image.right').toggle();
        console.log('bottom right');
      } else if (mouseX > imageRight && mouseY < imageTop) {
        $('.product-hero-image.right').toggle();
        console.log('top right');
      } else {
        $('.product-hero-image.middle').toggle();
        console.log('middle');
      }
    }

    $('.product-hero-image').css('z-index', '0');

https://codepen.io/H0BB5/pen/rwqwPP

Any help is much appreciated! :)

Body:
You did too much logic decisions in your code.

You have to get things easier :D. I did a fork of your code and I simplify it and it works. Check this out.

$(".product-hero").mousemove(getMousePosition);

function getMousePosition(event) {
  let elementVisible = $('.product-hero-image:visible');
  let imageTop = elementVisible.offset().top;
  let imageLeft = elementVisible.offset().left;
  let imageBottom = imageTop + elementVisible.height();
  let imageRight = imageLeft + elementVisible.width();

  var mouseX = event.pageX;
  var mouseY = event.pageY;

  if (mouseY < imageTop || mouseY > imageBottom) {
    return;
  }
  console.log(mouseY);
  elementVisible.hide();

  if (mouseX > imageLeft && mouseX < imageRight){
    $('.product-hero-image.middle').show();
  }
  else if (mouseX < imageLeft) {
    $('.product-hero-image.left').show();
  }
  else {
    $('.product-hero-image.right').show();
  }
}

$('.product-hero-image').css('z-index', '0');


问:
json parsing in django
I've built a webhook to receive json POST. However, I'm recieving an error from json decoder. Here's the view.py file from the webhook

```<code>import json
from django.shortcuts import render
from django.views.decorators.http import require_POST
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
from .models import UserText

# Create your views here.
@csrf_exempt
@require_POST
def webhookmb(request):
    usrtxt = json.loads(request.body)

    UserText.objects.create(
        id = usrtxt['id'],
        recipient = usrtxt['recipient'],
        originator = usrtxt['originator'],
        body = usrtxt['body'],
        createdDatetime = usrtxt['createdDatetime'],
    )

    # redirect to API.AI
    # TODO

    return HttpResponse(200)
</code>```

This is the error I am receiving

```<code>2017-07-09T00:19:45.559146+00:00 app[web.1]: Internal Server Error: /webhookmb/
2017-07-09T00:19:45.559154+00:00 app[web.1]: Traceback (most recent call last):
2017-07-09T00:19:45.559155+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner
2017-07-09T00:19:45.559156+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_respon
se
2017-07-09T00:19:45.559157+00:00 app[web.1]:     response = self.process_exception_by_middleware(e, request)
2017-07-09T00:19:45.559155+00:00 app[web.1]:     response = get_response(request)
2017-07-09T00:19:45.559159+00:00 app[web.1]:     response = wrapped_callback(request, *callback_args, **callback_kwargs)
2017-07-09T00:19:45.559158+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_respon
se
2017-07-09T00:19:45.559160+00:00 app[web.1]:     return view_func(*args, **kwargs)
2017-07-09T00:19:45.559159+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_v
iew
2017-07-09T00:19:45.559161+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/django/views/decorators/http.py", line 40, in inner
2017-07-09T00:19:45.559161+00:00 app[web.1]:     return func(request, *args, **kwargs)
2017-07-09T00:19:45.559162+00:00 app[web.1]:   File "/app/webhookmb/views.py", line 12, in webhookmb
2017-07-09T00:19:45.559162+00:00 app[web.1]:     usrtxt = json.loads(request.body)
2017-07-09T00:19:45.559163+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/json/__init__.py", line 354, in loads
2017-07-09T00:19:45.559163+00:00 app[web.1]:     return _default_decoder.decode(s)
2017-07-09T00:19:45.559164+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/json/decoder.py", line 339, in decode
2017-07-09T00:19:45.559165+00:00 app[web.1]:     obj, end = self.raw_decode(s, idx=_w(s, 0).end())
2017-07-09T00:19:45.559165+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/json/decoder.py", line 357, in raw_decode
2017-07-09T00:19:45.559166+00:00 app[web.1]:     raise JSONDecodeError("Expecting value", s, err.value) from None
2017-07-09T00:19:45.559170+00:00 app[web.1]: json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
</code>```

I'm not quite sure how to approach fixing this, I've trouble shot a bunch of things however I'm stumped on how to fix json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) Any feedback would be amazing. Thanks!

答:
It may be due to an encoding mismatch.

As you haven't provided the json itself.

Try this instead.

```<code>json.loads(request.body.decode('utf-8'))
</code>```

Title: json parsing in django

Body:
I've built a webhook to receive json POST. However, I'm recieving an error from json decoder. Here's the view.py file from the webhook

import json
from django.shortcuts import render
from django.views.decorators.http import require_POST
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
from .models import UserText

# Create your views here.
@csrf_exempt
@require_POST
def webhookmb(request):
    usrtxt = json.loads(request.body)

    UserText.objects.create(
        id = usrtxt['id'],
        recipient = usrtxt['recipient'],
        originator = usrtxt['originator'],
        body = usrtxt['body'],
        createdDatetime = usrtxt['createdDatetime'],
    )

    # redirect to API.AI
    # TODO

    return HttpResponse(200)

This is the error I am receiving

2017-07-09T00:19:45.559146+00:00 app[web.1]: Internal Server Error: /webhookmb/
2017-07-09T00:19:45.559154+00:00 app[web.1]: Traceback (most recent call last):
2017-07-09T00:19:45.559155+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner
2017-07-09T00:19:45.559156+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_respon
se
2017-07-09T00:19:45.559157+00:00 app[web.1]:     response = self.process_exception_by_middleware(e, request)
2017-07-09T00:19:45.559155+00:00 app[web.1]:     response = get_response(request)
2017-07-09T00:19:45.559159+00:00 app[web.1]:     response = wrapped_callback(request, *callback_args, **callback_kwargs)
2017-07-09T00:19:45.559158+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_respon
se
2017-07-09T00:19:45.559160+00:00 app[web.1]:     return view_func(*args, **kwargs)
2017-07-09T00:19:45.559159+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_v
iew
2017-07-09T00:19:45.559161+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/django/views/decorators/http.py", line 40, in inner
2017-07-09T00:19:45.559161+00:00 app[web.1]:     return func(request, *args, **kwargs)
2017-07-09T00:19:45.559162+00:00 app[web.1]:   File "/app/webhookmb/views.py", line 12, in webhookmb
2017-07-09T00:19:45.559162+00:00 app[web.1]:     usrtxt = json.loads(request.body)
2017-07-09T00:19:45.559163+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/json/__init__.py", line 354, in loads
2017-07-09T00:19:45.559163+00:00 app[web.1]:     return _default_decoder.decode(s)
2017-07-09T00:19:45.559164+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/json/decoder.py", line 339, in decode
2017-07-09T00:19:45.559165+00:00 app[web.1]:     obj, end = self.raw_decode(s, idx=_w(s, 0).end())
2017-07-09T00:19:45.559165+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/json/decoder.py", line 357, in raw_decode
2017-07-09T00:19:45.559166+00:00 app[web.1]:     raise JSONDecodeError("Expecting value", s, err.value) from None
2017-07-09T00:19:45.559170+00:00 app[web.1]: json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

I'm not quite sure how to approach fixing this, I've trouble shot a bunch of things however I'm stumped on how to fix json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) Any feedback would be amazing. Thanks!

Body:
It may be due to an encoding mismatch.

As you haven't provided the json itself.

Try this instead.

json.loads(request.body.decode('utf-8'))


问:
How can create Semi Circle Donut in android
Is it possible to design the following cycle bar of BMI (Body Mass Index) in Android:

答: You probably want a custom view where you control the rendering of each of those elements.</p>


问:
Is it possible to use ngFor to display multiple component selector tags?
I have a question in angular 2.
so i am able to use ngFor to display {{data}} tags from a local json and display the data.

However i was wondering if theres a way to render component selector tags that are stored in a json and display them within an ng for. for example,
 I have this json component.ts in my file: (See comments for explanation about the issue)

```<code>import { Component, OnInit } from '@angular/core';
import * as jQuery from 'jquery';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
widgets;
  constructor() { }

  ngOnInit() {

    this.widgets = [
{
  "widgetcode": "<app-analytics-widget></app-club-chooser>" //Existing component selector tag within the angular cli system
},
{
  "widgetcode": "<app-club-chooser></app-club-chooser>" //Existing component selector tag within the angular cli system
},
{
  "widgetcode": "<app-account-widget></app-account-widget>" //Existing component selector tag within the angular cli system
}

    ]
  }

}
</code>```

my component.html file:

```<code>    <div class="DahsboardWrapper">

<!-- DashBoard Ges here -->

<!-- widget elements go here -->
<div class="DashoardHeaderClass" id="dashboard">
Dashboard Loaded
<div class="WidgetAreaWrapper">
<div class="widgets" *ngFor="let widget of widgets">

 <!-- {{widget.widgetcode}}  Not working atm..-->
<!-- this is displayng just plain text -->
</div>

<!-- This is working -->
<app-analytics-widget></app-analytics-widget>
<app-club-chooser></app-club-chooser>
<app-account-widget></app-account-widget>

</div>
</div>
</code>```

Any suggestions maybe theres a better way to do this?

答:
You cannot go from selector. That wouldn't work in production with Ahead of Time (AoT) compiler anyway, because the compiler runs at build time, and it is what matches selectors to components and directives.

If you have a limited set of tags in mind, you can use ngSwitch. Each of the components you support would be one of the switch cases, and you choose which one to display by some string property in your JSON. The entire [ngSwitch] would be the ngFor item.

If you need to support more complex scenarios, and you are using Angular 4, you can use ngComponentOutlet'. This still required a Type (importing the class) not a selector.

Finally, also Angular 4, for dynamically loading components in general, you can pick which way makes most sense to you by the many ways supported in this library https://github.com/apoterenko/ngx-dynamic-template.

Body:
I have a question in angular 2.
so i am able to use ngFor to display {{data}} tags from a local json and display the data.

However i was wondering if theres a way to render component selector tags that are stored in a json and display them within an ng for. for example,
 I have this json component.ts in my file: (See comments for explanation about the issue)

import { Component, OnInit } from '@angular/core';
import * as jQuery from 'jquery';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
widgets;
  constructor() { }

  ngOnInit() {

    this.widgets = [
{
  "widgetcode": "<app-analytics-widget></app-club-chooser>" //Existing component selector tag within the angular cli system
},
{
  "widgetcode": "<app-club-chooser></app-club-chooser>" //Existing component selector tag within the angular cli system
},
{
  "widgetcode": "<app-account-widget></app-account-widget>" //Existing component selector tag within the angular cli system
}

    ]
  }

}

my component.html file:

Dashboard Loaded

<app-analytics-widget></app-analytics-widget>
<app-club-chooser></app-club-chooser>
<app-account-widget></app-account-widget>

Any suggestions maybe theres a better way to do this?


问:
How to get the key from a given value in a Python dictionary?
How to get the key from a given value in a Python dictionary?

For example, if I have:

```<code>d = {
        'Italy' : ['IT', 'ITA'],
        'Austria' : ['AT'],
    }

search = 'ITA'
</code>```

What code is needed if I want this to return Italy. Notice that values can be lists

So if I search for AT, it should return Austria.

IT or ITA should return Italy.

Thanks in advance

答:
Possible duplicate of Get key by value in dictionary but you could invert the dictionary with this code:

```<code>d_inv = {}

for k, v in d.items():
    for i in v:
        d_inv[i] = k
</code>```

And then use:

```<code>d_inv[search]
</code>```

Body:
How to get the key from a given value in a Python dictionary?

For example, if I have:

d = {
        'Italy' : ['IT', 'ITA'],
        'Austria' : ['AT'],
    }

search = 'ITA'

What code is needed if I want this to return Italy. Notice that values can be lists

So if I search for AT, it should return Austria.

IT or ITA should return Italy.

Thanks in advance

Body:
Possible duplicate of Get key by value in dictionary but you could invert the dictionary with this code:

d_inv = {}

for k, v in d.items():
    for i in v:
        d_inv[i] = k

And then use:

d_inv[search]


问:
c# log file truncation
I would like to create a class that creates and manages log files. I would like the log file to be truncated when it exceeds a certain amount of text lines. Does any one have any recommendations on best practices to remove lines from the beginning of a text file.</p>

答:
I created a simple Logfile class in C# at http://www.blackbeltcoder.com/Articles/files/a-convenient-logfile-class.

However, files are truncated at the end--not the start. So if you truncated the file, you'd keep the old data and lose the new data. That's probably not what you want.

I would recommend either deleting the file every so often, or creating a new one. For example, you can write to a filename based on the current date, or a name based on the date that would change only once a week, etc.

OwnerDisplayName: Brad

ContentLicense: CC BY-SA 2.5

Title: c# log file truncation

LastEditorDisplayName: Kevin


问:
Why would GCC enable an optimization at O2/O3 when it explicitly says that it will slow the program?
Quoted from https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html:

-falign-labels

-falign-labels=n

Align all branch targets to a power-of-two boundary, skipping up to n bytes like -falign-functions. This option can easily
make code slower, because it must insert dummy operations for when the
branch target is reached in the usual flow of the code.

-fno-align-labels and -falign-labels=1 are equivalent and mean that labels are not aligned.

If -falign-loops or -falign-jumps are applicable and are greater than
this value, then their values are used instead.

If n is not specified or is zero, use a machine-dependent default
which is very likely to be ‘1’, meaning no alignment.

Enabled at levels -O2, -O3.

Thinking about this flag more makes it lose even more sense... there are consequences of provoking code cache miss, and what even enabling means when parameter takes numeric value (1..)?

答:
It doesn't say that. It says that can easily make code slower. It means, that in certain situations, it can make code slower. In other situations, it can make code faster.

Alignment causes to run code slower:

increases code size, so there is a higher chance that a code is not in the cache.

added nop operations slow down code

Alignment could cause to run code faster: branch prediction, instruction fetch, and god-knows-what.

In the case of a single if, it is hard to say which effect is stronger. It depends on the conditions.

However, for a loop, usually code becomes faster. Why? Because slow factors happen only once, but every cycle of the loop will be executed faster.

(My GCC seems to align labels to 8)


问:
PHP - array_search not working as expected - works then fails
So I have the following:

```<code>    echo array_search('Resolved at Tier 1', array_column($getHighLevelOverviewPeriodsArray, 'status'));
    print_r($getHighLevelOverviewPeriodsArray);

    if (!array_search('Resolved at Tier 1', array_column($getHighLevelOverviewPeriodsArray, 'status'))) {
        $resolved = array('status' => 'Resolved at Tier 1', 'amount' => 0);
        array_splice($getHighLevelOverviewPeriodsArray, 0, 0, array($resolved));
    }
    print_r($getHighLevelOverviewPeriodsArray);
</code>```

The echo spits out a zero which is right. It does exist in the first place. However the second part runs (if statement) and the array_splice gets executed. The output of print_r is below.

What is it being executed even though it's there?

I have the exact same code for Tier 2, character for character (expect for the 2) and that works as expected.

```<code>Array
(
    [0] => Array
        (
            [status] => Resolved at Tier 1
            [amount] => 10
        )

    [1] => Array
        (
            [status] => Resolved at Tier 2
            [amount] => 7
        )

    [2] => Array
        (
            [status] => Resolved Total
            [amount] => 17
        )

    [3] => Array
        (
            [status] => Phone Calls
            [amount] => 0
        )

)
Array
(
    [0] => Array
        (
            [status] => Resolved at Tier 1
            [amount] => 0
        )

    [1] => Array
        (
            [status] => Resolved at Tier 1
            [amount] => 10
        )

    [2] => Array
        (
            [status] => Resolved at Tier 2
            [amount] => 7
        )

    [3] => Array
        (
            [status] => Resolved Total
            [amount] => 17
        )

    [4] => Array
        (
            [status] => Phone Calls
            [amount] => 0
        )

)
</code>```

答:
Read the warning in the manual http://php.net/manual/en/function.array-search.php. 0 == false after type juggling. You need:

```<code> if (false !== array_search ...
</code>```

instead of:

```<code> if (!array_search...
</code>```

edit to add: Tier 2 works as expected, because indexes greater than zero are 'truthy'.

Body:
So I have the following:

    echo array_search('Resolved at Tier 1', array_column($getHighLevelOverviewPeriodsArray, 'status'));
    print_r($getHighLevelOverviewPeriodsArray);

    if (!array_search('Resolved at Tier 1', array_column($getHighLevelOverviewPeriodsArray, 'status'))) {
        $resolved = array('status' => 'Resolved at Tier 1', 'amount' => 0);
        array_splice($getHighLevelOverviewPeriodsArray, 0, 0, array($resolved));
    }
    print_r($getHighLevelOverviewPeriodsArray);

The echo spits out a zero which is right. It does exist in the first place. However the second part runs (if statement) and the array_splice gets executed. The output of print_r is below.

What is it being executed even though it's there?

I have the exact same code for Tier 2, character for character (expect for the 2) and that works as expected.

Array
(
    [0] => Array
        (
            [status] => Resolved at Tier 1
            [amount] => 10
        )

    [1] => Array
        (
            [status] => Resolved at Tier 2
            [amount] => 7
        )

    [2] => Array
        (
            [status] => Resolved Total
            [amount] => 17
        )

    [3] => Array
        (
            [status] => Phone Calls
            [amount] => 0
        )

)
Array
(
    [0] => Array
        (
            [status] => Resolved at Tier 1
            [amount] => 0
        )

    [1] => Array
        (
            [status] => Resolved at Tier 1
            [amount] => 10
        )

    [2] => Array
        (
            [status] => Resolved at Tier 2
            [amount] => 7
        )

    [3] => Array
        (
            [status] => Resolved Total
            [amount] => 17
        )

    [4] => Array
        (
            [status] => Phone Calls
            [amount] => 0
        )

)

Body:
Read the warning in the manual http://php.net/manual/en/function.array-search.php. 0 == false after type juggling. You need:

 if (false !== array_search ...

instead of:

 if (!array_search...

edit to add: Tier 2 works as expected, because indexes greater than zero are 'truthy'.


问:
Block focus/select in a ReadOnly textbox
Someone knows how to block the focus/select in a read-only textbox (ReadOnly = true), without using enabled = false?

Thanks!

答:
Controls have a GotFocus Event. You can add an event handler for this event and give another control focus, for example by calling Select() on another control or by using SelectNextControl:

```<code>Private Sub MyTextBox_GotFocus(sender as Object, e as EventArgs) _
 Handles  MyTextBox.GotFocus
    MyTextBox.Parent.SelectNextControl(MyTextBox, True, True, True, True)
End Sub
</code>```

Alternately, you can create a custom control that inherits TextBox and set ControlStyles.Selectable to False.

```<code>Public Class NonSelectableTextBox Inherits TextBox
    Public Sub New()
         SetStyle(ControlStyles.Selectable, false)
    End Sub
End Class
</code>```

Setting ControlStyles.Selectable to false will make the TextBox mimic the behavior of other controls which have this bit set to False:

Label

Panel

GroupBox

PictureBox

ProgressBar

Splitter

LinkLabel (when there is no link present in the control)

Body:
Controls have a GotFocus Event. You can add an event handler for this event and give another control focus, for example by calling Select() on another control or by using SelectNextControl:

Private Sub MyTextBox_GotFocus(sender as Object, e as EventArgs) _
 Handles  MyTextBox.GotFocus
    MyTextBox.Parent.SelectNextControl(MyTextBox, True, True, True, True)
End Sub

Alternately, you can create a custom control that inherits TextBox and set ControlStyles.Selectable to False.

Public Class NonSelectableTextBox Inherits TextBox
    Public Sub New()
         SetStyle(ControlStyles.Selectable, false)
    End Sub
End Class

Setting ControlStyles.Selectable to false will make the TextBox mimic the behavior of other controls which have this bit set to False:

Label

Panel

GroupBox

PictureBox

ProgressBar

Splitter

LinkLabel (when there is no link present in the control)


问:
How can I target a table cell in the same row with jQuery?
I have a table with a single input field and an AJAX script that runs when the input field value is modified. This is all working well. I now need to extend this to insert a date into another cell in the same row, but now sure how to target this as the ID will have to be dynamic. Here's the current table:

    Order Number
    Order Date
    Con Note

      123456

      <input type="text" class="form-control" placeholder="Con Note" name="conNote" value="">

      987654

      <input type="text" class="form-control" placeholder="Con Note" name="conNote" value="">

```
</div>
</div>
</p>

<p>I need to insert the current data into the Order Data cell when the AJAX script is run, something like this:</p>

```$("#85759.OrderDate").html('current date');
```

<p>but not sure how to dynamically target the Order Data cell? I'm setting the ID for the Order Data cell to be the same ID as the input field with ".OrderDate" appended. Current script is:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function() {
  $("input[type='text']").change(function() {
    var recid = $(this).closest('td').attr('id');
    var conNote = $(this).val();
    $this = $(this);
    $.post('updateOrder.php', {
      type: 'updateOrder',
      recid: recid,
      conNote: conNote
    }, function(data) {
      data = JSON.parse(data);
      if (data.error) {
        var ajaxError = (data.text);
        var errorAlert = 'There was an error updating the Con Note Number - ' + ajaxError;
        $this.closest('td').addClass("has-error");
        $("#serialNumberError").html(errorAlert);
        $("#serialNumberError").show();
        return; // stop executing this function any further
      } else {
        $this.closest('td').addClass("has-success")
        $this.closest('td').removeClass("has-error");
      }

    }).fail(function(xhr) {
      var httpStatus = (xhr.status);
      var ajaxError = 'There was an error updating the Con Note Number - AJAX request error. HTTP Status: ' + httpStatus;
      $this.closest('td').addClass("has-error");
      //display AJAX error details
      $("#serialNumberError").html(ajaxError);
      $("#serialNumberError").show();
    });
  });
});</code>```

答:
Check the code below. I've removed the ajax call and replaced it with the success block, but the concept is still the same. It gets the cell that has an id that ends with "OrderDate" on the same row and sets the html for that cell. I've used the jQuery Ends With selector for this.

$(document).ready(function() {
  $("input[type='text']").change(function() {
    var recid = $(this).closest('td').attr('id');
    var conNote = $(this).val();
    var $this = $(this);
    $this.parents('tr:first').find("td[id$='OrderDate']").html(new Date());
    $this.closest('td').addClass("has-success")
    $this.closest('td').removeClass("has-error");
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.has-success {
   border: 1px solid green;
}</code>```

    Order Number
    Order Date
    Con Note

      123456

      <input type="text" class="form-control" placeholder="Con Note" name="conNote" value="">

      987654

      <input type="text" class="form-control" placeholder="Con Note" name="conNote" value="">

```

ContentLicense: CC BY-SA 4.0

Body:
I have a table with a single input field and an AJAX script that runs when the input field value is modified. This is all working well. I now need to extend this to insert a date into another cell in the same row, but now sure how to target this as the ID will have to be dynamic. Here's the current table:

    Order Number
    Order Date
    Con Note

      123456

      <input type="text" class="form-control" placeholder="Con Note" name="conNote" value="">

      987654

      <input type="text" class="form-control" placeholder="Con Note" name="conNote" value="">

I need to insert the current data into the Order Data cell when the AJAX script is run, something like this:

$("#85759.OrderDate").html('current date');

but not sure how to dynamically target the Order Data cell? I'm setting the ID for the Order Data cell to be the same ID as the input field with ".OrderDate" appended. Current script is:

$(document).ready(function() {
  $("input[type='text']").change(function() {
    var recid = $(this).closest('td').attr('id');
    var conNote = $(this).val();
    $this = $(this);
    $.post('updateOrder.php', {
      type: 'updateOrder',
      recid: recid,
      conNote: conNote
    }, function(data) {
      data = JSON.parse(data);
      if (data.error) {
        var ajaxError = (data.text);
        var errorAlert = 'There was an error updating the Con Note Number - ' + ajaxError;
        $this.closest('td').addClass("has-error");
        $("#serialNumberError").html(errorAlert);
        $("#serialNumberError").show();
        return; // stop executing this function any further
      } else {
        $this.closest('td').addClass("has-success")
        $this.closest('td').removeClass("has-error");
      }

    }).fail(function(xhr) {
      var httpStatus = (xhr.status);
      var ajaxError = 'There was an error updating the Con Note Number - AJAX request error. HTTP Status: ' + httpStatus;
      $this.closest('td').addClass("has-error");
      //display AJAX error details
      $("#serialNumberError").html(ajaxError);
      $("#serialNumberError").show();
    });
  });
});

Body:
Check the code below. I've removed the ajax call and replaced it with the success block, but the concept is still the same. It gets the cell that has an id that ends with "OrderDate" on the same row and sets the html for that cell. I've used the jQuery Ends With selector for this.

$(document).ready(function() {
  $("input[type='text']").change(function() {
    var recid = $(this).closest('td').attr('id');
    var conNote = $(this).val();
    var $this = $(this);
    $this.parents('tr:first').find("td[id$='OrderDate']").html(new Date());
    $this.closest('td').addClass("has-success")
    $this.closest('td').removeClass("has-error");
  });
});

.has-success {
   border: 1px solid green;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-condensed table-striped table-bordered">
  <thead>
    <th class="text-center" scope="col">Order Number</th>
    <th class="text-center" scope="col">Order Date</th>
    <th class="text-center" scope="col">Con Note</th>
  </thead>
  <tbody>

    <tr>
      <td>123456</td>
      <td id="85759.OrderDate"></td>
      <td id="85759"><input type="text" class="form-control" placeholder="Con Note" name="conNote" value=""></td>
    </tr>
    <tr>
      <td>987654</td>
      <td id="85760.OrderDate"></td>
      <td id="85760"><input type="text" class="form-control" placeholder="Con Note" name="conNote" value=""></td>
    </tr>

  </tbody>
</table>


问:
scrolling entire screen with UIScrollview and UICollectionView
I am trying to build this view where I have a UI Image view with some labels below it. And then Below this I have a Collection view which has a few items. I am struggling to figure out how I could have this view such that the whole screen keeps scrolling up once i get to the collection view.

Right now, the image view and the labels below scroll, but then the collection view only scrolls within its constraints. What I want is the entire screen to scroll up so the collection view items fill the screen up. I have seen several other replies to similar questions but am unable to follow it.

Can someone help with what I am doing wrong here ?

答:
For the best practice on mobile programming, you should not have a scrollable view in another scrollable view. If you do so, you will have the problem as you described that your child collection view starts to scroll while other elements like your imageview and labels stay there.

To achieve your point, you can simply use a collection view and have custom cells. Now your entire window has only one scrollable view so it looks better. Then you are basically have different cell types. On top you have a collection cell as image, then you have few collection cell as labels, and so on.


问:
How to Prevent Form Resubmission when page is refreshed or back button is clicked
On my form , i allow users to upload files to the database and i send them to another page, which is submission_successful.php, that says "Thank You for Submitting". But i noticed that when i hit the back button on the submission successful php file, it goes back to the form and the same information is there and allows another submission. What i want to do is kill the code, upon hitting back button, or clear everything that was inputted by the user. I found a couple of answers around like using cache control but, some were vague and others didn't work for me. And plus i don't want the user going back to the upload page when they're on the success page. So thats why i will create 2 buttons for "logout" or "go back to upload page" and if they hit back button, it will crash. I want to show the Confirm Form Resubmission page. In other post they are trying to actually prevent the "Confirm Form Resubmission" but i would like to have it for security. Here is my code

developerUpload.php

```<code><?php

session_start();

if(array_key_exists("invalid", $_GET)){

    echo '<br><h3 style="color:red;">File(s) were already submitted! Please re-name file or select a different file...</h3>';
}

if(isset($_COOKIE['username'])){

    if($_SERVER['REQUEST_METHOD'] =="POST"){

        $price = addslashes(trim($_POST['price']));
        $description = addslashes(trim($_POST['description']));

        if(!empty($price) && !empty($description)){

            $userid = $_SESSION['id'];
            $username = $_SESSION['username'];
            echo '<br>'.$userid;
            $pack_id = rand();

            //Check file 1
            if($_FILES['file1']['error'] !== UPLOAD_ERR_OK){

                    $file1 = null;
            }else{

                $target1 = "devFiles/";
                $target_file1 = addslashes(trim($target1 . basename($_FILES["file1"]["name"])));
                $file1 = addslashes(trim($_FILES['file1']['tmp_name']));

            }

            //Check file 2
            if($_FILES['file2']['error'] !== UPLOAD_ERR_OK){

                    $file2 = null;
            }else{

                $target2 = "devFiles/";
                $target_file2 = addslashes(trim($target2 . basename($_FILES["file2"]["name"])));
                $file2 = addslashes(trim($_FILES['file2']['tmp_name']));

            }

            //Check file 3
            if($_FILES['file3']['error'] !== UPLOAD_ERR_OK){

                    $file3 = null;
            }else{

                $target3 = "devFiles/";
                $target_file3 = addslashes(trim($target3 . basename($_FILES["file3"]["name"])));
                $file3 = addslashes(trim($_FILES['file3']['tmp_name']));

            }

            //Check file 4
            if($_FILES['file4']['error'] !== UPLOAD_ERR_OK){

                    $file4 = null;
            }else{

                $target4 = "devFiles/";
                $target_file4 = addslashes(trim($target4 . basename($_FILES["file4"]["name"])));
                $file4 = addslashes(trim($_FILES['file4']['tmp_name']));

            }

            //Check file 5
            if($_FILES['file5']['error'] !== UPLOAD_ERR_OK){

                    $file5 = null;
            }else{

                $target5 = "devFiles/";
                $target_file5 = addslashes(trim($target5 . basename($_FILES["file5"]["name"])));
                $file5 = addslashes(trim($_FILES['file5']['tmp_name']));

            }

            //Check video
            if($_FILES['video']['error'] !== UPLOAD_ERR_OK){

                $video = null;
                $videoName = null;
            }else{

                $target = "devFiles/";
                $target_file = addslashes(trim($target . basename($_FILES["video"]["name"])));
                $video = addslashes(trim($_FILES['video']['tmp_name']));
                $videoName = addslashes(trim($_FILES['video']['name']));

            }

            if(file_exists($target_file1)
               or file_exists($target_file2)
               or file_exists($target_file3)
               or file_exists($target_file4)
               or file_exists($target_file5)
               or file_exists($target_file)){

                header("Location: developerUpload.php?invalid");
                exit;

            }

            if(move_uploaded_file($_FILES["file1"]["tmp_name"], $target_file1)
               && move_uploaded_file($_FILES["file2"]["tmp_name"], $target_file2)
               && move_uploaded_file($_FILES["file3"]["tmp_name"], $target_file3)
               && move_uploaded_file($_FILES["file4"]["tmp_name"], $target_file4)
               && move_uploaded_file($_FILES["file5"]["tmp_name"], $target_file5)
               && move_uploaded_file($_FILES["video"]["tmp_name"], $target_file)){

                try{

                    // new php data object
                    $handler = new PDO('mysql:host=127.0.0.1;dbname=magicsever', 'root', '');
                    //ATTR_ERRMODE set to exception
                    $handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

                }catch(PDOException $e){
                    die("There was an error connecting to the database");

                }

                header("Location: submission_successful.php?");
                die();
            }

        }else{

            echo '<br><h1 style="color:red;">VALUES MISSING!</h1>';

        }
    }
}else {

    header("Location: developerLogin.php");
}

?>
</code>```

submission_successful.php

```<code><?php
session_start();

    if(array_key_exists("invalid", $_GET)){

        header("Location: developerUpload.php?invalid");

    }
    if(isset($_COOKIE['username'])){
        echo '<br><h1 style="color:red; text_align:center;">Thank You for Submitting!</h1>';

    }else{

        header("Location: developerLogin.php");
    }

?>
</code>```

答: Not sure whether you can check if a value exists twice in the database (thus preventing multiple submissions), but you could block users from submitting the form too frequently. Create a timestamp that gets saved upon first submission, and if the second resubmission's timestamp is not too far(big) from the first one, you could try sth like (you are submitting too frequently), or you could use ajax, or this https://es.m.wikipedia.org/wiki/Post/Redirect/Get</p>

Body:
On my form , i allow users to upload files to the database and i send them to another page, which is submission_successful.php, that says "Thank You for Submitting". But i noticed that when i hit the back button on the submission successful php file, it goes back to the form and the same information is there and allows another submission. What i want to do is kill the code, upon hitting back button, or clear everything that was inputted by the user. I found a couple of answers around like using cache control but, some were vague and others didn't work for me. And plus i don't want the user going back to the upload page when they're on the success page. So thats why i will create 2 buttons for "logout" or "go back to upload page" and if they hit back button, it will crash. I want to show the Confirm Form Resubmission page. In other post they are trying to actually prevent the "Confirm Form Resubmission" but i would like to have it for security. Here is my code

developerUpload.php

<?php

session_start();

if(array_key_exists("invalid", $_GET)){

    echo '

File(s) were already submitted! Please re-name file or select a different file...
';
}

if(isset($_COOKIE['username'])){

    if($_SERVER['REQUEST_METHOD'] =="POST"){

        $price = addslashes(trim($_POST['price']));
        $description = addslashes(trim($_POST['description']));

        if(!empty($price) && !empty($description)){

            $userid = $_SESSION['id'];
            $username = $_SESSION['username'];
            echo '
'.$userid;
            $pack_id = rand();

            //Check file 1
            if($_FILES['file1']['error'] !== UPLOAD_ERR_OK){

                    $file1 = null;
            }else{

                $target1 = "devFiles/";
                $target_file1 = addslashes(trim($target1 . basename($_FILES["file1"]["name"])));
                $file1 = addslashes(trim($_FILES['file1']['tmp_name']));

            }

            //Check file 2
            if($_FILES['file2']['error'] !== UPLOAD_ERR_OK){

                    $file2 = null;
            }else{

                $target2 = "devFiles/";
                $target_file2 = addslashes(trim($target2 . basename($_FILES["file2"]["name"])));
                $file2 = addslashes(trim($_FILES['file2']['tmp_name']));

            }

            //Check file 3
            if($_FILES['file3']['error'] !== UPLOAD_ERR_OK){

                    $file3 = null;
            }else{

                $target3 = "devFiles/";
                $target_file3 = addslashes(trim($target3 . basename($_FILES["file3"]["name"])));
                $file3 = addslashes(trim($_FILES['file3']['tmp_name']));

            }

            //Check file 4
            if($_FILES['file4']['error'] !== UPLOAD_ERR_OK){

                    $file4 = null;
            }else{

                $target4 = "devFiles/";
                $target_file4 = addslashes(trim($target4 . basename($_FILES["file4"]["name"])));
                $file4 = addslashes(trim($_FILES['file4']['tmp_name']));

            }

            //Check file 5
            if($_FILES['file5']['error'] !== UPLOAD_ERR_OK){

                    $file5 = null;
            }else{

                $target5 = "devFiles/";
                $target_file5 = addslashes(trim($target5 . basename($_FILES["file5"]["name"])));
                $file5 = addslashes(trim($_FILES['file5']['tmp_name']));

            }

            //Check video
            if($_FILES['video']['error'] !== UPLOAD_ERR_OK){

                $video = null;
                $videoName = null;
            }else{

                $target = "devFiles/";
                $target_file = addslashes(trim($target . basename($_FILES["video"]["name"])));
                $video = addslashes(trim($_FILES['video']['tmp_name']));
                $videoName = addslashes(trim($_FILES['video']['name']));

            }

            if(file_exists($target_file1)
               or file_exists($target_file2)
               or file_exists($target_file3)
               or file_exists($target_file4)
               or file_exists($target_file5)
               or file_exists($target_file)){

                header("Location: developerUpload.php?invalid");
                exit;

            }

            if(move_uploaded_file($_FILES["file1"]["tmp_name"], $target_file1)
               && move_uploaded_file($_FILES["file2"]["tmp_name"], $target_file2)
               && move_uploaded_file($_FILES["file3"]["tmp_name"], $target_file3)
               && move_uploaded_file($_FILES["file4"]["tmp_name"], $target_file4)
               && move_uploaded_file($_FILES["file5"]["tmp_name"], $target_file5)
               && move_uploaded_file($_FILES["video"]["tmp_name"], $target_file)){

                try{

                    // new php data object
                    $handler = new PDO('mysql:host=127.0.0.1;dbname=magicsever', 'root', '');
                    //ATTR_ERRMODE set to exception
                    $handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

                }catch(PDOException $e){
                    die("There was an error connecting to the database");

                }

                header("Location: submission_successful.php?");
                die();
            }

        }else{

            echo '

VALUES MISSING!
';

        }
    }
}else {

    header("Location: developerLogin.php");
}

?>

submission_successful.php

<?php
session_start();

    if(array_key_exists("invalid", $_GET)){

        header("Location: developerUpload.php?invalid");

    }
    if(isset($_COOKIE['username'])){
        echo '

Thank You for Submitting!
';

    }else{

        header("Location: developerLogin.php");
    }

?>


问:
Python: difference between "|" and "or" in equation
all.
I'm running a simple python program and I found when I use followees = self.followee.get(userId, set()) | set([userId]), it passed the test. However, if I use followees = self.followee.get(userId, set()) or set([userId]), it didn't.

So, apparently, there are some differences between these two operators in equations. Does anyone have some idea what's going on?

Thanks!

答:
For sets (which are your operands here), | returns the union of both sets (the operands), while the or operator returns the first truthy operand (a non-empty set) or the last, if all of the operands are falsy — making or a short-circuit operator.

Consider the following examples:

```<code>>>> set([1,2,3]) | set([4])
set([1, 2, 3, 4])
>>> set([1,2,3]) or set([4])
set([1, 2, 3])
>>> set([1,2,3]) or set([])
set([1, 2, 3])
>>> set([1,2,3]) | set([])
set([1, 2, 3])
</code>```

Notice that with two operands, if at least one of the operands is falsy, both | and or give the same results.

or's behaviour is consistent for all objects, while | would behave differently depending on how the operands implement the __or__ or __ror__ magic methods e.g. acts as the bitwise or for integer types and [max-]union for collections.Counter objects.

Body:
For sets (which are your operands here), | returns the union of both sets (the operands), while the or operator returns the first truthy operand (a non-empty set) or the last, if all of the operands are falsy — making or a short-circuit operator.

Consider the following examples:

>>> set([1,2,3]) | set([4])
set([1, 2, 3, 4])
>>> set([1,2,3]) or set([4])
set([1, 2, 3])
>>> set([1,2,3]) or set([])
set([1, 2, 3])
>>> set([1,2,3]) | set([])
set([1, 2, 3])

Notice that with two operands, if at least one of the operands is falsy, both | and or give the same results.

or's behaviour is consistent for all objects, while | would behave differently depending on how the operands implement the __or__ or __ror__ magic methods e.g. acts as the bitwise or for integer types and [max-]union for collections.Counter objects.


问:
Change cell color based on value faster
I have vba code to change the color of cells based on the content of it currently I am looping through 13000 cells individually using row and column indexed for loops and a select case statement but it takes around 30 secs. Does anyone know a quicker way ?</p>

答: use a range for each color. Put the cells in a vba array. In a loop you build each 'color range' but do not color the ranges yet. After the loop, each 'color range' receives its color accordingly. Voila. Basicaly</p>

Title: Change cell color based on value faster


问:
Use string to refer to an array name in vba
I have Powerpoint presentation. On each slide I have 8 shapes with text space. They can contain text representing group which has sth related to content/data update and so on.
I have following arrays which contain users for those responsibility area:

```<code>GEN = Array("username_01","username_02","username_03",..."username_xx")
POL = Array("username_01","username_02","username_03",..."username_xx")
B2B = Array("username_01","username_02","username_03",..."username_xx")
RUS = Array("username_01","username_02","username_03",..."username_xx")
</code>```

And this function which is checking if user is in array

```<code>   Function IsInArray(stringToBeFound As Variant, arr As Variant) As Boolean
   IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
   End Function
</code>```

My problem is that when I want to use the function it works only if I will give the Array name as below:

```<code>auser = Environ("UserName")
IsInArray(auser,GEN) 'it will give me answer if the user is in array
</code>```

I want to get shape text:

```<code>res_group_txt = ActivePresentation.Slides(i).Shapes(shape_owner).TextEffect.Text
</code>```

And put it somehow in a function so it will not return an error

```<code>auser = Environ("UserName")
IsInArray(auser,res_group_txt)
</code>```

I have tried to change variables and look through all topics but I have not found answer :(

Help pls :)

BR Misza

答:
First of all, the answer is 'yes', you can access these arrays by name. You'd use the CallByName() function which enables you to access any property (and, indeed, method) of an object by its name, passed as a string.

The small adjustment you'd need to make to your code would be to create an object which contained the arrays as properties. Specifically, you'd do this by inserting a Class object (Insert > Class Module). In the example below, I've called the class cArrayFields and added your code as follows:

```<code>Option Explicit

Public GEN As Variant
Public POL As Variant
Public B2B As Variant
Public RUS As Variant

Private Sub Class_Initialize()
    GEN = Array("username_01", "username_02", "username_03", "username_04")
    POL = Array("username_02", "username_03", "username_04")
    B2B = Array("username_03", "username_04")
    RUS = Array("username_04")
End Sub
</code>```

In your main procedure (the one in your module), your code would simply be:

```<code>Dim o As cArrayFields
Dim targetShape As Shape
Dim targetName As String, shapeText As String, aUser As String
Dim arr As Variant
Dim i As Long

targetName = "MyShape"
aUser = "username_03" 'test example

Set o = New cArrayFields
For i = 1 To 4
    Set targetShape = ActivePresentation.Slides(i).Shapes(targetName)
    shapeText = targetShape.TextEffect.Text
    arr = CallByName(o, shapeText, VbGet)
    Debug.Print IsInArray(aUser, arr)
Next
</code>```

However, I wonder if your users and responsibilities are structured in the most efficient manner. A more intuitive way to go might be to have a list of users and each member contains a list of the areas they are responsible for. If you did it this way, then the look-up would be far simpler; for example you could just use a Collection object, which accesses each item by a String key. So your code could just be a couple of small routines to create the lists:

```<code>Private Sub DefineUserList()
    Set mUsers = New Collection

    AddNewUser "username_01", "GEN"
    AddNewUser "username_02", "GEN", "POL"
    AddNewUser "username_03", "GEN", "POL", "B2B"
    AddNewUser "username_04", "GEN", "POL", "B2B", "RUS"
End Sub
Private Sub AddNewUser(userName, ParamArray respAreas() As Variant)
    Dim resp As Collection
    Dim v As Variant

    Set resp = New Collection
    For Each v In respAreas
        resp.Add True, CStr(v)
    Next
    mUsers.Add resp, userName

End Sub
</code>```

And then your look-up routines in your main module as follows:

```<code>Option Explicit

Private mUsers As Collection

Public Sub Main()
    Dim targetShape As Shape
    Dim targetName As String, shapeText As String, aUser As String
    Dim i As Long

    DefineUserList

    targetName = "MyShape"
    aUser = "username_03" 'test example

    For i = 1 To 4
        Set targetShape = ActivePresentation.Slides(i).Shapes(targetName)
        shapeText = targetShape.TextEffect.Text
        Debug.Print IsUsersArea(aUser, shapeText)
    Next
End Sub

Private Function IsUsersArea(userName As String, respArea As String) As Boolean
    On Error Resume Next
    IsUsersArea = mUsers(userName).Item(respArea)
    On Error GoTo 0
End Function
</code>```

Body:
I have Powerpoint presentation. On each slide I have 8 shapes with text space. They can contain text representing group which has sth related to content/data update and so on.
I have following arrays which contain users for those responsibility area:

GEN = Array("username_01","username_02","username_03",..."username_xx")
POL = Array("username_01","username_02","username_03",..."username_xx")
B2B = Array("username_01","username_02","username_03",..."username_xx")
RUS = Array("username_01","username_02","username_03",..."username_xx")

And this function which is checking if user is in array

   Function IsInArray(stringToBeFound As Variant, arr As Variant) As Boolean
   IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
   End Function

My problem is that when I want to use the function it works only if I will give the Array name as below:

auser = Environ("UserName")
IsInArray(auser,GEN) 'it will give me answer if the user is in array

I want to get shape text:

res_group_txt = ActivePresentation.Slides(i).Shapes(shape_owner).TextEffect.Text

And put it somehow in a function so it will not return an error

auser = Environ("UserName")
IsInArray(auser,res_group_txt)

I have tried to change variables and look through all topics but I have not found answer :(

Help pls :)

BR Misza

Body:
First of all, the answer is 'yes', you can access these arrays by name. You'd use the CallByName() function which enables you to access any property (and, indeed, method) of an object by its name, passed as a string.

The small adjustment you'd need to make to your code would be to create an object which contained the arrays as properties. Specifically, you'd do this by inserting a Class object (Insert > Class Module). In the example below, I've called the class cArrayFields and added your code as follows:

Option Explicit

Public GEN As Variant
Public POL As Variant
Public B2B As Variant
Public RUS As Variant

Private Sub Class_Initialize()
    GEN = Array("username_01", "username_02", "username_03", "username_04")
    POL = Array("username_02", "username_03", "username_04")
    B2B = Array("username_03", "username_04")
    RUS = Array("username_04")
End Sub

In your main procedure (the one in your module), your code would simply be:

Dim o As cArrayFields
Dim targetShape As Shape
Dim targetName As String, shapeText As String, aUser As String
Dim arr As Variant
Dim i As Long

targetName = "MyShape"
aUser = "username_03" 'test example

Set o = New cArrayFields
For i = 1 To 4
    Set targetShape = ActivePresentation.Slides(i).Shapes(targetName)
    shapeText = targetShape.TextEffect.Text
    arr = CallByName(o, shapeText, VbGet)
    Debug.Print IsInArray(aUser, arr)
Next

However, I wonder if your users and responsibilities are structured in the most efficient manner. A more intuitive way to go might be to have a list of users and each member contains a list of the areas they are responsible for. If you did it this way, then the look-up would be far simpler; for example you could just use a Collection object, which accesses each item by a String key. So your code could just be a couple of small routines to create the lists:

Private Sub DefineUserList()
    Set mUsers = New Collection

    AddNewUser "username_01", "GEN"
    AddNewUser "username_02", "GEN", "POL"
    AddNewUser "username_03", "GEN", "POL", "B2B"
    AddNewUser "username_04", "GEN", "POL", "B2B", "RUS"
End Sub
Private Sub AddNewUser(userName, ParamArray respAreas() As Variant)
    Dim resp As Collection
    Dim v As Variant

    Set resp = New Collection
    For Each v In respAreas
        resp.Add True, CStr(v)
    Next
    mUsers.Add resp, userName

End Sub

And then your look-up routines in your main module as follows:

Option Explicit

Private mUsers As Collection

Public Sub Main()
    Dim targetShape As Shape
    Dim targetName As String, shapeText As String, aUser As String
    Dim i As Long

    DefineUserList

    targetName = "MyShape"
    aUser = "username_03" 'test example

    For i = 1 To 4
        Set targetShape = ActivePresentation.Slides(i).Shapes(targetName)
        shapeText = targetShape.TextEffect.Text
        Debug.Print IsUsersArea(aUser, shapeText)
    Next
End Sub

Private Function IsUsersArea(userName As String, respArea As String) As Boolean
    On Error Resume Next
    IsUsersArea = mUsers(userName).Item(respArea)
    On Error GoTo 0
End Function


问:
Send message to particular user by Facebook Messenger
I am new in Facebook integration work.  I am working on one project by which i have to send a text message to fixed user (admin) , I already check several question/answer but i am not able to get exact answer.  Thank u in Advance</p>

答: If your bot installed to a Page, and if you know the user id of the admin then you can send many messages that user only. But, user id is not the same user id of Facebook user id. When someone creates a conversation with your bot, you can get the unique user id of that user for your bot. Please note that this user id is only for your bot, and it is different for other bots.   </p>


问:
Overwriting/clearing previous console line
My problem is, that I want to be able to overwrite/clear previous printed line in python console. This question has been asked many times (Python - Remove and Replace Printed items for example), however with the very same code that is
(the answer marked as correct, for me prints out nothing at all):

```<code>for i in range(10):
    print("Loading" + "." * i)
    time.sleep(1)
    sys.stdout.write("\033[F") # Cursor up one line
    sys.stdout.write("\033[K") # Clear to the end of line
</code>```

I get the output (In python IDLE) :

```<code>Loading
[F[KLoading.
[F[KLoading..
[F[KLoading...
[F[KLoading....
[F[KLoading.....
[F[KLoading......
[F[KLoading.......
[F[KLoading........
[F[KLoading.........
[F[KLoading..........
[F[K
</code>```

Any ideas? I googled a lot, nothing works really. It either prints out nothing or just does not overwrite.

If that helps, I am running windows 8.1 and Python 3.51. Running the code trough cmd doesn't affect anything.

Also, adding sys.stdout.flush() does not help.

答:
You're trying to use ANSI escape sequences to move the cursor. Windows doesn't support those by default. To enable them, you could install the colorama module with pip install colorama in your terminal, then in Python:

```<code>import colorama
colorama.init()
</code>```

If you've upgraded to Windows 10, you can enable support with this instead:

```<code>import ctypes
kernel32 = ctypes.windll.kernel32
kernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7)
</code>```

(Source: https://stackoverflow.com/a/36760881/6379747)

Body:
My problem is, that I want to be able to overwrite/clear previous printed line in python console. This question has been asked many times (Python - Remove and Replace Printed items for example), however with the very same code that is
(the answer marked as correct, for me prints out nothing at all):

for i in range(10):
    print("Loading" + "." * i)
    time.sleep(1)
    sys.stdout.write("\033[F") # Cursor up one line
    sys.stdout.write("\033[K") # Clear to the end of line

I get the output (In python IDLE) :

Loading
[F[KLoading.
[F[KLoading..
[F[KLoading...
[F[KLoading....
[F[KLoading.....
[F[KLoading......
[F[KLoading.......
[F[KLoading........
[F[KLoading.........
[F[KLoading..........
[F[K

Any ideas? I googled a lot, nothing works really. It either prints out nothing or just does not overwrite.

If that helps, I am running windows 8.1 and Python 3.51. Running the code trough cmd doesn't affect anything.

Also, adding sys.stdout.flush() does not help.

Body:
You're trying to use ANSI escape sequences to move the cursor. Windows doesn't support those by default. To enable them, you could install the colorama module with pip install colorama in your terminal, then in Python:

import colorama
colorama.init()

If you've upgraded to Windows 10, you can enable support with this instead:

import ctypes
kernel32 = ctypes.windll.kernel32
kernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7)

(Source: https://stackoverflow.com/a/36760881/6379747)


问:
Does anybody know equivalent for NETLINK Sockets API for MAC OS X?
Does anybody know equivalent for NETLINK Sockets API for MAC OS X ?
I am trying to port Linux application to MAC OS X and I couldn’t find anything similar in MACOS.

I need to provide asynchronous access to the network adapter in my application.

Polling network adapter about configuration changes etc every certain amount of seconds is not convenient solution for me.
NETLINK Socket API game me way to receive notification only when something interesting happened.

I know that NETLINK is Linux specific thing to communicate between Linux kernel and user space, but maybe there is exist something like NETLINK under MACOS.

I see the the only tool to communicate with kernel – sysctl()

Does anybody have any info?

答:
The traditional way of doing this is to wait for events on the socket using select/poll/epoll/kqueue. See this answer for what is best on what platform: select vs poll vs epoll.

Alternatively, spawn a new thread for each connection and use blocking socket reads. Though, history have taught us that this is less scalable than non-blocking I/O via select/poll/kqueue. This was the way most people originally wrote network servers in the 1990s. Depending on your coding style, blocking I/O + threads may be easier to work with.

Note that contrary to its name, epoll is not polling.


问:
how can i hide a  from print page in asp.net mvc project?
i have a table contains lot of td. i want to hide one of them from print page in the browser when i click print button. how to do that?
this is the index page code:

```<code><div id="div_print"><table class="table table-bordered">
<tr class="info">
    <th dir="rtl">
        @Html.DisplayNameFor(model => model.a)
    </th>
    <th dir="rtl">
        @Html.DisplayNameFor(model => model.b)
    </th>
    <th dir="rtl">
        @Html.DisplayNameFor(model => model.c)
    </th>
        </tr>
      </div>
       @foreach (var item in Model) {
      <tr>
      <td>
        @{
        ViewData["class"]= "text-uppercase";
        }
        @Html.DisplayFor(modelItem => item.a)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.b)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.c)
    </td>
       <td>
        @Html.ActionLink("Edit", "Edit", new { id=item.z}, new { @class = "btn btn-primary" }) |
        @Html.ActionLink("Details", "Details", new { id=item.z}, new { @class = "btn btn-primary" }) |
        @Html.ActionLink("Delete", "Delete", new { id=item.z}, new { @class = "btn btn-warning" })
    </td>
</tr>
  }
  </table>
</code>```

i want to hide this part:

```<code>            <td>
                @Html.ActionLink("Edit", "Edit", new { id=item.z}, new { @class = "btn btn-primary" }) |
                @Html.ActionLink("Details", "Details", new { id=item.z}, new { @class = "btn btn-primary" }) |
                @Html.ActionLink("Delete", "Delete", new { id=item.z}, new { @class = "btn btn-warning" })
            </td>
</code>```

答:
Use CSS to do that:

```<code>@media print
{
    .not-printable, .not-printable *
    {
        display: none !important;
    }
}
</code>```

Then add the not-printable to the element you do not want to print:

```<code><div class="not-printable"></div>
</code>```

CSS 3 Media Queries

Title: how can i hide a <td> from print page in asp.net mvc project?

Body:
i have a table contains lot of td. i want to hide one of them from print page in the browser when i click print button. how to do that?
this is the index page code:

        @Html.DisplayNameFor(model => model.a)

        @Html.DisplayNameFor(model => model.b)

        @Html.DisplayNameFor(model => model.c)

       @foreach (var item in Model) {

        @{
        ViewData["class"]= "text-uppercase";
        }
        @Html.DisplayFor(modelItem => item.a)

        @Html.DisplayFor(modelItem => item.b)

        @Html.DisplayFor(modelItem => item.c)

        @Html.ActionLink("Edit", "Edit", new { id=item.z}, new { @class = "btn btn-primary" }) |
        @Html.ActionLink("Details", "Details", new { id=item.z}, new { @class = "btn btn-primary" }) |
        @Html.ActionLink("Delete", "Delete", new { id=item.z}, new { @class = "btn btn-warning" })

  }

i want to hide this part:

                @Html.ActionLink("Edit", "Edit", new { id=item.z}, new { @class = "btn btn-primary" }) |
                @Html.ActionLink("Details", "Details", new { id=item.z}, new { @class = "btn btn-primary" }) |
                @Html.ActionLink("Delete", "Delete", new { id=item.z}, new { @class = "btn btn-warning" })

Body:
Use CSS to do that:

@media print
{
    .not-printable, .not-printable *
    {
        display: none !important;
    }
}

Then add the not-printable to the element you do not want to print:

<div class="not-printable"></div>

CSS 3 Media Queries


问:
Why do variables get into for loops with zero length?
can somebody explain why for loops are executed even on variables with zero length? For example

```<code>listFunction<-function(listinput)
{
for (i in 1:length(listinput))
{listinput[i]<-listinput[i]+1
print("googats")
}

  listinput
}

listB<-c()

listFunction(listB)
[1] "googats"
[1] "googats"

> listB
NULL
</code>```

why does it iterate the loop twice rather than simply not go in at all?

答:
Per official documentation, for loop

The syntax of the for loop is

```<code>for ( name in vector )
    statement1
</code>```

where vector can be either a
  vector or a list. For each element in vector the variable name is set
  to the value of that element and statement1 is evaluated. A side
  effect is that the variable name still exists after the loop has
  concluded and it has the value of the last element of vector that the
  loop was evaluated for.

So, it will iterate through each element.

In your case,

```<code>for (i in 1:length(listinput))
{
    listinput[i]<-listinput[i]+1
    print("googats")
}
</code>```

is like

```<code>for (i in 1:0)
{
    listinput[i]<-listinput[i]+1
    print("googats")
}
</code>```

since there are 2 elements 1 and 0 in your vector, the loop body will be iterated twice.

Body:
can somebody explain why for loops are executed even on variables with zero length? For example

listFunction<-function(listinput)
{
for (i in 1:length(listinput))
{listinput[i]<-listinput[i]+1
print("googats")
}

  listinput
}

listB<-c()

listFunction(listB)
[1] "googats"
[1] "googats"

> listB
NULL

why does it iterate the loop twice rather than simply not go in at all?

Body:
Per official documentation, for loop

The syntax of the for loop is

for ( name in vector )
    statement1

where vector can be either a
  vector or a list. For each element in vector the variable name is set
  to the value of that element and statement1 is evaluated. A side
  effect is that the variable name still exists after the loop has
  concluded and it has the value of the last element of vector that the
  loop was evaluated for.

So, it will iterate through each element.

In your case,

for (i in 1:length(listinput))
{
    listinput[i]<-listinput[i]+1
    print("googats")
}

is like

for (i in 1:0)
{
    listinput[i]<-listinput[i]+1
    print("googats")
}

since there are 2 elements 1 and 0 in your vector, the loop body will be iterated twice.


答:
You can select the cell by $this.closest('tr').children('td[id$="OrderDate"]').

You can simplify it more by:

Instead of using attribute ends with selector ([id$=".."]), if you can, add a CSS class "OrderDate" for example to all the order date cells, and simplify the selector to $this.closest('tr').children('.OrderData')

Instead of closest() use parents(). This is a micro-optimization. The only difference is that closest tests the actual element itself for matching the selector, and in this case you know you only need to check parent elements

You can also optionally rely on the fact that the cells are siblings and instead of children use siblings like like$this.parents('td').siblings('.OrderDate')

Title: How can I target a table cell in the same row with jQuery?


问:
In the child page, I want to find master page's Content placeholder and add text to it. How do I make that possible?
I tried this much:-</p>

```<code>protected void Page_PreInit(object sender, EventArgs e)
  {
        class1 obj = new class1();
        DataTable dt = new DataTable();
        dt = obj.get_text();
        ContentPlaceHolder ContentPlaceHolder1 = (ContentPlaceHolder)this.Master.FindControl("ContentPlaceHolder1");
        ContentPlaceHolder1. ????

 }
</code>```

答:
Given you have a valid reference to ContentPlaceHolder1...

In this line:

```<code>ContentPlaceHolder1. ????
</code>```

Do this:

```<code>// Add text to the place holder.
ContentPlaceHolder1.Controls.Add(new LiteralControl("my text to insert"));
</code>```

Body:
I tried this much:-

protected void Page_PreInit(object sender, EventArgs e)
  {
        class1 obj = new class1();
        DataTable dt = new DataTable();
        dt = obj.get_text();
        ContentPlaceHolder ContentPlaceHolder1 = (ContentPlaceHolder)this.Master.FindControl("ContentPlaceHolder1");
        ContentPlaceHolder1. ????

 }

Body:
Given you have a valid reference to ContentPlaceHolder1...

In this line:

ContentPlaceHolder1. ????

Do this:

// Add text to the place holder.
ContentPlaceHolder1.Controls.Add(new LiteralControl("my text to insert"));


答:
Use a session variable like this

```<code>$_SESSION["post_id"] = "";
if($_POST) {
    if($_POST["post_id"] != $_SESSION["post_id"]) {
        $_SESSION["post_id"] = $_POST["post_id"];
        // do database submission here
    }
}
</code>```

This sets a session variable and if they resubmit the form it won't post the data twice.

Title: How to Prevent Form Resubmission when page is refreshed or back button is clicked

Body:
Use a session variable like this

$_SESSION["post_id"] = "";
if($_POST) {
    if($_POST["post_id"] != $_SESSION["post_id"]) {
        $_SESSION["post_id"] = $_POST["post_id"];
        // do database submission here
    }
}

This sets a session variable and if they resubmit the form it won't post the data twice.


问:
why is maximum single-line length limited to 132 characters in Fortran Standard?
Is it about performance, clean source code, compilers, ...? I know that many compilers allow longer single-line codes. But, if this extension is possible without any compromise, then why does Fortran standard strictly adhere to this rule?

I know that this is very general question (stackoverflow warns me that this question might be downvoted given its title), but I cannot find any resources that explain the logic behind a max length of 132 characters in modern Fortran standard.

Update Oct 22, 2019: See https://j3-fortran.org/doc/year/19/19-138r1.txt for a proposal accepted as a work item for the next 202X revision of the Fortran standard, which eliminates the maximum line length and continuation limits.

答:
Take a look at specification:

ftp://ftp.nag.co.uk/sc22wg5/N001-N1100/N692.pdf

section: 3.3.1

It's just convention. Somebody decided that 132 will be ok. In 66 version it was 72.

Standards: https://gcc.gnu.org/wiki/GFortranStandards#Fortran_Standards_Documents

Usually, these limitations (like 80, 132 characters per line), were dictated by terminals.

Just to illustrate, in a "funny" way, how was it to code in 90's ;)


问:
Does updating Cocoapods update in all app versions?
I am using Cocoapods to manage my Admob/Google ad-related frameworks.
My pod file is as follows:

```<code>target 'SKGameTest' do
   use_frameworks!
   pod 'Firebase/Core'
   pod 'Firebase/AdMob'
   pod 'Google-Mobile-Ads-SDK'
end
</code>```

I have updated Firebase and Google-Mobile-Ads-SDK using the Cocoapods app. Now that these frameworks have been updated, will all current versions of my app use these latest frameworks? Or will my app users have to download a new update containing these updated frameworks? If the last option (downloading a new update for the app) is true, then this would be really annoying as you would have to release a new update for your app each time Google updates their SDKs.

Please explain to me about how this all works, thank you.

答: I have gone through some testing and have discovered that updating Cocoapods will not update all versions of the app (unfortunately). When updating your SDKs you will need to release a new version with it.</p>

Body:
I am using Cocoapods to manage my Admob/Google ad-related frameworks.
My pod file is as follows:

target 'SKGameTest' do
   use_frameworks!
   pod 'Firebase/Core'
   pod 'Firebase/AdMob'
   pod 'Google-Mobile-Ads-SDK'
end

I have updated Firebase and Google-Mobile-Ads-SDK using the Cocoapods app. Now that these frameworks have been updated, will all current versions of my app use these latest frameworks? Or will my app users have to download a new update containing these updated frameworks? If the last option (downloading a new update for the app) is true, then this would be really annoying as you would have to release a new update for your app each time Google updates their SDKs.

Please explain to me about how this all works, thank you.


问:
how do you precompile ejs templates to file
So I wanted to precompile ejs templates into a .js file

```<code>var compiled = ejs.compile(source);
fs.writeFileSync(target, 'myTemplateFunction = ' + compiled);
</code>```

but that serilalizes into

```<code>function (locals){
   return fn.call(this, locals, filters, utils.escape);
}
</code>```

what's the best way to pre-compile and write ejs templates into a .js file

答:
Lodash _.template() method creates a string represention of the EJS template function during compilation and attaches it as source property to the compiled function. You can store that string into a JS file, embed it into HTML, or read it to your grandchildren before sleep.

For example:

```<code>> var _ = require('lodash');
> var compiled = _.template('Hi <%= user %>!');
> compiled({ user: 'Axel' })
"Hi Axel!"
> compiled.source
"function(obj) {
  obj || (obj = {});
  var __t, __p = '';
  with (obj) {
    __p += 'Hi' + ((__t = ( user )) == null ? '' : __t) + '!';
  }
  return __p
}"
> var fs = require('fs')
> var src = 'module.exports = ' + compiled.source;
> fs.writeFileSync('mylittlescript.js', src);
</code>```

This approach is used by Webpack's ejs-loader module. Note also that npm package ejs does not provide such source property.

Body:
So I wanted to precompile ejs templates into a .js file

var compiled = ejs.compile(source);
fs.writeFileSync(target, 'myTemplateFunction = ' + compiled);

but that serilalizes into

function (locals){
   return fn.call(this, locals, filters, utils.escape);
}

what's the best way to pre-compile and write ejs templates into a .js file

Body:
Lodash _.template() method creates a string represention of the EJS template function during compilation and attaches it as source property to the compiled function. You can store that string into a JS file, embed it into HTML, or read it to your grandchildren before sleep.

For example:

> var _ = require('lodash');
> var compiled = _.template('Hi <%= user %>!');
> compiled({ user: 'Axel' })
"Hi Axel!"
> compiled.source
"function(obj) {
  obj || (obj = {});
  var __t, __p = '';
  with (obj) {
    __p += 'Hi' + ((__t = ( user )) == null ? '' : __t) + '!';
  }
  return __p
}"
> var fs = require('fs')
> var src = 'module.exports = ' + compiled.source;
> fs.writeFileSync('mylittlescript.js', src);

This approach is used by Webpack's ejs-loader module. Note also that npm package ejs does not provide such source property.


问:
ionic2/angular 2 How to show comment replies in descending order based on time
Question in short:

What is the best way to show comments in ionic2, especially when it has replies. I need to show replies based on their time.

++++++++++++++++++++++++++++++

Question in detail:

I have the below data with me in json format.

This is the list of comments. In this example 19 comments are there under items tag.

http://www.jsoneditoronline.org/?id=47b282c498505ed25869dc36f5f3bd58

Comments are already sorted based on Date published.

Now on the Item Id 10th there are two replies to this comment.

I am looking for a way to order this reply based on publishedAt time.

Below is my html:
Here videoComments = the json data specified above

I tried using angualr-pipes orderBy pipe but that did not work for me, is there any alternative way?

```<code><ion-list>
  <ion-item *ngFor="let comment of videoComments">
    <!-- here i Print the details what is required , next if there are any reply i would like to show them-->
    <div *ngIf="comment.snippet.totalReplyCount != 0">
      <ion-list>
        <ion-item *ngFor="let reply of comment.replies.comments | orderBy: 'publishedAt'">
          <!-- Above orderBy pipe is not working , may be my syntax is wrong -->
           <!-- I would like to show replies in ascending order of when it was submitted-->
          <!-- Details of replies will be shown here -->
        </ion-item>
      </ion-list>
    </div>
  </ion-item>
</ion-list>
</code>```

答:
Angular doesn't provide orderBy pipe. See here.

So you have to write it by yourself. Maybe this post can help you: Angular 2. How to apply orderBy?

Body:
Question in short:

What is the best way to show comments in ionic2, especially when it has replies. I need to show replies based on their time.

++++++++++++++++++++++++++++++

Question in detail:

I have the below data with me in json format.

This is the list of comments. In this example 19 comments are there under items tag.

http://www.jsoneditoronline.org/?id=47b282c498505ed25869dc36f5f3bd58

Comments are already sorted based on Date published.

Now on the Item Id 10th there are two replies to this comment.

I am looking for a way to order this reply based on publishedAt time.

Below is my html:
Here videoComments = the json data specified above

I tried using angualr-pipes orderBy pipe but that did not work for me, is there any alternative way?

<ion-list>
  <ion-item *ngFor="let comment of videoComments">

      <ion-list>
        <ion-item *ngFor="let reply of comment.replies.comments | orderBy: 'publishedAt'">

        </ion-item>
      </ion-list>

  </ion-item>
</ion-list>