问:
foundation 6 tooltip position issue
The problem is that tooltip is in wrong place - on far left side. So for instance when I hover element with tooltip that is on right side of the screen it will show tooltip on the left side far away from the hovered element. I could't find anything useful on the topic so far. Tried different options, but all tooltips were displayed on the left. Code for my tooltip copied from official foundation page

```<code><button class="button has-tip" type="button" data-tooltip aria-haspopup="true"
data-disable-hover="false" tabindex="1" data-position="top"
title="Fancy word for a beetle." data-alignment="center">
      Top Center
</button>
</code>```

答:
What version of Foundation are you using?  Here is a jsfiddle with your HTML using Foundation 6.4.1, and it works fine.  The only thing I changed was to add a margin on the button to allow the tooltip to position on top.  https://jsfiddle.net/genestd/svygwghz/

```<code><div>
  <button class="button has-tip center" type="button" data-tooltip aria-haspopup="true" data-disable-hover="false" tabindex="1" data-position="top" title="Fancy word for a beetle." data-alignment="center">
  Top Center
  </button>
</div>
</code>```

.

```<code>.center{
  margin: 100px;
}
</code>```

Title: foundation 6 tooltip position issue

Body:
The problem is that tooltip is in wrong place - on far left side. So for instance when I hover element with tooltip that is on right side of the screen it will show tooltip on the left side far away from the hovered element. I could't find anything useful on the topic so far. Tried different options, but all tooltips were displayed on the left. Code for my tooltip copied from official foundation page

<button class="button has-tip" type="button" data-tooltip aria-haspopup="true"
data-disable-hover="false" tabindex="1" data-position="top"
title="Fancy word for a beetle." data-alignment="center">
      Top Center
</button>

Body:
What version of Foundation are you using?  Here is a jsfiddle with your HTML using Foundation 6.4.1, and it works fine.  The only thing I changed was to add a margin on the button to allow the tooltip to position on top.  https://jsfiddle.net/genestd/svygwghz/

<div>
  <button class="button has-tip center" type="button" data-tooltip aria-haspopup="true" data-disable-hover="false" tabindex="1" data-position="top" title="Fancy word for a beetle." data-alignment="center">
  Top Center
  </button>
</div>

.

.center{
  margin: 100px;
}


来源: stackexchange

问:
Geolocation problems when switch GPS on and off
Thanks in advance first.I build a website with an option to lead you to a specific place when you click button "Navigate". Everything works fine on desktop and everything works fine on mobile when GPS of the phone is enabled.

I use the google maps reference and it works just fine:

```<code>http://maps.google.com/maps?saddr=myLat,myLng&daddr=targetLat,targetLng
</code>```

I do this on $('.button').click(). Not on $(window).load or $(document).ready. When you click the button, it calls the geolocation functions:

```<code>function getGeolocation(){
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(geoSuccess, geoError);
    } else {
        $('.error-message').html('<p>Your browser does not support this function</p>');
    }
}

function geoSuccess(position) {
    myLat = position.coords.latitude;
    myLng = position.coords.longitude;

    window.location.href = 'http://maps.google.com/maps?saddr=' + myLat + ',' + myLng + '&daddr=targetLat,targetLng';
}

function geoError(){
    switch(error.code) {
        alert('example alert - enable GPS');

        case error.PERMISSION_DENIED:
            $('.error-message').html('<p>User denied the request for Geolocation.</p>');
            break;
        case error.POSITION_UNAVAILABLE:
            $('.error-message').html('<p>Location information is unavailable.</p>');
            break;
        case error.TIMEOUT:
            $('.error-message').html('<p>The request to get user location timed out.</p>');
            break;
        case error.UNKNOWN_ERROR:
            $('.error-message').html('<p>An unknown error occurred.</p>');
            break;
    }
}
</code>```

But the problem comes when the GPS is disabled.

First of all, sometimes, it doesn't enter in geoError(). I tried so many times, but the only thing I "found" is that it caches sometimes. Is that possible ?

But the main problem is that, when the GPS is disabled, the "example alert" pops up, then I turn my GPS on and click the button again, it doesn't work again. I have to refresh the page to apply the GPS turn on. I want to avoid that. Does anyone know why is that happening and is there a way to do what I want?

The other problem is when I load my page with GPS turned on. Then I turn it off and click the button. Nothing happens at all. It enter getGeolocation(), gets true and then it stops. It doesn't enter getCurrentPosition(). Any ideas?

答:
I've got the same problem on Android 6.0 and Chrome 59.0.3071.125.

In short: When I start a webapp with location Off, I receive a PositionError as expected.

However when I switch location back to On, every subsequent call to navigator.geolocation.getCurrentPosition or navigator.geolocation.watchPosition returns same error.

I've tried the same with maps.google.com and result is exactly the same (they show a snackbar Google Maps could not determine your precise location) so I believe that there is no workaround.

There is a similar post on ionic framework forum - They didn't find a solution either.

To sum up:

Looks like Chrome is checking for location services **on page load and doesn't update the state any more.

So only thing that helps is reloading the webapp which forces chrome to check again if location services are available.

Update:

this is a known bug in Chromium: 672301, 721977.
Workaround is available in Chrome Mobile v59 behind lsd-permission-prompts flag.

ContentLicense: CC BY-SA 3.0

Body:
Thanks in advance first.I build a website with an option to lead you to a specific place when you click button "Navigate". Everything works fine on desktop and everything works fine on mobile when GPS of the phone is enabled.

I use the google maps reference and it works just fine:

http://maps.google.com/maps?saddr=myLat,myLng&daddr=targetLat,targetLng

I do this on $('.button').click(). Not on $(window).load or $(document).ready. When you click the button, it calls the geolocation functions:

function getGeolocation(){
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(geoSuccess, geoError);
    } else {
        $('.error-message').html('
Your browser does not support this function
');
    }
}

function geoSuccess(position) {
    myLat = position.coords.latitude;
    myLng = position.coords.longitude;

    window.location.href = 'http://maps.google.com/maps?saddr=' + myLat + ',' + myLng + '&daddr=targetLat,targetLng';
}

function geoError(){
    switch(error.code) {
        alert('example alert - enable GPS');

        case error.PERMISSION_DENIED:
            $('.error-message').html('
User denied the request for Geolocation.
');
            break;
        case error.POSITION_UNAVAILABLE:
            $('.error-message').html('
Location information is unavailable.
');
            break;
        case error.TIMEOUT:
            $('.error-message').html('
The request to get user location timed out.
');
            break;
        case error.UNKNOWN_ERROR:
            $('.error-message').html('
An unknown error occurred.
');
            break;
    }
}

But the problem comes when the GPS is disabled.

First of all, sometimes, it doesn't enter in geoError(). I tried so many times, but the only thing I "found" is that it caches sometimes. Is that possible ?

But the main problem is that, when the GPS is disabled, the "example alert" pops up, then I turn my GPS on and click the button again, it doesn't work again. I have to refresh the page to apply the GPS turn on. I want to avoid that. Does anyone know why is that happening and is there a way to do what I want?

The other problem is when I load my page with GPS turned on. Then I turn it off and click the button. Nothing happens at all. It enter getGeolocation(), gets true and then it stops. It doesn't enter getCurrentPosition(). Any ideas?


问:
How to get device unlock count in iphone/ipad even if the application is in background
i am new to iOS can anyone tell me how to detect the device unlock count, from the application even if the application goes to background or if the user kills the application..

Its working in android even if the user kills the application..

can anyone please tell me how to do that...

答:
You can hook into the com.apple.springboard.lockstate event:

```<code>- (BOOL)application:(UIApplication *)application
         didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

   int notify_token;

   notify_register_dispatch("com.apple.springboard.lockstate",    &notify_token,dispatch_get_main_queue(), ^(int token) {
      uint64_t state = UINT64_MAX;
      notify_get_state(token, &state);

      if (state == 0) {
         locked++;
      } else {
         unlocked++;
      }
  });
</code>```

Put this code in your app-delegate

Body:
You can hook into the com.apple.springboard.lockstate event:

- (BOOL)application:(UIApplication *)application
         didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

   int notify_token;

   notify_register_dispatch("com.apple.springboard.lockstate",    &notify_token,dispatch_get_main_queue(), ^(int token) {
      uint64_t state = UINT64_MAX;
      notify_get_state(token, &state);

      if (state == 0) {
         locked++;
      } else {
         unlocked++;
      }
  });

Put this code in your app-delegate


问:
Offline Java Documentation
I've finally gotten around to learning Java and am looking for some documentation for Java that I can download and read offline. Something like Sun's stuff but zipped up or as a PDF or CHM.

I'm using Eclipse so something that integrates with that would be nice. It already seems to have some of what I want somewhere (the javadoc stuff) but I don't see how to search it and I'm not seeing a language ref.

答:
Full Documentation in Windows Help Format
http://javadoc.allimant.org/</p>

OwnerDisplayName: BCS

Title: Offline Java Documentation

LastEditorDisplayName: Gamecat

OwnerDisplayName: Timur Fanshteyn

ContentLicense: CC BY-SA 2.5


问:
Best Way to Store Laravel Passport Token in Client Side Angular2 / Angular4
I am Developing a user module with Laravel 5 as backend with passport and Angular 4 is front end client.

In this Module After authenticating the user in server side passport issues a access_token , and refresh_token and i am storing both Tokens in Client side
Local storage, and working fine.

My questions is what is the better way to store the user Auth token in client side  "Local Storage" or "Cookies".

Can anyone Please suggest the better way to store the sensitive data from vulnerability.

Thanks in Advance.

答:
Local storage and cookie have their own advantage and disadvantages.
so before selecting your storage take consider below points

Cookie are more prone CSRF attack so you should be careful.

Local storage token domain based so you can't access local storage tokens from other domain and sub domain.

if domain is not problem than i will recommend using local storage.


问:
SVG - Move a circle along a path of an animated straight line
I am trying to do a simple animation of a circle that moves along with a line that is also being animated.

My current method for moving the circle is using  and just matching the to and from coordinates with the start and end coordinates of the line, it's a manual and time consuming process.

I was also reading that the SMIL animation is deprecated with little or no support in the future. https://developer.mozilla.org/en-US/docs/Web/SVG/SVG_animation_with_SMIL

Can anyone suggest a more efficient way of doing this?

.line {
  stroke: #bfbfbf;
  stroke-width: 1;
  fill: none;
  animation: drawline 2s linear forwards;
  -moz-animation: drawline 2s linear forwards;
  -webkit-animation: drawline 2s linear forwards;
}

@keyframes drawline {
  from {
    stroke-dasharray: 0 400;
    stroke-dashoffset: 0;
  }
  to {
    stroke-dasharray: 400 400;
    stroke-dashoffset: 0;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 521.156 545.59">

  <line class="line" id="audit-line" fill="#000" stroke="#bfbfbf" x1="154" y1="238" x2="214" y2="30"></line>

  <circle id="audit-circle" r="18" cx="158" cy="238" stroke="#7ac142" fill="#7ac142" />
  <text id="audit-text" font-family="Arial" font-size="13">A</text>
  <text id="audit" class="fade-in delay-2" x="245" y="35" font-size="13" font-family="Arial">Text</text>
  <animate
    xlink:href="#audit-circle"
    attributeName="cx"
    to="214"
    dur="1s"
    fill="freeze" />
  <animate
    xlink:href="#audit-circle"
    attributename="cy"
    to="30"
    dur="1s"
    fill="freeze"
  />
  <animate
    xlink:href="#audit-text"
    attributeName="x"
    from="155"
    to="210"
    dur="1s"
    fill="freeze" />
  <animate
    xlink:href="#audit-text"
    attributename="y"
    from="240"
    to="35"
    dur="1s"
    fill="freeze"
  />

</svg></code>```

答:
You can do it a little more efficiently. For example, you don't need to animate the circle and its text independently.  Also, IMO you are making things complicated for yourself by mixing CSS and SMIL animation.

.line {
  stroke: #bfbfbf;
  stroke-width: 1;
  fill: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 521.156 545.59">

  <line class="line" id="audit-line" fill="#000" stroke="#bfbfbf" x1="154" y1="238" x2="154" y2="238"></line>

  <g id="audit-circle">
    <circle r="18" cx="158" cy="238" stroke="#7ac142" fill="#7ac142" />
    <text x="154" y="242" font-family="Arial" font-size="13">A</text>
  </g>

  <text id="audit" class="fade-in delay-2" x="245" y="35" font-size="13" font-family="Arial">Text</text>

  <animateTransform
    xlink:href="#audit-circle"
    attributeName="transform"
    type="translate" from="0,0" to="56,-208" dur="1s"
                    additive="replace" fill="freeze"/>
  <animate
    xlink:href="#audit-line"
    attributeName="x2"
    from="154"
    to="214"
    dur="1s"
    fill="freeze" />
  <animate
    xlink:href="#audit-line"
    attributename="y2"
    from="238"
    to="30"
    dur="1s"
    fill="freeze"
  />

</svg></code>```

Body:
I am trying to do a simple animation of a circle that moves along with a line that is also being animated.

My current method for moving the circle is using  and just matching the to and from coordinates with the start and end coordinates of the line, it's a manual and time consuming process.

I was also reading that the SMIL animation is deprecated with little or no support in the future. https://developer.mozilla.org/en-US/docs/Web/SVG/SVG_animation_with_SMIL

Can anyone suggest a more efficient way of doing this?

.line {
  stroke: #bfbfbf;
  stroke-width: 1;
  fill: none;
  animation: drawline 2s linear forwards;
  -moz-animation: drawline 2s linear forwards;
  -webkit-animation: drawline 2s linear forwards;
}

@keyframes drawline {
  from {
    stroke-dasharray: 0 400;
    stroke-dashoffset: 0;
  }
  to {
    stroke-dasharray: 400 400;
    stroke-dashoffset: 0;
  }
}

<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 521.156 545.59">

  <line class="line" id="audit-line" fill="#000" stroke="#bfbfbf" x1="154" y1="238" x2="214" y2="30"></line>

  <circle id="audit-circle" r="18" cx="158" cy="238" stroke="#7ac142" fill="#7ac142" />
  <text id="audit-text" font-family="Arial" font-size="13">A</text>
  <text id="audit" class="fade-in delay-2" x="245" y="35" font-size="13" font-family="Arial">Text</text>
  <animate
    xlink:href="#audit-circle"
    attributeName="cx"
    to="214"
    dur="1s"
    fill="freeze" />
  <animate
    xlink:href="#audit-circle"
    attributename="cy"
    to="30"
    dur="1s"
    fill="freeze"
  />
  <animate
    xlink:href="#audit-text"
    attributeName="x"
    from="155"
    to="210"
    dur="1s"
    fill="freeze" />
  <animate
    xlink:href="#audit-text"
    attributename="y"
    from="240"
    to="35"
    dur="1s"
    fill="freeze"
  />

</svg>

Body:
You can do it a little more efficiently. For example, you don't need to animate the circle and its text independently.  Also, IMO you are making things complicated for yourself by mixing CSS and SMIL animation.

.line {
  stroke: #bfbfbf;
  stroke-width: 1;
  fill: none;
}

<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 521.156 545.59">

  <line class="line" id="audit-line" fill="#000" stroke="#bfbfbf" x1="154" y1="238" x2="154" y2="238"></line>

  <g id="audit-circle">
    <circle r="18" cx="158" cy="238" stroke="#7ac142" fill="#7ac142" />
    <text x="154" y="242" font-family="Arial" font-size="13">A</text>
  </g>

  <text id="audit" class="fade-in delay-2" x="245" y="35" font-size="13" font-family="Arial">Text</text>

  <animateTransform
    xlink:href="#audit-circle"
    attributeName="transform"
    type="translate" from="0,0" to="56,-208" dur="1s"
                    additive="replace" fill="freeze"/>
  <animate
    xlink:href="#audit-line"
    attributeName="x2"
    from="154"
    to="214"
    dur="1s"
    fill="freeze" />
  <animate
    xlink:href="#audit-line"
    attributename="y2"
    from="238"
    to="30"
    dur="1s"
    fill="freeze"
  />

</svg>


问:
Using AJAX to change a file in PHP
I'm trying to duplicate a file and put some information in. First I used the form-method-action (Method 1). This worked. But I wanted to used Ajax to stay on the same page. So then I created Method 2 but this method doesn't work.

This is how my folder looks like. The 'Document.docx' has '$naam' in it's file

HTML METHOD 1:

```<code><form method="post" action="kopie.php">
    <ul>
        <li><input type="text" name="factuur" id="factuur" placeholder="factuurnaam"></li>
        <li><input type="text" name="naam" id="naam" placeholder="naam"></li>
        <li><input type="submit" name="submit" id="submit"></li>
    </ul>
    <h2 class="ans"></h2>
</form>
</code>```

HTML METHOD 2:

```<code>        <ul>
            <li><input type="text" name="factuur" id="factuur" placeholder="factuurnaam"></li>
            <li><input type="text" name="naam" id="naam" placeholder="naam"></li>
            <li><input type="submit" name="submit" id="submit"></li>
        </ul>
        <h2 class="ans"></h2>

    <script type="text/javascript">
        $(document).ready(function(){
            $("#submit").click(function() {
                $.ajax({
                    url: 'kopie.php',
                    method: 'POST',
                    data: {
                        factuur: factuur,
                        naam: naam
                    }
                    success: function() {
                        $('#ans').html("It worked");
                    }
                })
            })
        })
    </script>
</code>```

PHP FOR BOTH METHODS:

```<code>    $factuur = $_POST['factuur'];

    $zip = new ZipArchive;
    //This is the main document in a .docx file.
    $fileToModify = 'word/document.xml';
    $wordDoc = "Document.docx";
    $newFile = $factuur . ".docx";

    copy("Document.docx", $newFile);

    $naam2 = $_POST['naam'];

    if ($zip->open($newFile) === TRUE) {

        $oldContents = $zip->getFromName($fileToModify);

        $newContents = str_replace('$naam', $naam2, $oldContents);

        $zip->deleteName($fileToModify);

        $zip->addFromString($fileToModify, $newContents);

        $return =$zip->close();
        If ($return==TRUE){
            echo "Success!";
        }
    } else {
        echo 'failed';
    }

    $newFilePath = 'factuur/' . $newFile;

    //Move the file using PHP's rename function.
    $fileMoved = rename($newFile, $newFilePath);
</code>```

答:
You need to define your input value on your data.

$(document).ready(function(){
  $("#submit").click(function() {
    $.ajax({
      url: 'kopie.php',
      method: 'POST',
      data: {
        factuur: $('input[name=factuur]').val(),
        naam: $('input[name=naam]').val()
      },
      success: function() {
          $('#ans').html("It worked");
      }
    })
  })
})```

Title: Using AJAX to change a file in PHP

Body:
I'm trying to duplicate a file and put some information in. First I used the form-method-action (Method 1). This worked. But I wanted to used Ajax to stay on the same page. So then I created Method 2 but this method doesn't work.

This is how my folder looks like. The 'Document.docx' has '$naam' in it's file

HTML METHOD 1:

<form method="post" action="kopie.php">

<input type="text" name="factuur" id="factuur" placeholder="factuurnaam">

<input type="text" name="naam" id="naam" placeholder="naam">

<input type="submit" name="submit" id="submit">

</form>

HTML METHOD 2:

<input type="text" name="factuur" id="factuur" placeholder="factuurnaam">

<input type="text" name="naam" id="naam" placeholder="naam">

<input type="submit" name="submit" id="submit">

PHP FOR BOTH METHODS:

    $factuur = $_POST['factuur'];

    $zip = new ZipArchive;
    //This is the main document in a .docx file.
    $fileToModify = 'word/document.xml';
    $wordDoc = "Document.docx";
    $newFile = $factuur . ".docx";

    copy("Document.docx", $newFile);

    $naam2 = $_POST['naam'];

    if ($zip->open($newFile) === TRUE) {

        $oldContents = $zip->getFromName($fileToModify);

        $newContents = str_replace('$naam', $naam2, $oldContents);

        $zip->deleteName($fileToModify);

        $zip->addFromString($fileToModify, $newContents);

        $return =$zip->close();
        If ($return==TRUE){
            echo "Success!";
        }
    } else {
        echo 'failed';
    }

    $newFilePath = 'factuur/' . $newFile;

    //Move the file using PHP's rename function.
    $fileMoved = rename($newFile, $newFilePath);


问:
Call to undefined method GuzzleHttp\Psr7\Uri::composeComponents()
I can't seem to get a simple file upload to work on Laravel 5.4. I have my file system configured correctly with the proper environment variables for S3. When I process files to upload using this code:

```<code>$disk = Storage::disk('s3');
foreach ($request->allFiles() as $file) {
    $disk->putFileAs('file-requests', $file, $file->getClientOriginalName());
}
</code>```

I get this error:

```<code>(1/1) FatalThrowableError
Call to undefined method GuzzleHttp\Psr7\Uri::composeComponents()
in UriResolver.php (line 102)
at UriResolver::resolve(object(Uri), object(Uri))
in RestSerializer.php (line 206)
at RestSerializer->buildEndpoint(object(Operation), array('Bucket' => 'myBucket', 'Key' => 'file-requests/test_2MB.dump', 'Body' => object(Stream), 'ACL' => 'private', 'ContentType' => 'text/plain', 'ContentLength' => 2097152, '@http' => array()), array('body' => object(Stream), 'headers' => array('x-amz-acl' => 'private', 'Content-Type' => 'text/plain', 'Content-Length' => 2097152)))
in RestSerializer.php (line 48)
at RestSerializer->__invoke(object(Command))
in Middleware.php (line 97)
at Middleware::Aws\{closure}(object(Command), null)
in Middleware.php (line 81)
at Middleware::Aws\{closure}(object(Command), null)
in S3Client.php (line 421)
at S3Client::Aws\S3\{closure}(object(Command), null)
in S3Client.php (line 444)
at S3Client::Aws\S3\{closure}(object(Command), null)
in S3Client.php (line 378)
at S3Client::Aws\S3\{closure}(object(Command), null)
in S3Client.php (line 397)
at S3Client::Aws\S3\{closure}(object(Command), null)
in Middleware.php (line 55)
at Middleware::Aws\{closure}(object(Command), null)
in SSECMiddleware.php (line 59)
at SSECMiddleware->__invoke(object(Command), null)
in IdempotencyTokenMiddleware.php (line 77)
at IdempotencyTokenMiddleware->__invoke(object(Command))
in AwsClientTrait.php (line 65)
at AwsClient->executeAsync(object(Command))
in ObjectUploader.php (line 90)
at ObjectUploader->promise()
in S3ClientTrait.php (line 44)
at S3Client->uploadAsync('myBucket', 'file-requests/test_2MB.dump', resource, 'private', array('params' => array('ContentType' => 'text/plain', 'ContentLength' => 2097152)))
in S3ClientTrait.php (line 29)
at S3Client->upload('myBucket', 'file-requests/test_2MB.dump', resource, 'private', array('params' => array('ContentType' => 'text/plain', 'ContentLength' => 2097152)))
in AwsS3Adapter.php (line 582)
at AwsS3Adapter->upload('file-requests/test_2MB.dump', resource, object(Config))
in AwsS3Adapter.php (line 367)
at AwsS3Adapter->writeStream('file-requests/test_2MB.dump', resource, object(Config))
in Filesystem.php (line 122)
at Filesystem->putStream('file-requests/test_2MB.dump', resource, object(Config))
in FilesystemAdapter.php (line 118)
at FilesystemAdapter->put('file-requests/test_2MB.dump', resource, array())
in FilesystemAdapter.php (line 152)
at FilesystemAdapter->putFileAs('file-requests/test_2MB.dump', object(UploadedFile), 'test_2MB.dump')
in FileRequestsController.php (line 373)
at FileRequestsController->upload(object(Request), object(FileRequest))
at call_user_func_array(array(object(FileRequestsController), 'upload'), array(object(Request), 'file_request' => object(FileRequest)))
in Controller.php (line 55)
at Controller->callAction('upload', array(object(Request), 'file_request' => object(FileRequest)))
in ControllerDispatcher.php (line 44)
at ControllerDispatcher->dispatch(object(Route), object(FileRequestsController), 'upload')
in Route.php (line 203)
at Route->runController()
in Route.php (line 160)
at Route->run()
in Router.php (line 574)
at Router->Illuminate\Routing\{closure}(object(Request))
in Pipeline.php (line 30)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in BaseController.php (line 20)
at BaseController->App\Http\Controllers\{closure}(object(Request), object(Closure))
in Pipeline.php (line 131)
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in LoginUsingOldPlm.php (line 39)
at LoginUsingOldPlm->handle(object(Request), object(Closure))
in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in SubstituteBindings.php (line 41)
at SubstituteBindings->handle(object(Request), object(Closure))
in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in Authenticate.php (line 43)
at Authenticate->handle(object(Request), object(Closure))
in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in VerifyCsrfToken.php (line 65)
at VerifyCsrfToken->handle(object(Request), object(Closure))
in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in ShareErrorsFromSession.php (line 49)
at ShareErrorsFromSession->handle(object(Request), object(Closure))
in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in StartSession.php (line 64)
at StartSession->handle(object(Request), object(Closure))
in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in AddQueuedCookiesToResponse.php (line 37)
at AddQueuedCookiesToResponse->handle(object(Request), object(Closure))
in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in EncryptCookies.php (line 59)
at EncryptCookies->handle(object(Request), object(Closure))
in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in Pipeline.php (line 102)
at Pipeline->then(object(Closure))
in Router.php (line 576)
at Router->runRouteWithinStack(object(Route), object(Request))
in Router.php (line 535)
at Router->dispatchToRoute(object(Request))
in Router.php (line 513)
at Router->dispatch(object(Request))
in Kernel.php (line 174)
at Kernel->Illuminate\Foundation\Http\{closure}(object(Request))
in Pipeline.php (line 30)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in TransformsRequest.php (line 30)
at TransformsRequest->handle(object(Request), object(Closure))
in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in TransformsRequest.php (line 30)
at TransformsRequest->handle(object(Request), object(Closure))
in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in ValidatePostSize.php (line 27)
at ValidatePostSize->handle(object(Request), object(Closure))
in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in CheckForMaintenanceMode.php (line 46)
at CheckForMaintenanceMode->handle(object(Request), object(Closure))
in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in Pipeline.php (line 102)
at Pipeline->then(object(Closure))
in Kernel.php (line 149)
at Kernel->sendRequestThroughRouter(object(Request))
in Kernel.php (line 116)
at Kernel->handle(object(Request))
in index.php (line 52)
</code>```

BUT the method IS defined. Maybe I am missing something but I can't see it. Any help is appreciated. Adding this at line 102 in the UriResolver.php:

```<code>$_uri = new Uri();
var_dump(method_exists($_uri, 'composeComponents'));
exit;
</code>```

On my fresh Laravel install returns:

```<code>/home/vagrant/Code/test-aws/vendor/guzzlehttp/psr7/src/UriResolver.php:103:boolean true
</code>```

On my large project it says:

```<code>/home/vagrant/Code/plm/vendor/guzzlehttp/psr7/src/UriResolver.php:103:boolean false
</code>```

Even though it does exist. I believe the real question is what would make static methods on a class not exist or be uncallable. Moving the method into a variable I was able to complete my file upload to AWS but this is all kinds of wrong:

```<code>$composeComponents = function ($scheme, $authority, $path, $query, $fragment) {
    $uri = '';

    // weak type checks to also accept null until we can add scalar type hints
    if ($scheme != '') {
        $uri .= $scheme . ':';
    }

    if ($authority != ''|| $scheme === 'file') {
        $uri .= '//' . $authority;
    }

    $uri .= $path;

    if ($query != '') {
        $uri .= '?' . $query;
    }

    if ($fragment != '') {
        $uri .= '#' . $fragment;
    }

    return $uri;
};

//$_uri = new Uri();
//var_dump($_uri);
//var_dump(method_exists($_uri, 'composeComponents'));
//exit;

//return new Uri(Uri::composeComponents(
return new Uri($composeComponents(
    $base->getScheme(),
    $targetAuthority,
    $targetPath,
    $targetQuery,
    $rel->getFragment()
));
</code>```

答:
This was an autoloading issue.

I have a older website within Laravel that has its own autoloading. This occurred because a middleware always included a file from the older website which caused irregular behavior.

Body:
I can't seem to get a simple file upload to work on Laravel 5.4. I have my file system configured correctly with the proper environment variables for S3. When I process files to upload using this code:

$disk = Storage::disk('s3');
foreach ($request->allFiles() as $file) {
    $disk->putFileAs('file-requests', $file, $file->getClientOriginalName());
}

I get this error:

(1/1) FatalThrowableError
Call to undefined method GuzzleHttp\Psr7\Uri::composeComponents()
in UriResolver.php (line 102)
at UriResolver::resolve(object(Uri), object(Uri))
in RestSerializer.php (line 206)
at RestSerializer->buildEndpoint(object(Operation), array('Bucket' => 'myBucket', 'Key' => 'file-requests/test_2MB.dump', 'Body' => object(Stream), 'ACL' => 'private', 'ContentType' => 'text/plain', 'ContentLength' => 2097152, '@http' => array()), array('body' => object(Stream), 'headers' => array('x-amz-acl' => 'private', 'Content-Type' => 'text/plain', 'Content-Length' => 2097152)))
in RestSerializer.php (line 48)
at RestSerializer->__invoke(object(Command))
in Middleware.php (line 97)
at Middleware::Aws\{closure}(object(Command), null)
in Middleware.php (line 81)
at Middleware::Aws\{closure}(object(Command), null)
in S3Client.php (line 421)
at S3Client::Aws\S3\{closure}(object(Command), null)
in S3Client.php (line 444)
at S3Client::Aws\S3\{closure}(object(Command), null)
in S3Client.php (line 378)
at S3Client::Aws\S3\{closure}(object(Command), null)
in S3Client.php (line 397)
at S3Client::Aws\S3\{closure}(object(Command), null)
in Middleware.php (line 55)
at Middleware::Aws\{closure}(object(Command), null)
in SSECMiddleware.php (line 59)
at SSECMiddleware->__invoke(object(Command), null)
in IdempotencyTokenMiddleware.php (line 77)
at IdempotencyTokenMiddleware->__invoke(object(Command))
in AwsClientTrait.php (line 65)
at AwsClient->executeAsync(object(Command))
in ObjectUploader.php (line 90)
at ObjectUploader->promise()
in S3ClientTrait.php (line 44)
at S3Client->uploadAsync('myBucket', 'file-requests/test_2MB.dump', resource, 'private', array('params' => array('ContentType' => 'text/plain', 'ContentLength' => 2097152)))
in S3ClientTrait.php (line 29)
at S3Client->upload('myBucket', 'file-requests/test_2MB.dump', resource, 'private', array('params' => array('ContentType' => 'text/plain', 'ContentLength' => 2097152)))
in AwsS3Adapter.php (line 582)
at AwsS3Adapter->upload('file-requests/test_2MB.dump', resource, object(Config))
in AwsS3Adapter.php (line 367)
at AwsS3Adapter->writeStream('file-requests/test_2MB.dump', resource, object(Config))
in Filesystem.php (line 122)
at Filesystem->putStream('file-requests/test_2MB.dump', resource, object(Config))
in FilesystemAdapter.php (line 118)
at FilesystemAdapter->put('file-requests/test_2MB.dump', resource, array())
in FilesystemAdapter.php (line 152)
at FilesystemAdapter->putFileAs('file-requests/test_2MB.dump', object(UploadedFile), 'test_2MB.dump')
in FileRequestsController.php (line 373)
at FileRequestsController->upload(object(Request), object(FileRequest))
at call_user_func_array(array(object(FileRequestsController), 'upload'), array(object(Request), 'file_request' => object(FileRequest)))
in Controller.php (line 55)
at Controller->callAction('upload', array(object(Request), 'file_request' => object(FileRequest)))
in ControllerDispatcher.php (line 44)
at ControllerDispatcher->dispatch(object(Route), object(FileRequestsController), 'upload')
in Route.php (line 203)
at Route->runController()
in Route.php (line 160)
at Route->run()
in Router.php (line 574)
at Router->Illuminate\Routing\{closure}(object(Request))
in Pipeline.php (line 30)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in BaseController.php (line 20)
at BaseController->App\Http\Controllers\{closure}(object(Request), object(Closure))
in Pipeline.php (line 131)
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in LoginUsingOldPlm.php (line 39)
at LoginUsingOldPlm->handle(object(Request), object(Closure))
in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in SubstituteBindings.php (line 41)
at SubstituteBindings->handle(object(Request), object(Closure))
in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in Authenticate.php (line 43)
at Authenticate->handle(object(Request), object(Closure))
in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in VerifyCsrfToken.php (line 65)
at VerifyCsrfToken->handle(object(Request), object(Closure))
in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in ShareErrorsFromSession.php (line 49)
at ShareErrorsFromSession->handle(object(Request), object(Closure))
in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in StartSession.php (line 64)
at StartSession->handle(object(Request), object(Closure))
in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in AddQueuedCookiesToResponse.php (line 37)
at AddQueuedCookiesToResponse->handle(object(Request), object(Closure))
in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in EncryptCookies.php (line 59)
at EncryptCookies->handle(object(Request), object(Closure))
in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in Pipeline.php (line 102)
at Pipeline->then(object(Closure))
in Router.php (line 576)
at Router->runRouteWithinStack(object(Route), object(Request))
in Router.php (line 535)
at Router->dispatchToRoute(object(Request))
in Router.php (line 513)
at Router->dispatch(object(Request))
in Kernel.php (line 174)
at Kernel->Illuminate\Foundation\Http\{closure}(object(Request))
in Pipeline.php (line 30)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in TransformsRequest.php (line 30)
at TransformsRequest->handle(object(Request), object(Closure))
in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in TransformsRequest.php (line 30)
at TransformsRequest->handle(object(Request), object(Closure))
in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in ValidatePostSize.php (line 27)
at ValidatePostSize->handle(object(Request), object(Closure))
in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in CheckForMaintenanceMode.php (line 46)
at CheckForMaintenanceMode->handle(object(Request), object(Closure))
in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in Pipeline.php (line 102)
at Pipeline->then(object(Closure))
in Kernel.php (line 149)
at Kernel->sendRequestThroughRouter(object(Request))
in Kernel.php (line 116)
at Kernel->handle(object(Request))
in index.php (line 52)

BUT the method IS defined. Maybe I am missing something but I can't see it. Any help is appreciated. Adding this at line 102 in the UriResolver.php:

$_uri = new Uri();
var_dump(method_exists($_uri, 'composeComponents'));
exit;

On my fresh Laravel install returns:

/home/vagrant/Code/test-aws/vendor/guzzlehttp/psr7/src/UriResolver.php:103:boolean true

On my large project it says:

/home/vagrant/Code/plm/vendor/guzzlehttp/psr7/src/UriResolver.php:103:boolean false

Even though it does exist. I believe the real question is what would make static methods on a class not exist or be uncallable. Moving the method into a variable I was able to complete my file upload to AWS but this is all kinds of wrong:

$composeComponents = function ($scheme, $authority, $path, $query, $fragment) {
    $uri = '';

    // weak type checks to also accept null until we can add scalar type hints
    if ($scheme != '') {
        $uri .= $scheme . ':';
    }

    if ($authority != ''|| $scheme === 'file') {
        $uri .= '//' . $authority;
    }

    $uri .= $path;

    if ($query != '') {
        $uri .= '?' . $query;
    }

    if ($fragment != '') {
        $uri .= '#' . $fragment;
    }

    return $uri;
};

//$_uri = new Uri();
//var_dump($_uri);
//var_dump(method_exists($_uri, 'composeComponents'));
//exit;

//return new Uri(Uri::composeComponents(
return new Uri($composeComponents(
    $base->getScheme(),
    $targetAuthority,
    $targetPath,
    $targetQuery,
    $rel->getFragment()
));


问:
VBA using an array to avoid hard coding values to call different macros
I have values in column D of a sheet (Sheet2) that are derived from a formula of longer values that are automatically entered in column C thru a double-click. So, the values in columnd D is a part taken from the values in column C. On a separate sheet (Sheet5), I have a list of values in the C column of that sheet. If any of the values in column D of Sheet2 equal any of the values in column C of Sheet5, I want the cell in the F column of Sheet2 to turn red. Once the F column cell in Sheet2 is red, depending on the value in column D, I want the red colored cell to become clickable which will take the user to a different sheet listing reference values associated with the value in column D. The code below does just that. However I would like to avoid hard coding the different values in anticipation that some of the values which require a reference code will be added or taken away from the list in column C of Sheet5.

```<code>    Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim c As Range: Set c = Union(Range("D7:D446"), Range("F7:F446"))
    Dim CellF As Range, CellD As Range, Cell As Range

If Not Application.Intersect(c, Range(Target.Address)) _
           Is Nothing Then

        Set CellF = Range("F" & Target.Row)
        Set CellD = Range("D" & Target.Row)

        Dim refCodes As Variant
        refCodes = Sheet5.Range("C1:C17").Value

        If CellF.Value <> "" Then
            CellF.Interior.ColorIndex = 0

            If CellD.Value = refCodes.Value Then
                CellF.Interior.ColorIndex = 3

            'Select Case CellD.Value
                         'Case "0GP", "0MM", "FEST", "IEDU", "ONLC", "PART", "PRDV", "SPPR", "DANC", "LFLC", "MEDA", "CCH", "POUBL", "GA01", "GA17", "GA99", "REDV"
                    'CellF.Interior.ColorIndex = 3
            'Case Else
                'CellF.Interior.ColorIndex = 0

        End If
        End If
End If
End Sub

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
  Set sourceRange = Nothing
  If Target.Column = 6 And Target.Cells.Count = 1 And Target.Interior.ColorIndex = 3 Then
      Set sourceRange = Target

      Select Case Target.Offset(0, -2).Value2
        Case "1000GP": gotoref1
        Case "1000MM": gotoref2
        Case "19FEST": gotoref3
        Case "20IEDU": gotoref4
        Case "20ONLC": gotoref5
        Case "20PART": gotoref6
        Case "20PRDV": gotoref7
        Case "20SPPR": gotoref8
        Case "22DANC": gotoref9
        Case "22LFLC": gotoref10
        Case "22MEDA": gotoref11
        Case "530CCH": gotoref12
        Case "60PUBL": gotoref13
        Case "74GA01": gotoref14
        Case "74GA17": gotoref15
        Case "74GA99": gotoref16
        Case "78REDV": gotoref17
      End Select
End If

End Sub
</code>```

I thought the best way to go about avoiding hard-coding was to create an array. In the first sub you'll see the commented out snip-its of code, I tried to do that but, I am unsure of how I can call the different macros since they are associated with certain values.

Thanks in advance for any help!

答:
I would use Application.Run to call the macro using its string name and a Scripting Dictionary to associate the values with the Macro names.</p>

```<code>Private Sub Worksheet_Change(ByVal Target As Range)

    Dim c As Range: Set c = Union(Range("D7:D446"), Range("F7:F446"))
    Dim CellF As Range, CellD As Range, Cell As Range

    If Not Application.Intersect(c, Range(Target.Address)) Is Nothing Then

        Set CellF = Range("F" & Target.Row)
        Set CellD = Range("D" & Target.Row)

        If CellF.Value <> "" And getMacroDictionary.Exists(CellD.Text) Then
            CellF.Interior.ColorIndex = 3
        Else
            CellF.Interior.ColorIndex = 0
        End If
    End If

End Sub

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim key As String, dic As Object
    Set SourceRange = Nothing
    If Target.Column = 6 And Target.Cells.Count = 1 And Target.Interior.ColorIndex = 3 Then
        Set SourceRange = Target
        Set dic = getMacroDictionary
        key = Target.Offset(0, -2).Value2
        If dic.Exists(key) Then Application.Run dic(key)
    End If

End Sub

Function getMacroDictionary() As Object
    Dim dic As Object
    Set dic = CreateObject("SCripting.Dictionary")
    dic.Add "0GP", "gotoref1"
    dic.Add "0MM", "gotoref2"
    dic.Add "FEST", "gotoref3"
    dic.Add "IEDU", "gotoref4"
    dic.Add "ONLC", "gotoref5"
    dic.Add "PART", "gotoref6"
    dic.Add "PRDV", "gotoref7"
    dic.Add "SPPR", "gotoref8"
    dic.Add "DANC", "gotoref9"
    dic.Add "LFLC", "gotoref10"
    dic.Add "MEDA", "gotoref11"
    dic.Add "CCH", "gotoref12"
    dic.Add "PUBL", "gotoref13"
    dic.Add "GA01", "gotoref14"
    dic.Add "GA17", "gotoref15"
    dic.Add "GA99", "gotoref16"
    dic.Add "REDV", "gotoref17"
    Set getMacroDictionary = dic
End Function
</code>```

Body:
I have values in column D of a sheet (Sheet2) that are derived from a formula of longer values that are automatically entered in column C thru a double-click. So, the values in columnd D is a part taken from the values in column C. On a separate sheet (Sheet5), I have a list of values in the C column of that sheet. If any of the values in column D of Sheet2 equal any of the values in column C of Sheet5, I want the cell in the F column of Sheet2 to turn red. Once the F column cell in Sheet2 is red, depending on the value in column D, I want the red colored cell to become clickable which will take the user to a different sheet listing reference values associated with the value in column D. The code below does just that. However I would like to avoid hard coding the different values in anticipation that some of the values which require a reference code will be added or taken away from the list in column C of Sheet5.

    Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim c As Range: Set c = Union(Range("D7:D446"), Range("F7:F446"))
    Dim CellF As Range, CellD As Range, Cell As Range

If Not Application.Intersect(c, Range(Target.Address)) _
           Is Nothing Then

        Set CellF = Range("F" & Target.Row)
        Set CellD = Range("D" & Target.Row)

        Dim refCodes As Variant
        refCodes = Sheet5.Range("C1:C17").Value

        If CellF.Value <> "" Then
            CellF.Interior.ColorIndex = 0

            If CellD.Value = refCodes.Value Then
                CellF.Interior.ColorIndex = 3

            'Select Case CellD.Value
                         'Case "0GP", "0MM", "FEST", "IEDU", "ONLC", "PART", "PRDV", "SPPR", "DANC", "LFLC", "MEDA", "CCH", "POUBL", "GA01", "GA17", "GA99", "REDV"
                    'CellF.Interior.ColorIndex = 3
            'Case Else
                'CellF.Interior.ColorIndex = 0

        End If
        End If
End If
End Sub

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
  Set sourceRange = Nothing
  If Target.Column = 6 And Target.Cells.Count = 1 And Target.Interior.ColorIndex = 3 Then
      Set sourceRange = Target

      Select Case Target.Offset(0, -2).Value2
        Case "1000GP": gotoref1
        Case "1000MM": gotoref2
        Case "19FEST": gotoref3
        Case "20IEDU": gotoref4
        Case "20ONLC": gotoref5
        Case "20PART": gotoref6
        Case "20PRDV": gotoref7
        Case "20SPPR": gotoref8
        Case "22DANC": gotoref9
        Case "22LFLC": gotoref10
        Case "22MEDA": gotoref11
        Case "530CCH": gotoref12
        Case "60PUBL": gotoref13
        Case "74GA01": gotoref14
        Case "74GA17": gotoref15
        Case "74GA99": gotoref16
        Case "78REDV": gotoref17
      End Select
End If

End Sub

I thought the best way to go about avoiding hard-coding was to create an array. In the first sub you'll see the commented out snip-its of code, I tried to do that but, I am unsure of how I can call the different macros since they are associated with certain values.

Thanks in advance for any help!

Body:
I would use Application.Run to call the macro using its string name and a Scripting Dictionary to associate the values with the Macro names.

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim c As Range: Set c = Union(Range("D7:D446"), Range("F7:F446"))
    Dim CellF As Range, CellD As Range, Cell As Range

    If Not Application.Intersect(c, Range(Target.Address)) Is Nothing Then

        Set CellF = Range("F" & Target.Row)
        Set CellD = Range("D" & Target.Row)

        If CellF.Value <> "" And getMacroDictionary.Exists(CellD.Text) Then
            CellF.Interior.ColorIndex = 3
        Else
            CellF.Interior.ColorIndex = 0
        End If
    End If

End Sub

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim key As String, dic As Object
    Set SourceRange = Nothing
    If Target.Column = 6 And Target.Cells.Count = 1 And Target.Interior.ColorIndex = 3 Then
        Set SourceRange = Target
        Set dic = getMacroDictionary
        key = Target.Offset(0, -2).Value2
        If dic.Exists(key) Then Application.Run dic(key)
    End If

End Sub

Function getMacroDictionary() As Object
    Dim dic As Object
    Set dic = CreateObject("SCripting.Dictionary")
    dic.Add "0GP", "gotoref1"
    dic.Add "0MM", "gotoref2"
    dic.Add "FEST", "gotoref3"
    dic.Add "IEDU", "gotoref4"
    dic.Add "ONLC", "gotoref5"
    dic.Add "PART", "gotoref6"
    dic.Add "PRDV", "gotoref7"
    dic.Add "SPPR", "gotoref8"
    dic.Add "DANC", "gotoref9"
    dic.Add "LFLC", "gotoref10"
    dic.Add "MEDA", "gotoref11"
    dic.Add "CCH", "gotoref12"
    dic.Add "PUBL", "gotoref13"
    dic.Add "GA01", "gotoref14"
    dic.Add "GA17", "gotoref15"
    dic.Add "GA99", "gotoref16"
    dic.Add "REDV", "gotoref17"
    Set getMacroDictionary = dic
End Function


问:
Measuring bytecode usage
I'm looking for an absolute method to benchmark/measure computations performed in python. In Java, it's possible to calculate the bytecode usage for a given set of instructions. Is there a similar approach I could take in Python?

I'm open to alternative suggestions for measuring computation performed so long as the variance is minimal (time for example, is far too sensitive to the machine the code is being run on).

答:
Check out the dis module.

```<code>>>> import dis
>>> def x(a,b):
...     return a+b
...
>>> dis.dis(x)
  2           0 LOAD_FAST                0 (a)
              3 LOAD_FAST                1 (b)
              6 BINARY_ADD
              7 RETURN_VALUE
</code>```

Title: Measuring bytecode usage

Body:
Check out the dis module.

>>> import dis
>>> def x(a,b):
...     return a+b
...
>>> dis.dis(x)
  2           0 LOAD_FAST                0 (a)
              3 LOAD_FAST                1 (b)
              6 BINARY_ADD
              7 RETURN_VALUE


问:
Allow only a single marker on a Google Map
I want the user to place a marker on a Google Map on a page. If the user clicks again, the first marker should disappear, and be replaced by the new one. How would I do this, starting from this code, as provided by Google:

```<code>function myMap() {
        var mapCanvas = document.getElementById("map");
        var mapOptions = {
        center: new google.maps.LatLng(51.7, 5), zoom: 6
        };
        var map = new google.maps.Map(mapCanvas, mapOptions);

        google.maps.event.addListener(map, 'click', function(event) {
            marker = new google.maps.Marker({
            position: event.latLng,
            map: map
            });
        });
</code>```

My first attempt was to add marker.remove(); at the start of the addListener function, this did not work for me.

Thanks in advance for any help!

答:
The following code helps you in placing the marker when the user clicks. If user clicks again the earlier marker is removed and the new position is marked. My answer aims at rectifying your mistakes in the first try you did. Try this.</p>

```<code>  var flag=0,marker;
  map.addListener('click', function(e) {
  if(flag)
    marker.setMap(null);
  else
    flag=1;
  marker = new google.maps.Marker({
    position: e.latLng,
    map: map});
  });
</code>```

Body:
I want the user to place a marker on a Google Map on a page. If the user clicks again, the first marker should disappear, and be replaced by the new one. How would I do this, starting from this code, as provided by Google:

function myMap() {
        var mapCanvas = document.getElementById("map");
        var mapOptions = {
        center: new google.maps.LatLng(51.7, 5), zoom: 6
        };
        var map = new google.maps.Map(mapCanvas, mapOptions);

        google.maps.event.addListener(map, 'click', function(event) {
            marker = new google.maps.Marker({
            position: event.latLng,
            map: map
            });
        });

My first attempt was to add marker.remove(); at the start of the addListener function, this did not work for me.

Thanks in advance for any help!

Body:
The following code helps you in placing the marker when the user clicks. If user clicks again the earlier marker is removed and the new position is marked. My answer aims at rectifying your mistakes in the first try you did. Try this.

  var flag=0,marker;
  map.addListener('click', function(e) {
  if(flag)
    marker.setMap(null);
  else
    flag=1;
  marker = new google.maps.Marker({
    position: e.latLng,
    map: map});
  });


问:
How to get base enum name in Dynamics AX?
I would like get in code name of base enum not value or label.
With this code I get label not name:</p>

```<code>info(enum2str(KPAssetGroup::PWNiP));
</code>```

答:
You can do this as follows.

1 - Declare a EnumId variable.

2 - Declare a dictEnum variable.

3 - Declare a int variable.

4 - Use index2Symbol method of dictEnum to get code name of base enum.

Optional - Use index2Label method of dictEnum to get label of base enum.

Code example:

```<code>static void StackOverflow(Args _args)
{
    EnumId   Id        = enumNum(SalesType);
    DictEnum dictEnum  = new DictEnum(Id);
    int      EnumValue = enum2Int(SalesType::Journal); //Replace Base enum for Your Base Enum.

    info(dictEnum.index2Symbol(EnumValue));
    //info(dictEnum.index2Label(EnumValue)); //Optional only reference
}
</code>```

Body:
I would like get in code name of base enum not value or label.
With this code I get label not name:

info(enum2str(KPAssetGroup::PWNiP));

Body:
You can do this as follows.

1 - Declare a EnumId variable.

2 - Declare a dictEnum variable.

3 - Declare a int variable.

4 - Use index2Symbol method of dictEnum to get code name of base enum.

Optional - Use index2Label method of dictEnum to get label of base enum.

Code example:

static void StackOverflow(Args _args)
{
    EnumId   Id        = enumNum(SalesType);
    DictEnum dictEnum  = new DictEnum(Id);
    int      EnumValue = enum2Int(SalesType::Journal); //Replace Base enum for Your Base Enum.

    info(dictEnum.index2Symbol(EnumValue));
    //info(dictEnum.index2Label(EnumValue)); //Optional only reference
}


问:
Need files from directory with today's date
I am trying to create a method that tells me if there is a current date's file from a parameter passed to it.

Here is my method so far:

```<code>DoesFileExist("c:\temp\file*.*");

private static bool DoesFileExist(string file)
{
  var dir = Path.GetDirectoryName(file);
  var nfile = Path.GetFileName(file);
  var fileEntries = Directory.GetFiles(dir, nfile);
  foreach (string fileName in fileEntries)
  {
    Console.WriteLine(fileName);
  }
  return true;
}
</code>```

fileEntries is populated but what would be the best way to get the file(s) that are today's date, if they exist?

Thanks!

EDIT1

This is what I changed it to:

```<code>DoesFileExist("c:\temp\file*.*");
private static bool DoesFileExist(string file2)
{
  var resultfiles = Directory.GetFiles(file2).Where(file => new FileInfo(file).CreationTime.Date == DateTime.Today.Date);

  if (resultfiles.Count() > 0)
  {
    return true;
  }

  return false;
}

The file2 ends up being c:\\temp\\file*.*.
</code>```

答:
use linq

```<code>var resultfiles = Directory.GetFiles("c:\temp\file*.*")
                 .Where(file => new FileInfo(file).CreationTime.Date == DateTime.Today.Date);
</code>```

Body:
I am trying to create a method that tells me if there is a current date's file from a parameter passed to it.

Here is my method so far:

DoesFileExist("c:\temp\file*.*");

private static bool DoesFileExist(string file)
{
  var dir = Path.GetDirectoryName(file);
  var nfile = Path.GetFileName(file);
  var fileEntries = Directory.GetFiles(dir, nfile);
  foreach (string fileName in fileEntries)
  {
    Console.WriteLine(fileName);
  }
  return true;
}

fileEntries is populated but what would be the best way to get the file(s) that are today's date, if they exist?

Thanks!

EDIT1

This is what I changed it to:

DoesFileExist("c:\temp\file*.*");
private static bool DoesFileExist(string file2)
{
  var resultfiles = Directory.GetFiles(file2).Where(file => new FileInfo(file).CreationTime.Date == DateTime.Today.Date);

  if (resultfiles.Count() > 0)
  {
    return true;
  }

  return false;
}

The file2 ends up being c:\\temp\\file*.*.

Body:
use linq

var resultfiles = Directory.GetFiles("c:\temp\file*.*")
                 .Where(file => new FileInfo(file).CreationTime.Date == DateTime.Today.Date);


问:
To use or not to use SSL? Why use SSL always?
The argument for using SSL is to prevent some malicious user who has gone through the pains of snooping your traffic being able to read your traffic. So while it may make sense if you are using an unsecured wireless (non WPA2) network to use SSL when logging on to your bank account or giving your credit card number, I find it difficult to see it's neccessaity in more common business cases.

Why even bother with SSL?  (when your client is not going to be on an unsecured wireless network)

The only way someone can snoop your particular HTTP connections and data therein is if they have admin access to your router (and then only if there is some facility to monitor/copy traffic), installed some tool on your machine (a key logger of course would by pass SSL anyway) or they monitor you at the ISP (for which a warrant is required in most jurisdictions).

Update Warning Some jurisdictions are not as free as you may think, particularly the 1st and 2nd world, e.g. in the UK, government may soon not require a warrant: http://en.wikipedia.org/wiki/Communications_Data_Bill_2008 which will probably entail the ability to read websites as they were historically (i.e. decrypt SSL) and the US's "Patriot Act" http://en.wikipedia.org/wiki/US_Patriot_Act#Title_II:_Surveillance_procedures

Furthermore:

Accepting SSL connections server side adds significant load as the establishing of a connection is processor intensive (during the generation of secret keys).

Publicly trusted SSL certificates have to be purchased from a 3rd Party periodically

UPDATE: I am actually using SSL, though I thought it worthwhile to ask the question anyway. Certainly I think there are time SSL is not necessary. Maybe this could be turned into a community wiki of the pros and cons of SSL? If so how?

There seems to be commonly occurring myth in the answers below: "anyone between you and the server can eavesdrop on you"...

This is not not possible on the Internet as the low level TCP routers only forward packets where they have to go and even in the same session can be routed through different routes, and no one can look at these packets except in extreme cases - technically or lawfully.

As for someone at the ISP looking at your traffic I wonder why they would signal you out and look at the 'so important data' which no doubt is boring to them, this is also illegal without a warrant.

On your LAN (except wireless) unless you are using a dinosaur Hub which broadcasts every packet there is no way listen on someone else's traffic - this is not possible because the hardware simply does not send the packets to you even if you have your network card in promiscuous mode and are using a sniffing tool such as Snort or Wireshark.

Passive ARP poisoning is one way to  listen in but has to be done internally and should be picked up as name conflicts etc. start occuring and often the default gateway would be static so would be v. difficult cause the default gateway will be on before you.

答:
SSL should be used anywhere where you are communicating information that should not be public.  It is a very dangerous assumption to believe that no-one is listening to traffic between your computer and the remote server.

All someone needs to do to snoop traffic is be on your network - they don't need admin access to your router.  Without using SSL for sensitive communications, a single machine with a virus on a coworkers computer is all that is needed for stealing your identity.

The ISP also has access to all network traffic - how much do you trust their techies?

Dear User,

We've decided against
encrypting our internet traffic
because we just don't think it's
important.  We decided that it's
really too hard to monitor internet
traffic, so if anyone really is
prepared to go to that effort, well
they deserve all the data they can get
their hands on. If you're using an old
style of router, have corrupt IT
staff and/or co-workers, or someone
just doesn't like you and decides to
steal your data, we accept no
liability.

We advise against you telling anyone about our decision, as this will direct unwanted attention to our IP traffic.

Kindest Regards,

Good Enough Programming

Disclaimer: If you are a hacker and stumbled across this message while monitoring IP traffic, we politely point out that what you are doing is illegal, and request that you pretend you never saw it.

OwnerDisplayName: anon

LastEditorDisplayName: anon


问:
ffmpeg: Generate video's thumbnail in original orientation in php
I am trying to generate thumbnail from a video. My command is working fine but it is generating thumbnail in wrong orientation.

I want to keep same orientation of the video I am using.

Here is my command:

```<code>exec("ffmpeg  -i  567293a3a6b48.mp4 -ss   01:00  -vframes 1  thumbnail.jpg");
</code>```

Also thumbnail does not contain any orientation info in exif data.

答:
Having a similar issue and I found these commands:

```<code>ffmpeg -i input -metadata:s:v:0 rotate=0 -c copy output
</code>```

or

```<code>ffmpeg -i input -metadata rotate=0 -c copy output
</code>```

Found here: http://ffmpeg.gusari.org/viewtopic.php?f=11&t=1293#p3523

This wasn't a fix for my project, maybe it will help you?  Additionally, I don't think this includes logic to determine if you need to rotate the image in the first place.

Body:
I am trying to generate thumbnail from a video. My command is working fine but it is generating thumbnail in wrong orientation.

I want to keep same orientation of the video I am using.

Here is my command:

exec("ffmpeg  -i  567293a3a6b48.mp4 -ss   01:00  -vframes 1  thumbnail.jpg");

Also thumbnail does not contain any orientation info in exif data.

Body:
Having a similar issue and I found these commands:

ffmpeg -i input -metadata:s:v:0 rotate=0 -c copy output

or

ffmpeg -i input -metadata rotate=0 -c copy output

Found here: http://ffmpeg.gusari.org/viewtopic.php?f=11&t=1293#p3523

This wasn't a fix for my project, maybe it will help you?  Additionally, I don't think this includes logic to determine if you need to rotate the image in the first place.


问:
Expanding use of Javascript array.reduce helper method
Background

I am following a course on Udemy which goes over all of the ES6 features. In one of the lessons the instructor talks about using the reduce helper method to solve the popular balance parenthesis interview question.

I can solve this without the reduce method. Although with the reduce method it does get the job done in less code. I have been asked to find the depth of the parenthesis in an interview before and was wondering if this could all be done in the same method using reduce.

I do not know why this addition to the question confuses me so much but I would like to learn.

Problem

I have been trying to figure it out for a while and it might be my lack of understanding how reduce works.

Example

This uses reduce to return true of false regarding if the parenthesis or open and closed evenly.

```<code>function balanceParens(string) {
    return !string.split("").reduce((counter, char) => {
        // Handle if parens open and close out of order
        if (counter < 0) { return counter; }
        // Add 1 for each open in order
        if (char === "(") { return ++counter; }
        // subtract 1 for each close in order
        if (char === ")") { return --counter; }
        // handle use case if char is not a paren
        return counter;
    }, 0);
}
console.log(balanceParens("((()))"));
</code>```

Question

How would I return the max depth of the parenthesis using the reduce helper method.

答:
This should answer it!

function balanceParens(string) {
    let max = 0;
    let res = string.split("").reduce((counter, char) => {
        // Handle if parens open and close out of order
        if (counter < 0) {
          return counter;
        }
        // Add 1 for each open in order
        if (char === "(") {
          if(++counter > max) {
            max = counter;
          }
          return counter;
        }
        // subtract 1 for each close in order
        if (char === ")") {
          return --counter;
        }
        // handle use case if char is not a paren
        return counter;
    }, 0);
    console.log("Max depth was :", max);
    return !res;
}
console.log(balanceParens("((()(((())))))((((()))))"));```

Body:
Background

I am following a course on Udemy which goes over all of the ES6 features. In one of the lessons the instructor talks about using the reduce helper method to solve the popular balance parenthesis interview question.

I can solve this without the reduce method. Although with the reduce method it does get the job done in less code. I have been asked to find the depth of the parenthesis in an interview before and was wondering if this could all be done in the same method using reduce.

I do not know why this addition to the question confuses me so much but I would like to learn.

Problem

I have been trying to figure it out for a while and it might be my lack of understanding how reduce works.

Example

This uses reduce to return true of false regarding if the parenthesis or open and closed evenly.

function balanceParens(string) {
    return !string.split("").reduce((counter, char) => {
        // Handle if parens open and close out of order
        if (counter < 0) { return counter; }
        // Add 1 for each open in order
        if (char === "(") { return ++counter; }
        // subtract 1 for each close in order
        if (char === ")") { return --counter; }
        // handle use case if char is not a paren
        return counter;
    }, 0);
}
console.log(balanceParens("((()))"));

Question

How would I return the max depth of the parenthesis using the reduce helper method.


问:
Using sublime regex to find all links that dont start with "home" word
I am using handlebars. So I need a way to detect all {{#link-to 'route-name'}}... helpers that dont start with home name. I am new to regex so I cannot find good regex. Bad example: ([^home]|^) {{#link-to

答:
You're using the [^...] term, which means any character except those in the brackets, so [^home] should match any character except for h, o, m and e.

In your case, what you're searching for is a Negative Lookahead:

```<code>^.+\s?{{#link-to '(?:(?!home).{0,4}.*)'}}
</code>```

Take a look at this Regex101 working example.

^ Matches start of a text (or line, with /m flag enabled)

.+ Matches the name of the element (You may remove it if needed)

\s? Matches one or zero occurrences of a whitespace character (\s, you also may remove)

{{#link-to ' The literal form of the text to be matched

(?: Start of a non-capturing group

(?! Start of a negative lookahead group

home Literal text to NOT be matched

) End of the negative lookahead group

.{0,4} Matches any zero-four characters except if they value is home (because of the (?!home))

.* If the link-to's name is longer than four characters, match them.

) End of the non-capturing group

'}} Literal text to match (end of the route link)

Body:
You're using the [^...] term, which means any character except those in the brackets, so [^home] should match any character except for h, o, m and e.

In your case, what you're searching for is a Negative Lookahead:

^.+\s?{{#link-to '(?:(?!home).{0,4}.*)'}}

Take a look at this Regex101 working example.

^ Matches start of a text (or line, with /m flag enabled)

.+ Matches the name of the element (You may remove it if needed)

\s? Matches one or zero occurrences of a whitespace character (\s, you also may remove)

{{#link-to ' The literal form of the text to be matched

(?: Start of a non-capturing group

(?! Start of a negative lookahead group

home Literal text to NOT be matched

) End of the negative lookahead group

.{0,4} Matches any zero-four characters except if they value is home (because of the (?!home))

.* If the link-to's name is longer than four characters, match them.

) End of the non-capturing group

'}} Literal text to match (end of the route link)


问:
Dynamically Created Controls losing data after postback
Actually, I am Creating 1 TextBox on Pageload and adding that TextBox to Panel.
Now, I have a LinkButton like Add Another.

I am entering Text in that TextBox and if needed I need to Create New TextBox,by clicking Add Another LinkButton.

Actually, I am able to get the count and recreate the TextBoxes.
But,the Problem is that, My Entered text in the Previously Generated Textboxes is Missing.

Can Anyone,Suggest me a solution for this?

```<code>protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!IsPostBack)
            {
                for (int i = 0; i < 5; i++)
                {
                    TableRow row = new TableRow();
                    for (int j = 0; j < 5; j++)
                    {
                        TableCell cell = new TableCell();
                        TextBox tb = new TextBox();
                        tb.ID = "TextBoxRow_" + i + "Col_" + j;
                        cell.Controls.Add(tb);
                        row.Cells.Add(cell);
                    }
                    Table1.Rows.Add(row);
                }
            }
        }
        catch (Exception ex)
        {
            throw;
        }
    }
</code>```

This is a Sample Code, the same code is written in Button_Click Also

```<code> protected void ASPxButton1_Click(object sender, EventArgs e)
    {
 int k = Table1.Controls.Count;
}
</code>```

I am getting a Count=0 on Button_Click.

答:
When  you are working with dynamic controls they will not able to maintain its state during postback and their data lost Cause they dont have any viewstate to maintain their data.

You only need to maintain the created controls data into ViewState
dynamically and loads the data into page at the time of postback and you
done.

```<code>public Dictionary<Guid, string> UcList
{
    get { return ViewState["MyUcIds"] != null ? (Dictionary<Guid, string>)ViewState["MyUcIds"] : new Dictionary<Guid, string>(); }
    set { ViewState["MyUcIds"] = value; }
}

public void InitializeUC()
{
    int index = 1;
    foreach (var item in UcList)
    {
        var myUc = (UserControls_uc_MyUserControl)LoadControl("~/UserControls/uc_MyUserControl.ascx");
        myUc.ID = item.Value;
        pnlMyUC.Controls.AddAt(index, myUc);
        index++;
    }
}

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
        LoadControl();
    else
        InitializeUC();
}
</code>```

Body:
Actually, I am Creating 1 TextBox on Pageload and adding that TextBox to Panel.
Now, I have a LinkButton like Add Another.

I am entering Text in that TextBox and if needed I need to Create New TextBox,by clicking Add Another LinkButton.

Actually, I am able to get the count and recreate the TextBoxes.
But,the Problem is that, My Entered text in the Previously Generated Textboxes is Missing.

Can Anyone,Suggest me a solution for this?

protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!IsPostBack)
            {
                for (int i = 0; i < 5; i++)
                {
                    TableRow row = new TableRow();
                    for (int j = 0; j < 5; j++)
                    {
                        TableCell cell = new TableCell();
                        TextBox tb = new TextBox();
                        tb.ID = "TextBoxRow_" + i + "Col_" + j;
                        cell.Controls.Add(tb);
                        row.Cells.Add(cell);
                    }
                    Table1.Rows.Add(row);
                }
            }
        }
        catch (Exception ex)
        {
            throw;
        }
    }

This is a Sample Code, the same code is written in Button_Click Also

 protected void ASPxButton1_Click(object sender, EventArgs e)
    {
 int k = Table1.Controls.Count;
}

I am getting a Count=0 on Button_Click.

Body:
When  you are working with dynamic controls they will not able to maintain its state during postback and their data lost Cause they dont have any viewstate to maintain their data.

You only need to maintain the created controls data into ViewState
dynamically and loads the data into page at the time of postback and you
done.

public Dictionary<Guid, string> UcList
{
    get { return ViewState["MyUcIds"] != null ? (Dictionary<Guid, string>)ViewState["MyUcIds"] : new Dictionary<Guid, string>(); }
    set { ViewState["MyUcIds"] = value; }
}

public void InitializeUC()
{
    int index = 1;
    foreach (var item in UcList)
    {
        var myUc = (UserControls_uc_MyUserControl)LoadControl("~/UserControls/uc_MyUserControl.ascx");
        myUc.ID = item.Value;
        pnlMyUC.Controls.AddAt(index, myUc);
        index++;
    }
}

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
        LoadControl();
    else
        InitializeUC();
}

ContentLicense: CC BY-SA 4.0


问:
how to submit form in Azure Scheduler
I have a web-service running at AWS (lets say example.com) . I would like to transfer data to the web-service once per hour. I also have Azure account, and I would like to use Azure's Scheduler to transfer data to my web-service.

I can use my web-service by cUrl like this:

```<code>curl -H "Content-Type = application/json" -XPOST http://example.com -F imurl=http://example_image.jpg
</code>```

The above cUrl statement submits a form by using POST method.
I would like to do the same thing what cUrl does in Azure Scheduler but I could not figure out how to fill the body.

Here is what I did in Scheduler:

Fail Detail is:
  Http Action - Response from host '52.164.126.98':
  'InternalServerError' Response Headers: Connection: close Date: Thu,
  06 Jul 2017 08:16:17 GMT Server: Apache/2.4.18 (Ubuntu)  Body:
   500
  Internal Server Error
Internal Server Error

The
  server encountered an internal error and was unable to complete your
  request.  Either the server is overloaded or there is an error in the
  application.

when I check /var/log/apache2/error.log it says imurl is not assigned properly.

答:
Please consider using Logic Apps instead of Scheduler for this scenario.

With Logic Apps, start with a recurrence trigger followed by an HTTP action, to send formdata, format the body of the HTTP request like so:

```<code>"body": {
   "$content-type": "multipart/form-data",
   "$multipart": [
      {
         "body": "val0",
         "headers": {
            "Content-Disposition": "form-data; name=\"pkey0\""
         }
      },
      {
         "body": "val1",
         "headers": {
            "Content-Disposition": "form-data; name=\"pkey1\""
         }
      }
   ]
}
</code>```

Alternatively, if you have a Swagger definition of the API you're trying to invoke, simply supply that to the HTTP+Swagger action in Logic Apps and we will populate a composer it for you.

Title: how to submit form in Azure Scheduler

Body:
I have a web-service running at AWS (lets say example.com) . I would like to transfer data to the web-service once per hour. I also have Azure account, and I would like to use Azure's Scheduler to transfer data to my web-service.

I can use my web-service by cUrl like this:

curl -H "Content-Type = application/json" -XPOST http://example.com -F imurl=http://example_image.jpg

The above cUrl statement submits a form by using POST method.
I would like to do the same thing what cUrl does in Azure Scheduler but I could not figure out how to fill the body.

Here is what I did in Scheduler:

Fail Detail is:
  Http Action - Response from host '52.164.126.98':
  'InternalServerError' Response Headers: Connection: close Date: Thu,
  06 Jul 2017 08:16:17 GMT Server: Apache/2.4.18 (Ubuntu)  Body:
   500
  Internal Server Error
Internal Server Error

The
  server encountered an internal error and was unable to complete your
  request.  Either the server is overloaded or there is an error in the
  application.

when I check /var/log/apache2/error.log it says imurl is not assigned properly.

Body:
Please consider using Logic Apps instead of Scheduler for this scenario.

With Logic Apps, start with a recurrence trigger followed by an HTTP action, to send formdata, format the body of the HTTP request like so:

"body": {
   "$content-type": "multipart/form-data",
   "$multipart": [
      {
         "body": "val0",
         "headers": {
            "Content-Disposition": "form-data; name=\"pkey0\""
         }
      },
      {
         "body": "val1",
         "headers": {
            "Content-Disposition": "form-data; name=\"pkey1\""
         }
      }
   ]
}

Alternatively, if you have a Swagger definition of the API you're trying to invoke, simply supply that to the HTTP+Swagger action in Logic Apps and we will populate a composer it for you.


问:
loading page shows for three seconds
I'm making a personal portfolio and want to show my site tagline for like 3 seconds (full screen), then fade out to show the actual website. What code is used to show some initial div then fade out to the actual website?</p>

答:
I made a CSS-only version using CSS3 keyframes/animation.

HTML:

```<code><div id="websiteOverlay">
  "Some tagline"
</div>
<div class="container">
  <h1>
    Website content header
  </h1>
  <p>
    Website content body, with some paragraphs
  </p>
</div>
</code>```

CSS:

```<code>@-webkit-keyframes fadeOut {
  0% {
    opacity: 1;
  }
  50% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}

@keyframes fadeOut {
  0% {
    opacity: 1;
  }
  50% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}

#websiteOverlay {
  text-align: center;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: black;
  color: white;
  opacity: 0;
  -webkit-animation: fadeOut 3s;
  animation: fadeOut 3s;
}
</code>```

Fiddle: https://jsfiddle.net/9z6ow28m/

Title: loading page shows for three seconds

Body:
I made a CSS-only version using CSS3 keyframes/animation.

HTML:

<div id="websiteOverlay">
  "Some tagline"
</div>
<div class="container">
  <h1>
    Website content header
  </h1>
  <p>
    Website content body, with some paragraphs
  </p>
</div>

CSS:

@-webkit-keyframes fadeOut {
  0% {
    opacity: 1;
  }
  50% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}

@keyframes fadeOut {
  0% {
    opacity: 1;
  }
  50% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}

#websiteOverlay {
  text-align: center;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: black;
  color: white;
  opacity: 0;
  -webkit-animation: fadeOut 3s;
  animation: fadeOut 3s;
}

Fiddle: https://jsfiddle.net/9z6ow28m/


问:
Why does Android's onItemClick want a long for row Id?
For a listView, when you register an OnItemClickListener, the method you specify looks like this:

public abstract void onItemClick (AdapterView parent, View view, int position, long id)

The id corresponds to the row that the user clicked on.  My question is simply why is it a long and not an int?  When would you use it as a long?  I've been casting it to an int when I use it, so it makes me think that maybe I'm using it wrong.

答: Just in case you want more than several million rows.</p>


问:
how to load a ViewController from xib: UIView file? swift 3
OK, i have 2 problem here:

1
I try to load a ViewController from a button in the xib file.
This is my button from my xib: UIView.

```<code>@IBAction func fechaSalida(_ sender: Any) {

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let vc = storyboard.instantiateViewController(withIdentifier: "calendario") as! CalendarioViewController
    self.presentViewController(vc, animated: true, completion: nil)

}
</code>```

The problem here is the presentViewController because my xib is a UIView type, his show me this error: "(value type ViewController) has no member of presentViewController".
Why i try to use this code? is because in my CalendarioViewController i have this code when pressed a button: dismiss(animated: true, completion: nil) so this is my first problem...

2
The second problem is when i have this code in a button inside of my xib: UIView, the CalendarioViewController is load ok...but the code: dismiss(animated: true, completion: nil) is not working anymore.
Here my code of my button xib:

```<code>@IBAction func fechaSalida(_ sender: Any) {

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let vc:CalendarioViewController = storyboard.instantiateViewController(withIdentifier: "calendario") as! CalendarioViewController
    vc.dateDelegate = self
    self.window!.rootViewController = vc

}
</code>```

So..how can load a ViewController (CalendarioViewController) and the dismiss code Keep running?

答:
ok... i have what i need.
For this work i use UITapGestureRecognizer in View Controller which holds the view:

In override func viewDidLoad() put this code:

```<code>    let fechaArriboTap = UITapGestureRecognizer(target: self, action:#selector(handleArribo))
    let fechaSalidaTap = UITapGestureRecognizer(target: self, action:#selector(handleSalida))
    fechaArribo.addGestureRecognizer(fechaArriboTap)
    fechaSalida.addGestureRecognizer(fechaSalidaTap)
</code>```

Then create the methods:

```<code>func handleArribo() {

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let vc:CalendarioViewController = storyboard.instantiateViewController(withIdentifier: "calendario") as! CalendarioViewController
    vc.dateDelegate = self
    present(vc, animated: true, completion: nil)

}

func handleSalida() {

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let vc:CalendarioViewController = storyboard.instantiateViewController(withIdentifier: "calendario") as! CalendarioViewController
    vc.dateDelegate = self
    present(vc, animated: true, completion: nil)

}
</code>```

and thats is! Thanks @sasquatch

Body:
OK, i have 2 problem here:

1
I try to load a ViewController from a button in the xib file.
This is my button from my xib: UIView.

@IBAction func fechaSalida(_ sender: Any) {

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let vc = storyboard.instantiateViewController(withIdentifier: "calendario") as! CalendarioViewController
    self.presentViewController(vc, animated: true, completion: nil)

}

The problem here is the presentViewController because my xib is a UIView type, his show me this error: "(value type ViewController) has no member of presentViewController".
Why i try to use this code? is because in my CalendarioViewController i have this code when pressed a button: dismiss(animated: true, completion: nil) so this is my first problem...

2
The second problem is when i have this code in a button inside of my xib: UIView, the CalendarioViewController is load ok...but the code: dismiss(animated: true, completion: nil) is not working anymore.
Here my code of my button xib:

@IBAction func fechaSalida(_ sender: Any) {

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let vc:CalendarioViewController = storyboard.instantiateViewController(withIdentifier: "calendario") as! CalendarioViewController
    vc.dateDelegate = self
    self.window!.rootViewController = vc

}

So..how can load a ViewController (CalendarioViewController) and the dismiss code Keep running?

Body:
ok... i have what i need.
For this work i use UITapGestureRecognizer in View Controller which holds the view:

In override func viewDidLoad() put this code:

    let fechaArriboTap = UITapGestureRecognizer(target: self, action:#selector(handleArribo))
    let fechaSalidaTap = UITapGestureRecognizer(target: self, action:#selector(handleSalida))
    fechaArribo.addGestureRecognizer(fechaArriboTap)
    fechaSalida.addGestureRecognizer(fechaSalidaTap)

Then create the methods:

func handleArribo() {

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let vc:CalendarioViewController = storyboard.instantiateViewController(withIdentifier: "calendario") as! CalendarioViewController
    vc.dateDelegate = self
    present(vc, animated: true, completion: nil)

}

func handleSalida() {

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let vc:CalendarioViewController = storyboard.instantiateViewController(withIdentifier: "calendario") as! CalendarioViewController
    vc.dateDelegate = self
    present(vc, animated: true, completion: nil)

}

and thats is! Thanks @sasquatch


答:
Try this in your AJAX - I'll note the changes.</p>

```<code>$(document).ready(function(e){
        e.preventDefault(); //keeps the page from refreshing

        $("#submit").click(function() {
        //notice I'm gathering the form data here.
        var data = { 'factuur' : $("#factur").val(),
                     'naam' : $("#naam").val()
         }

            $.ajax({
                url: 'kopie.php',
                method: 'POST',
                data: data, //referencing the data variable above
                dataType: html
                success: function() {
                    $('#ans').html("It worked");
                }
            })
        })
    })
</code>```

Title: Using AJAX to change a file in PHP

Body:
I'm trying to duplicate a file and put some information in. First I used the form-method-action (Method 1). This worked. But I wanted to used Ajax to stay on the same page. So then I created Method 2 but this method doesn't work.

This is how my folder looks like. The 'Document.docx' has '$naam' in it's file

HTML METHOD 1:

<form method="post" action="kopie.php">

<input type="text" name="factuur" id="factuur" placeholder="factuurnaam">

<input type="text" name="naam" id="naam" placeholder="naam">

<input type="submit" name="submit" id="submit">

</form>

HTML METHOD 2:

<input type="text" name="factuur" id="factuur" placeholder="factuurnaam">

<input type="text" name="naam" id="naam" placeholder="naam">

<input type="submit" name="submit" id="submit">

PHP FOR BOTH METHODS:

    $factuur = $_POST['factuur'];

    $zip = new ZipArchive;
    //This is the main document in a .docx file.
    $fileToModify = 'word/document.xml';
    $wordDoc = "Document.docx";
    $newFile = $factuur . ".docx";

    copy("Document.docx", $newFile);

    $naam2 = $_POST['naam'];

    if ($zip->open($newFile) === TRUE) {

        $oldContents = $zip->getFromName($fileToModify);

        $newContents = str_replace('$naam', $naam2, $oldContents);

        $zip->deleteName($fileToModify);

        $zip->addFromString($fileToModify, $newContents);

        $return =$zip->close();
        If ($return==TRUE){
            echo "Success!";
        }
    } else {
        echo 'failed';
    }

    $newFilePath = 'factuur/' . $newFile;

    //Move the file using PHP's rename function.
    $fileMoved = rename($newFile, $newFilePath);

Body:
Try this in your AJAX - I'll note the changes.

$(document).ready(function(e){
        e.preventDefault(); //keeps the page from refreshing

        $("#submit").click(function() {
        //notice I'm gathering the form data here.
        var data = { 'factuur' : $("#factur").val(),
                     'naam' : $("#naam").val()
         }

            $.ajax({
                url: 'kopie.php',
                method: 'POST',
                data: data, //referencing the data variable above
                dataType: html
                success: function() {
                    $('#ans').html("It worked");
                }
            })
        })
    })


问:
How to configure Spark Standalone's web UI for HTTPS?
I'd like to set up Spark Standalone's Web UI so it can be accessed through HTTPS.

Spark is being run on a cluster external to the computer I'm using to access the browser.

Here's what I've done so far, and it's not working:

Used OpenSSL to make a self-signed certificate and key and then keytool to make a keystore

Packaged the certificate and key as a .p12 file

In Chrome's settings under Manage Certificates, imported said p12 file

In spark-defaults.conf, added options

```<code>spark.ui.https.enabled                   true
spark.ui.ssl.server.keystore.location    /path/to/spark.keystore
spark.ui.ssl.server.keystore.keypassword password
spark.ui.ssl.server.keystore.password    password
</code>```

In spark-env.sh, added

```<code>export SPARK_MASTER_OPTS="-Dspark.ui.https.enabled=true \
  -Dspark.ui.ssl.server.keystore.location=/path/to/spark.keystore \
  -Dspark.ui.ssl.server.keystore.keypassword=password \
  -Dspark.ui.ssl.server.keystore.password=password"

export SPARK_WORKER_OPTS="-Dspark.ui.https.enabled=true \
  -Dspark.ui.ssl.server.keystore.location=/path/to/spark.keystore \
  -Dspark.ui.ssl.server.keystore.keypassword=password \
  -Dspark.ui.ssl.server.keystore.password=password"
</code>```

I've tried to connect to the server before, after, and in between each of these steps, and I keep getting the error "This site can’t provide a secure connection". What am I missing here?

答:
According to this line I think that it's not possible to set up the Spark Standalone's web UI with HTTPS.

```<code>masterWebUiUrl = "http://" + masterPublicAddress + ":" + webUi.boundPort
</code>```

My recommendation is to file an issue in Spark's JIRA and find a Spark developer to fix it.

Body:
I'd like to set up Spark Standalone's Web UI so it can be accessed through HTTPS.

Spark is being run on a cluster external to the computer I'm using to access the browser.

Here's what I've done so far, and it's not working:

Used OpenSSL to make a self-signed certificate and key and then keytool to make a keystore

Packaged the certificate and key as a .p12 file

In Chrome's settings under Manage Certificates, imported said p12 file

In spark-defaults.conf, added options

spark.ui.https.enabled                   true
spark.ui.ssl.server.keystore.location    /path/to/spark.keystore
spark.ui.ssl.server.keystore.keypassword password
spark.ui.ssl.server.keystore.password    password

In spark-env.sh, added

export SPARK_MASTER_OPTS="-Dspark.ui.https.enabled=true \
  -Dspark.ui.ssl.server.keystore.location=/path/to/spark.keystore \
  -Dspark.ui.ssl.server.keystore.keypassword=password \
  -Dspark.ui.ssl.server.keystore.password=password"

export SPARK_WORKER_OPTS="-Dspark.ui.https.enabled=true \
  -Dspark.ui.ssl.server.keystore.location=/path/to/spark.keystore \
  -Dspark.ui.ssl.server.keystore.keypassword=password \
  -Dspark.ui.ssl.server.keystore.password=password"

I've tried to connect to the server before, after, and in between each of these steps, and I keep getting the error "This site can’t provide a secure connection". What am I missing here?

Body:
According to this line I think that it's not possible to set up the Spark Standalone's web UI with HTTPS.

masterWebUiUrl = "http://" + masterPublicAddress + ":" + webUi.boundPort

My recommendation is to file an issue in Spark's JIRA and find a Spark developer to fix it.


问:
How can I create the following UI in Android to be used in the bottom of a View?
I am trying to create the following UI for Android.
I want to try to put this UI only in the top or bottom of a View.

How Should I approach this problem.
Can anyone point me in the right direction?

Thanks.

答:
There is no "make a sawtooth border" option as far as I know, so you can do one of these things:

Find/make the background image with the pattern you want and add it as a drawable background (or just apply it on the edges you want)

Generate this pattern in the app using lines of triangles. (But why tho)

Find a library that does it for you.


问:
Add image before all a href tags. works but not inline
This should be easy but can't figure it out.

I'm adding an image icon to all a tags:

```<code>a.textLink:before{
content: "";
background: url("../img/plus-button.png") no-repeat;
background-size:contain;
display: block;
width: 36px;
height: 36px;
float: left;
margin: -6px 6px 0 0;}
}
</code>```

My HTML is just 2 links inline:

```<code><a class="textLink" href="#">Link 1</a>  <a class="textLink clearFloat" href="#">Link 2</a>
</code>```

The problem is, both "plus-buytton.png" images float left, so they aren't inserting before each link but together.

答:
Is this what you want?

a.textLink:before{
content: url("http://files.softicons.com/download/toolbar-icons/24x24-free-button-icons-by-aha-soft/png/24x24/user-admin.png");
vertical-align:middle;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Link 1  Link 2</code>```

Body:
This should be easy but can't figure it out.

I'm adding an image icon to all a tags:

a.textLink:before{
content: "";
background: url("../img/plus-button.png") no-repeat;
background-size:contain;
display: block;
width: 36px;
height: 36px;
float: left;
margin: -6px 6px 0 0;}
}

My HTML is just 2 links inline:

Link 1  Link 2

The problem is, both "plus-buytton.png" images float left, so they aren't inserting before each link but together.

Body:
Is this what you want?

a.textLink:before{
content: url("http://files.softicons.com/download/toolbar-icons/24x24-free-button-icons-by-aha-soft/png/24x24/user-admin.png");
vertical-align:middle;
}

<a class="textLink" href="#">Link 1</a>  <a class="textLink clearFloat" href="#">Link 2</a>


问:
Several GET Methods in ASP .NET WEB API causing 500 when sending array using URI
In my ASP .NET WEB API, I want to use the following methods:

```<code>        [Route(""), HttpGet]
        public IDictionary<int, string> GetAll()
        {
            //doSth
        }

        [Route(""), HttpGet]
        public IDictionary<int, string> GetSpecificOnes([FromUri]IEnumerable<int> carsIds)
        {
            //doSth
        }
</code>```

When requesting the second one using angular, I get the following exception:

```<code>angular.js:12011 GET http://localhost:12345/_api/cars?&carsIds[0]=1&carsIds[1]=2&carsIds[2]=5 500 (Internal Server Error)
</code>```

I think the problem is, that I have two GET-Methods without a route. But I don't need one. How do I solve this problem?

答:
You actually don't need to define a route, like you say, as long as the GET methods in the controllers have different signatures and parameterlist.

The problem in your case is that you call the method the wrong way.

Either change the parameter name in the api method to carsIds or change the angular HTTP query string to ?ids[0]=1&ids[1]=2&ids[2]=5

Body:
In my ASP .NET WEB API, I want to use the following methods:

        [Route(""), HttpGet]
        public IDictionary<int, string> GetAll()
        {
            //doSth
        }

        [Route(""), HttpGet]
        public IDictionary<int, string> GetSpecificOnes([FromUri]IEnumerable<int> carsIds)
        {
            //doSth
        }

When requesting the second one using angular, I get the following exception:

angular.js:12011 GET http://localhost:12345/_api/cars?&carsIds[0]=1&carsIds[1]=2&carsIds[2]=5 500 (Internal Server Error)

I think the problem is, that I have two GET-Methods without a route. But I don't need one. How do I solve this problem?