问:
PHP twig conditional filter
Let's say I have something like this:

what I want to do is apply imagine_filter('watermarked') only if article.isWatermarked() equals to true.

Is there any slicke way of doing this? Or I'm stuck with

```<code>{% set src = asset(article.image.path) %}
{% if article.isWatermarked() %}
{% set src = asset(article.image.path) | imagine_filter('watermarked') %}
{% endif %}
<img src='{{ src }}' />
</code>```

答:
Depending on how many places you need that functionality in you could put it in a macro:

macros.twig:

```<code>{%- macro wmImage(article) -%}
    {%- set src = article.watermarked ? asset(article.image.path) | imagine_filter('watermarked') : asset(article.image.path) -%}
    <img src="{{ src }}"/>
{%- endmacro -%}
</code>```

In your template(s):

```<code>{%- import 'macros.twig' as 'macros' -%}

Usage:
{{ macros.wmImage(article) }}
</code>```

Title: PHP twig conditional filter

Body:
Let's say I have something like this:

what I want to do is apply imagine_filter('watermarked') only if article.isWatermarked() equals to true.

Is there any slicke way of doing this? Or I'm stuck with

{% set src = asset(article.image.path) %}
{% if article.isWatermarked() %}
{% set src = asset(article.image.path) | imagine_filter('watermarked') %}
{% endif %}

Body:
Depending on how many places you need that functionality in you could put it in a macro:

macros.twig:

{%- macro wmImage(article) -%}
    {%- set src = article.watermarked ? asset(article.image.path) | imagine_filter('watermarked') : asset(article.image.path) -%}
    <img src="{{ src }}"/>
{%- endmacro -%}

In your template(s):

{%- import 'macros.twig' as 'macros' -%}

Usage:
{{ macros.wmImage(article) }}


来源: stackexchange

问:
Error : could not find function "ImportMethodFrom"
I tried to run the code in Chapter 7 Data mining with R learning with case study book but I got an error in following line:

```<code>rankWorkflows(svm, maxs = TRUE)
</code>```

The error was:

Error in as.character.default(X[[i]], ...) :    no method for coercing
  this S4 class to a vector

Then I searched on the internet and found following solution:

```<code>importMethodsFrom(GenomicRanges, as.data.frame)
</code>```

and again again I got a new error:

Error: could not find function "importMethodFrom"

I searched a lot but I got nothing :(

答:
Based on the answer of @Bea, there does not seem to be a importMethodsFrom anywhere in R. My guess is you found the call in a NAMESPACE file. Those files have different syntax than normal R scripts.

If you want to load a specific function from an R package (rather than all functions from a package), you can use libraryname::functionname instad of functionname in your code. In your case, replace as.data.frame with GenomicRanges::as.data.frame

If this does not work (for example because you don't have as.data.frame anywhere in your code), you can also load the whole GenomicRanges library with library(GenomicRanges)

ContentLicense: CC BY-SA 3.0

Body:
I tried to run the code in Chapter 7 Data mining with R learning with case study book but I got an error in following line:

rankWorkflows(svm, maxs = TRUE)

The error was:

Error in as.character.default(X[[i]], ...) :    no method for coercing
  this S4 class to a vector

Then I searched on the internet and found following solution:

importMethodsFrom(GenomicRanges, as.data.frame)

and again again I got a new error:

Error: could not find function "importMethodFrom"

I searched a lot but I got nothing :(


问:
Route::currentRouteAction not working in laravel 5.4
I am trying to create a middleware that checks the method action for the current route.

My middleware is as follows:

```<code><?php

namespace App\Http\Middleware;

use Closure;
use Route;

class PermissionMiddleware
{
/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @return mixed
 */
public function handle($request, Closure $next)
{
    $currentAction = Route::currentRouteAction();

    list($nothing,$route_action) = explode('App\Http\Controllers\\', $currentAction);

    $user_methods=session('userdata')['route_actions'];

    if((empty($user_methods))||!$user_methods->contains($route_action))
    {
        return redirect('denied');
    }
    return $next($request);

 }
}
</code>```

But when I go to the route, it throws up an error as shown below

indicating

Undefined offset: 1
  in PermissionMiddleware.php (line 21)

I cant figure out how to resolve the error.

I would need a guide to figure this out

Thank you

答:
Actually, your problem is not Route::currentRouteAction() but after the following line:

```<code>list($nothing, $route_action) = explode('App\Http\Controllers\\', $currentAction);
</code>```

It's not very obvious where it's happening but you should check the the following line:

```<code>$user_methods = session('userdata')['route_actions'];
</code>```

Make sure that, session('userdata') returns the expected result for example:

```<code>if ($userData = session('userdata')) {

    if (isset($userData['route_actions'])) {

        $user_methods = $userData['route_actions'];
        // ...
    }
}
</code>```

Also, you can use $request->route()->getActionName() to get the same result instead of using Route::currentRouteAction(). There are other useful methods available to get information about the route action for example:

```<code>$request->route()->getActionMethod(); // get the method name

$request->route()->getAction(); // get an array containing many information
</code>```

Body:
I am trying to create a middleware that checks the method action for the current route.

My middleware is as follows:

<?php

namespace App\Http\Middleware;

use Closure;
use Route;

class PermissionMiddleware
{
/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @return mixed
 */
public function handle($request, Closure $next)
{
    $currentAction = Route::currentRouteAction();

    list($nothing,$route_action) = explode('App\Http\Controllers\\', $currentAction);

    $user_methods=session('userdata')['route_actions'];

    if((empty($user_methods))||!$user_methods->contains($route_action))
    {
        return redirect('denied');
    }
    return $next($request);

 }
}

But when I go to the route, it throws up an error as shown below

indicating

Undefined offset: 1
  in PermissionMiddleware.php (line 21)

I cant figure out how to resolve the error.

I would need a guide to figure this out

Thank you

Body:
Actually, your problem is not Route::currentRouteAction() but after the following line:

list($nothing, $route_action) = explode('App\Http\Controllers\\', $currentAction);

It's not very obvious where it's happening but you should check the the following line:

$user_methods = session('userdata')['route_actions'];

Make sure that, session('userdata') returns the expected result for example:

if ($userData = session('userdata')) {

    if (isset($userData['route_actions'])) {

        $user_methods = $userData['route_actions'];
        // ...
    }
}

Also, you can use $request->route()->getActionName() to get the same result instead of using Route::currentRouteAction(). There are other useful methods available to get information about the route action for example:

$request->route()->getActionMethod(); // get the method name

$request->route()->getAction(); // get an array containing many information


问:
Print document text invisible
I am trying to build recipe application. Here is a sample

I am using text boxes to fill all fields and after I fill all fields I print them with this code

```<code>private void button1_Click(object sender, EventArgs e)
{
    PrintDialog pd = new PrintDialog();
    PrintDocument doc = new PrintDocument();
    doc.PrintPage += PrintPage;
    pd.Document = doc;
    if (pd.ShowDialog() == DialogResult.OK)
        doc.Print();
}

private void PrintPage(object sender, PrintPageEventArgs e)
{
    Font myfont = new Font("Arial", 12);
    e.Graphics.DrawImage(pictureBox1.BackgroundImage, 0, 0);
    e.Graphics.DrawString(textBox1.Text, myfont, Brushes.Black, 157, 164);
    e.Graphics.DrawImage(pictureBox1.Image, 0, 0);
    e.Graphics.Dispose();
}
</code>```

My problem is after I save file as PDF when I'm open it I can only see the text for like 1 second and then it disappear and if i double click in the spot where text should be I can copy the text from there...

I've been thinking maybe it's something about text transparency or picture box transparency changed few properties there and there but still no success.

答:
After calling the DrawString method there is another call to DrawImage.
I think that the image is being drawn on top of your textbox.

Try calling DrawString after both of the DrawImage calls.

Title: Print document text invisible

Body:
I am trying to build recipe application. Here is a sample

I am using text boxes to fill all fields and after I fill all fields I print them with this code

private void button1_Click(object sender, EventArgs e)
{
    PrintDialog pd = new PrintDialog();
    PrintDocument doc = new PrintDocument();
    doc.PrintPage += PrintPage;
    pd.Document = doc;
    if (pd.ShowDialog() == DialogResult.OK)
        doc.Print();
}

private void PrintPage(object sender, PrintPageEventArgs e)
{
    Font myfont = new Font("Arial", 12);
    e.Graphics.DrawImage(pictureBox1.BackgroundImage, 0, 0);
    e.Graphics.DrawString(textBox1.Text, myfont, Brushes.Black, 157, 164);
    e.Graphics.DrawImage(pictureBox1.Image, 0, 0);
    e.Graphics.Dispose();
}

My problem is after I save file as PDF when I'm open it I can only see the text for like 1 second and then it disappear and if i double click in the spot where text should be I can copy the text from there...

I've been thinking maybe it's something about text transparency or picture box transparency changed few properties there and there but still no success.


问:
Strongly typed partial view navigation
Basically, I started working on this app knowing nothing about web development which is severely inhibiting my search-fu.  Probably should read a book, but that's not likely.  Using ASP.NET MVC3 RC2, I'm trying to make a strongly typed partial view which can navigate to related items, as well as maintaining a bread crumb trail (which I thought would be a List in the ViewBag?).  A good analogy would be a dictionary page with a thesaurus sub-view.

```<code>class Entry
{
   string Name;
   string Definition;
   IEnumerable<Entry> Synonyms;
}
</code>```

Primarily the page shows the word and its definition, etc.  But there's a div with synonyms that you can click to see the selected word's synonyms, replaced w/ ajax.

I was initially thinking I needed to do an html helper, but then I saw stuff about returning PartialView from my controller which seems a lot better.

I'm having trouble piecing together all the pieces of the puzzle.  A sample or outline would be great.

Thanks!

答:
Man, I knew I should have worked on it a little longer before asking.

So, here's the recipe:

Make a function in the controller, Synonym(id) { return PartialView(GetEntry(id)); }

Make a partial view, Synonym.cshtml, strongly typed to Entry.

Display the partial view in your main display with
@{Html.RenderAction("Synonym", @Model.Id);}

For the ajax navigation link inside Synonym.cshtml, use something like this

```<code>@foreach(Entry syn in @Model.Synonyms)
    @Ajax.ActionLink((string)@syn.Name, "Synonym",
        new { id = @syn.Id }, new AjaxOptions { UpdateTargetId = "Synonyms" })
</code>```

One thing that briefly tripped me up was the new { id = @syn.Id } because the parameter name in my controller was actually number, I had to use new { number = ... }

Oh, and I asked about navigation.  I think the browser's back button will be sufficient for most navigation, but still wanted a "Back to Current Word" link.  For that I did the following:

Modified Controller.Synonym to take another parameter, int orig and set ViewBag.OrigId = orig; before returning.

Modified the ActionLinks to say new { id = @syn.Id, orig = @ViewBag.OrigId }

Created the back link inside Synonym.cshtml - @Ajax.ActionLink("Back To Current Word", "Synonym", new { id = @ViewBag.OrigId, orig = @ViewBag.OrigId }, new AjaxOptions { UpdateTargetId = "Synonyms" })

Modified the call to @Html.RenderAction to pass an object like in the ActionLinks new { id = @Model.Id, orig = @Model.Id }

If someone else comes up with a better answer that makes me want to rewrite my stuff, I'll accept theirs instead.  And I'd love feedback on whether I'm missing anything, like how I could avoid the second parameter to Controller.Synonym or other simplifications or improvements.

ContentLicense: CC BY-SA 2.5

Title: Strongly typed partial view navigation

Body:
Basically, I started working on this app knowing nothing about web development which is severely inhibiting my search-fu.  Probably should read a book, but that's not likely.  Using ASP.NET MVC3 RC2, I'm trying to make a strongly typed partial view which can navigate to related items, as well as maintaining a bread crumb trail (which I thought would be a List in the ViewBag?).  A good analogy would be a dictionary page with a thesaurus sub-view.

class Entry
{
   string Name;
   string Definition;
   IEnumerable<Entry> Synonyms;
}

Primarily the page shows the word and its definition, etc.  But there's a div with synonyms that you can click to see the selected word's synonyms, replaced w/ ajax.

I was initially thinking I needed to do an html helper, but then I saw stuff about returning PartialView from my controller which seems a lot better.

I'm having trouble piecing together all the pieces of the puzzle.  A sample or outline would be great.

Thanks!

Body:
Man, I knew I should have worked on it a little longer before asking.

So, here's the recipe:

Make a function in the controller, Synonym(id) { return PartialView(GetEntry(id)); }

Make a partial view, Synonym.cshtml, strongly typed to Entry.

Display the partial view in your main display with <div id="Synonyms">@{Html.RenderAction("Synonym", @Model.Id);}</div>

For the ajax navigation link inside Synonym.cshtml, use something like this

@foreach(Entry syn in @Model.Synonyms)
    @Ajax.ActionLink((string)@syn.Name, "Synonym",
        new { id = @syn.Id }, new AjaxOptions { UpdateTargetId = "Synonyms" })

One thing that briefly tripped me up was the new { id = @syn.Id } because the parameter name in my controller was actually number, I had to use new { number = ... }

Oh, and I asked about navigation.  I think the browser's back button will be sufficient for most navigation, but still wanted a "Back to Current Word" link.  For that I did the following:

Modified Controller.Synonym to take another parameter, int orig and set ViewBag.OrigId = orig; before returning.

Modified the ActionLinks to say new { id = @syn.Id, orig = @ViewBag.OrigId }

Created the back link inside Synonym.cshtml - @Ajax.ActionLink("Back To Current Word", "Synonym", new { id = @ViewBag.OrigId, orig = @ViewBag.OrigId }, new AjaxOptions { UpdateTargetId = "Synonyms" })

Modified the call to @Html.RenderAction to pass an object like in the ActionLinks new { id = @Model.Id, orig = @Model.Id }

If someone else comes up with a better answer that makes me want to rewrite my stuff, I'll accept theirs instead.  And I'd love feedback on whether I'm missing anything, like how I could avoid the second parameter to Controller.Synonym or other simplifications or improvements.


问:
How to use sha256 in php5.3.0
I'm using sha256 to encrypt the password. I can save the sha256 encrypted password in mysql. But i can't login with the same clause.

Insert code:

```<code><?php
error_reporting(E_ALL ^ E_NOTICE);
$username = $_POST['uusername'];
$passcode = $_POST['ppasscode'];
$userflag = $_POST['uuserflag'];
//$passcodeen = hash('sha256',$passcode);
$passcodeen = hash('sha256', (get_magic_quotes_gpc() ? stripslashes($ppasscode) : $ppasscode));
$conn = mysql_connect("localhost","charles","charles") or die("connection failed with DB:".mysql_error());
mysql_select_db("sessiondb");
$query = "INSERT INTO users(username,passcode,userflag) values('$username','$passcodeen','$userflag')";
</code>```

Select code:

```<code><?php
error_reporting(E_ALL ^ E_NOTICE);

    @mysql_connect("localhost","charles","charles") or die("Connection failed".mysql_error());
    @mysql_select_db("sessiondb") or die("Database doesn't exist".mysql_error());
    //get user input
    $username = $_POST['username'];
    $ppasscode = $_POST['ppasscode'];
    //$passcodeen = hash('sha256', $ppasscode);
    $passcodeen = hash('sha256', (get_magic_quotes_gpc() ? stripslashes($ppasscode) : $ppasscode));
    //get session value from mysql
    $query = @mysql_query("select username, userflag from users where username ='$username' and passcode = '$passcodeen'") or die("Query execution failed".mysql_error());
</code>```

Is there something wrong?  I'm very confused. Thanks.

答:
A way better solution is to just use the excelent compatibility script from Anthony Ferrara:

https://github.com/ircmaxell/password_compat

Please, and also, when checking the password, always add a way (preferibly async, so it doesn't impact the check process for timming attacks) to update the hash if needed.

Title: How to use sha256 in php5.3.0

Body:
I'm using sha256 to encrypt the password. I can save the sha256 encrypted password in mysql. But i can't login with the same clause.

Insert code:

<?php
error_reporting(E_ALL ^ E_NOTICE);
$username = $_POST['uusername'];
$passcode = $_POST['ppasscode'];
$userflag = $_POST['uuserflag'];
//$passcodeen = hash('sha256',$passcode);
$passcodeen = hash('sha256', (get_magic_quotes_gpc() ? stripslashes($ppasscode) : $ppasscode));
$conn = mysql_connect("localhost","charles","charles") or die("connection failed with DB:".mysql_error());
mysql_select_db("sessiondb");
$query = "INSERT INTO users(username,passcode,userflag) values('$username','$passcodeen','$userflag')";

Select code:

<?php
error_reporting(E_ALL ^ E_NOTICE);

    @mysql_connect("localhost","charles","charles") or die("Connection failed".mysql_error());
    @mysql_select_db("sessiondb") or die("Database doesn't exist".mysql_error());
    //get user input
    $username = $_POST['username'];
    $ppasscode = $_POST['ppasscode'];
    //$passcodeen = hash('sha256', $ppasscode);
    $passcodeen = hash('sha256', (get_magic_quotes_gpc() ? stripslashes($ppasscode) : $ppasscode));
    //get session value from mysql
    $query = @mysql_query("select username, userflag from users where username ='$username' and passcode = '$passcodeen'") or die("Query execution failed".mysql_error());

Is there something wrong?  I'm very confused. Thanks.


问:
Intel Galileo Azure REST call
i'm trying to make use of my Intel Galileo Gen2 by making calls to a microsoft web api (REST service) hosted in azure as an web app
but all i get is an azure 404 saying it won't find my app

the code on my arduino is the following

```<code>#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = { 0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 };
char serverName[] = "wack.azurewebsites.net";

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
   while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  // start the Ethernet connection:
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // no point in carrying on, so do nothing forevermore:
    while(true);
  }
  // give the Ethernet shield a second to initialize:
  delay(1000);
  Serial.println("connecting...");

  // if you get a connection, report back via serial:
  if (client.connect(serverName, 80)) {
    Serial.println("connected");
    // Make a HTTP request:
    client.println("GET /api/warning HTTP/1.0");
    client.println();
  }
  else {
    // if you didn't get a connection to the server:
    Serial.println("connection failed");
  }
}

void loop()
{
  // if there are incoming bytes available
  // from the server, read them and print them:
  if (client.available()) {
    char c = client.read();
    Serial.print(c);
  }

  // if the server's disconnected, stop the client:
  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();

    // do nothing forevermore:
    while(true);
  }
}
</code>```

i tried changing the target url several times

```<code> client.println("GET wack.azurewebsites.net/api/warning HTTP/1.0");
 client.println("GET api/warning HTTP/1.0");
 client.println("GET /api/warning ");
 client.println("GET /api/warning HTTP/1.1");
</code>```

none of them work, some don't even connect
however it only returns a 404 even though that URL is valid and tested throughout differnet applications even on the same network.

i have replaced the mac adress with the adress of the device and previously have confirmed that it can be reached in the network by making it a web server itself. Basically it can grab internet settings but for some reason will not connect to my rest service. Any kind of help is appreciated. Thx

答:
You're missing the Host header.

The Host header is mandated by HTTP/1.1 protocol specification, you MUST send it with every request.

You should also send User-Agent and Connection: close to be a good HTTP citizen. The latter tells the web server "Don't keep the socket open since I'll hang up right away". HTTP/1.1 defaults to Connection: keep-alive.

Amend your request to look like this:

client.println("GET /api/warning HTTP/1.1");
client.println("Host: wack.azurewebsites.net");
client.println("User-Agent: Intel Fakelileo");
client.println("Connection: close\r\n");
```

<p>A simple test:</p>

```$ telnet {sitename}.azurewebsites.net 80

Connected to waws-prod-am2-119.cloudapp.net.
Escape character is '^]'.
GET / HTTP/1.1
Host: {sitename}.azurewebsites.net
User-agent: Intel Fakelileo
Connection: close

HTTP/1.1 200 OK
Content-Length: 84
Content-Type: text/plain; charset=utf-8
Server: Microsoft-IIS/8.0
...
```

Title: Intel Galileo Azure REST call

Body:
i'm trying to make use of my Intel Galileo Gen2 by making calls to a microsoft web api (REST service) hosted in azure as an web app
but all i get is an azure 404 saying it won't find my app

the code on my arduino is the following

#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = { 0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 };
char serverName[] = "wack.azurewebsites.net";

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
   while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  // start the Ethernet connection:
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // no point in carrying on, so do nothing forevermore:
    while(true);
  }
  // give the Ethernet shield a second to initialize:
  delay(1000);
  Serial.println("connecting...");

  // if you get a connection, report back via serial:
  if (client.connect(serverName, 80)) {
    Serial.println("connected");
    // Make a HTTP request:
    client.println("GET /api/warning HTTP/1.0");
    client.println();
  }
  else {
    // if you didn't get a connection to the server:
    Serial.println("connection failed");
  }
}

void loop()
{
  // if there are incoming bytes available
  // from the server, read them and print them:
  if (client.available()) {
    char c = client.read();
    Serial.print(c);
  }

  // if the server's disconnected, stop the client:
  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();

    // do nothing forevermore:
    while(true);
  }
}

i tried changing the target url several times

 client.println("GET wack.azurewebsites.net/api/warning HTTP/1.0");
 client.println("GET api/warning HTTP/1.0");
 client.println("GET /api/warning ");
 client.println("GET /api/warning HTTP/1.1");

none of them work, some don't even connect
however it only returns a 404 even though that URL is valid and tested throughout differnet applications even on the same network.

i have replaced the mac adress with the adress of the device and previously have confirmed that it can be reached in the network by making it a web server itself. Basically it can grab internet settings but for some reason will not connect to my rest service. Any kind of help is appreciated. Thx

Body:
You're missing the Host header.

The Host header is mandated by HTTP/1.1 protocol specification, you MUST send it with every request.

You should also send User-Agent and Connection: close to be a good HTTP citizen. The latter tells the web server "Don't keep the socket open since I'll hang up right away". HTTP/1.1 defaults to Connection: keep-alive.

Amend your request to look like this:

client.println("GET /api/warning HTTP/1.1");
client.println("Host: wack.azurewebsites.net");
client.println("User-Agent: Intel Fakelileo");
client.println("Connection: close\r\n");

A simple test:

$ telnet {sitename}.azurewebsites.net 80

Connected to waws-prod-am2-119.cloudapp.net.
Escape character is '^]'.
GET / HTTP/1.1
Host: {sitename}.azurewebsites.net
User-agent: Intel Fakelileo
Connection: close

HTTP/1.1 200 OK
Content-Length: 84
Content-Type: text/plain; charset=utf-8
Server: Microsoft-IIS/8.0
...


问:
WAMP: Missing http://localhost/ in urls , wrong wamp projects links
I have a problem with Wamp which never happened to me before, cannot find what's wrong. I have a few projects located in my www folder ( running windows 7 ).

My hostfile has the line 127.0.0.1 localhost uncommented

When I go to http://localhost/ or http://127.0.0.1/ and click on a project name like "mysite" from the main Wamp panel page, the link just points to "mysite" and not "http://localhost/mysite"

Therefore I can't see any sites, what should I do ?

答:
In the latest version

CHANGE THIS

```<code>$suppress_localhost = ($wampConf['urlAddLocalhost'] == 'off' ? true : false);
</code>```

TO THIS

```<code>$suppress_localhost = ($wampConf['urlAddLocalhost'] == 'off' ? false : false);
</code>```

Body:
In the latest version

CHANGE THIS

$suppress_localhost = ($wampConf['urlAddLocalhost'] == 'off' ? true : false);

TO THIS

$suppress_localhost = ($wampConf['urlAddLocalhost'] == 'off' ? false : false);


问:
Unity3D Position and Rotation matching on Waypoints
I have a simple waypoint system. It uses a transform of arrays that act as the bucket what holds the waypoint values.

I use this waypoint system to move a camera throughout a scene by moving towards one point to another.  The scene is not big - so everything is close to each other.

The camera moves from one position to another by button click/press.  This works fine.

```<code>void Start()
{
    //Sets the Camera to the first point
    Camera = GameObject.Find("Main Camera");
    Camera.transform.position = patrolPoints[0].position
    currentPoint = 0;
}

//Fixed Update seems to work better for LookAt
void FixedUpdate()
{
    //Looks at initial Target
    Camera.transform.LookAt(TargetPoints[0]);

    if (click == true)
    {
        Camera.transform.position = Vector3.MoveTowards(Camera.transform.position, patrolPoints[currentPoint].position, moveSpeed * Time.deltaTime);
        //Camera.transform.rotation = Quaternion.Slerp(Camera.transform.rotation, patrolPoints[currentPoint].transform.rotation,  Time.deltaTime);
        Camera.transform.LookAt(TargetPoints[currentPoint]);
    }

}

public void onNextClick()
{
    if (currentPoint >= patrolPoints.Length)
    {
        currentPoint = 0;
    }
    if (Camera.transform.position == patrolPoints[currentPoint].position)
    {
        currentPoint++;
        click = true;
    }

}
</code>```

I am having difficulty with one aspect of the transform that I haven't talked about yet.  That is the rotation.

I have used lookAt for setting up the target of the first look at point and that works. However when it runs to the next target in the look at array - the change is sudden.

I have tried an Slerp in the shot as well - and this works when the waypoint has been placed in the appropriate rotation value - and the value Slerps from one position to the next. However, the timing isn't quite aligning up yet.  Some position transitions get there quicker - meaning the rotation is trying to get caught up / while others are lagging behind.

I have tried getting the distance between the current waypoint and the next waypoint and treating that as an overall percentage in the update relative to the current position of the camera - I believe this could help work out how far the rotation should be orientated given the position update.

However, I am somewhat lost on it.  Many examples suggest looking at iTween - and I wouldn't imagine this would work - however, I want to get into the math a bit.

Can anyone put me in the right direction?

答:
Looks like the Lerp for Position and a Slerp for Rotation done the trick.
MoveTowards wasn't playing ball with a Slerp on rotation - so I believe the timings weren't aligning.

```<code>   if (click == true)
    {
        Camera.transform.position = Vector3.MoveTowards(Camera.transform.position, patrolPoints[currentPoint].position, moveSpeed * Time.deltaTime);
        Camera.transform.rotation = Quaternion.Lerp(Camera.transform.rotation, patrolPoints[currentPoint].rotation, moveSpeed * Time.deltaTime);
</code>```

I've been led to believe the lerp values work like a percentage of such - so the same input value works for it.

Finally I used a range on the distance between current position and update on the click - this helped speed up the button click.

```<code> if (Vector3.Distance(Camera.transform.position, patrolPoints[currentPoint].position) < PositionThreshold)
    {
        currentPoint++;
        click = true;
    }
</code>```

Thank you for your time.

Body:
I have a simple waypoint system. It uses a transform of arrays that act as the bucket what holds the waypoint values.

I use this waypoint system to move a camera throughout a scene by moving towards one point to another.  The scene is not big - so everything is close to each other.

The camera moves from one position to another by button click/press.  This works fine.

void Start()
{
    //Sets the Camera to the first point
    Camera = GameObject.Find("Main Camera");
    Camera.transform.position = patrolPoints[0].position
    currentPoint = 0;
}

//Fixed Update seems to work better for LookAt
void FixedUpdate()
{
    //Looks at initial Target
    Camera.transform.LookAt(TargetPoints[0]);

    if (click == true)
    {
        Camera.transform.position = Vector3.MoveTowards(Camera.transform.position, patrolPoints[currentPoint].position, moveSpeed * Time.deltaTime);
        //Camera.transform.rotation = Quaternion.Slerp(Camera.transform.rotation, patrolPoints[currentPoint].transform.rotation,  Time.deltaTime);
        Camera.transform.LookAt(TargetPoints[currentPoint]);
    }

}

public void onNextClick()
{
    if (currentPoint >= patrolPoints.Length)
    {
        currentPoint = 0;
    }
    if (Camera.transform.position == patrolPoints[currentPoint].position)
    {
        currentPoint++;
        click = true;
    }

}

I am having difficulty with one aspect of the transform that I haven't talked about yet.  That is the rotation.

I have used lookAt for setting up the target of the first look at point and that works. However when it runs to the next target in the look at array - the change is sudden.

I have tried an Slerp in the shot as well - and this works when the waypoint has been placed in the appropriate rotation value - and the value Slerps from one position to the next. However, the timing isn't quite aligning up yet.  Some position transitions get there quicker - meaning the rotation is trying to get caught up / while others are lagging behind.

I have tried getting the distance between the current waypoint and the next waypoint and treating that as an overall percentage in the update relative to the current position of the camera - I believe this could help work out how far the rotation should be orientated given the position update.

However, I am somewhat lost on it.  Many examples suggest looking at iTween - and I wouldn't imagine this would work - however, I want to get into the math a bit.

Can anyone put me in the right direction?

Body:
Looks like the Lerp for Position and a Slerp for Rotation done the trick.
MoveTowards wasn't playing ball with a Slerp on rotation - so I believe the timings weren't aligning.

   if (click == true)
    {
        Camera.transform.position = Vector3.MoveTowards(Camera.transform.position, patrolPoints[currentPoint].position, moveSpeed * Time.deltaTime);
        Camera.transform.rotation = Quaternion.Lerp(Camera.transform.rotation, patrolPoints[currentPoint].rotation, moveSpeed * Time.deltaTime);

I've been led to believe the lerp values work like a percentage of such - so the same input value works for it.

Finally I used a range on the distance between current position and update on the click - this helped speed up the button click.

 if (Vector3.Distance(Camera.transform.position, patrolPoints[currentPoint].position) < PositionThreshold)
    {
        currentPoint++;
        click = true;
    }

Thank you for your time.


问:
Linking to a file in the Zend Framework
When I link directly to an uploaded file in a Zend Framework based project I get differing results depending on if I'm working in my local environment or my remote environment.

In both cases I want to link to an uploaded photo. The generated URL looks like:

http://whateverserverweareon/projectfiles/project18/photos/aphoto.jpg

On my local machine clicking that link will show me the photo, in my remote machine it gives me a warning about "invalid controller..." (as, while I do not have a "projectfiles" controller, the uploaded photos are in the projectfiles directory on the path specified in that sample url).

So how do I link to these uploaded photos? Create a controller just so I can link to them? Can I bypass the controller altogether and link directly? Is there some sort of custom route I need to create? Should I be doing this in a completely different manner? Any suggestions?

答:
ischenkodv is right.
And also, it's a better practice to put your file somewhere out of index.php's directory tree. Perhaps another subdomain.</p>

Title: Linking to a file in the Zend Framework


问:
Array Conversion To List Error
could someone explain to me what happens in the next lines of code and why it works?

```<code>Integer[] myray = {1,2,3,4,5};
List<Integer> l = new ArrayList<Integer>(Arrays.asList(myray));
l.add(6);
System.out.println(l);
</code>```

The code above works fine. It converts an array to a list and then adds another element.
But the following code dose  not work

```<code>Integer[] myray = {1,2,3,4,5};
List<Integer> l = (Arrays.asList(myray));
l.add(6);
System.out.println(l);
</code>```

The above code gives me the following error:
Exception in thread "main" java.lang.UnsupportedOperationException
Can someone please tell me the difference between the two conversions and why only the first one works??
Thanks in advance

答:
Because asList method from Arrays class gives you back a Immutable list where you cannot modify that. It is just  readable.

here are the docs for the same

Returns a fixed-size list backed by the specified array.

Where as in the first case you are not using it directly and you creating a new list around it.

```<code>new ArrayList<Integer>(Arrays.asList(myray));
</code>```

When you do that internally the elements only gets copy and you get a regular instance of ArrayList.

Title: Array Conversion To List Error

Body:
could someone explain to me what happens in the next lines of code and why it works?

Integer[] myray = {1,2,3,4,5};
List<Integer> l = new ArrayList<Integer>(Arrays.asList(myray));
l.add(6);
System.out.println(l);

The code above works fine. It converts an array to a list and then adds another element.
But the following code dose  not work

Integer[] myray = {1,2,3,4,5};
List<Integer> l = (Arrays.asList(myray));
l.add(6);
System.out.println(l);

The above code gives me the following error:
Exception in thread "main" java.lang.UnsupportedOperationException
Can someone please tell me the difference between the two conversions and why only the first one works??
Thanks in advance

Body:
Because asList method from Arrays class gives you back a Immutable list where you cannot modify that. It is just  readable.

here are the docs for the same

Returns a fixed-size list backed by the specified array.

Where as in the first case you are not using it directly and you creating a new list around it.

new ArrayList<Integer>(Arrays.asList(myray));

When you do that internally the elements only gets copy and you get a regular instance of ArrayList.


问:
How to turn off a spinner directive in angularjs for a specific $http requests
This directive will simply turn it on/off for a loading icon automatically. when $http requests occurs

My code

```<code>angular.module('directive.loading', [])
        .directive('loading',   ['$http' ,function ($http)
        {
            return {
                restrict: 'A',
                link: function (scope, elm, attrs)
                {
                    scope.isLoading = function () {
                        return $http.pendingRequests.length > 0;
                    };

                    scope.$watch(scope.isLoading, function (v)
                    {
                        if(v){
                            elm.show();
                        }else{
                            elm.hide();
                        }
                    });
                }
            };

        }]);
</code>```

My html code

```<code><div class="loading-spiner-holder" data-loading ><div class="loading-spiner"><img src="..." /></div></div>
</code>```

My scenario was how to turn off for a specific request in a page .

答:
You could add a condition and then change it via the rootscope. Before your ajax request, you simply call $rootScope.$emit('stopLoader');

```<code>angular.module('directive.loading', [])
    .directive('loading',   ['$http', '$rootScope',function ($http, $rootScope)
    {
        return {
            restrict: 'A',
            link: function (scope, elm, attrs)
            {
                scope.isNoLoadingForced = false;
                scope.isLoading = function () {
                    return $http.pendingRequests.length > 0 && scope.isNoLoadingForced;
                };

                $rootScope.$on('stopLoader', function(){
                    scope.isNoLoadingForced = true;
                })

                scope.$watch(scope.isLoading, function (v)
                {
                    if(v){
                        elm.show();
                    }else{
                        elm.hide();
                    }
                });
            }
        };

    }]);
</code>```

This is definatly not the best solution but it would still works.

Body:
This directive will simply turn it on/off for a loading icon automatically. when $http requests occurs

My code

angular.module('directive.loading', [])
        .directive('loading',   ['$http' ,function ($http)
        {
            return {
                restrict: 'A',
                link: function (scope, elm, attrs)
                {
                    scope.isLoading = function () {
                        return $http.pendingRequests.length > 0;
                    };

                    scope.$watch(scope.isLoading, function (v)
                    {
                        if(v){
                            elm.show();
                        }else{
                            elm.hide();
                        }
                    });
                }
            };

        }]);

My html code

My scenario was how to turn off for a specific request in a page .

Body:
You could add a condition and then change it via the rootscope. Before your ajax request, you simply call $rootScope.$emit('stopLoader');

angular.module('directive.loading', [])
    .directive('loading',   ['$http', '$rootScope',function ($http, $rootScope)
    {
        return {
            restrict: 'A',
            link: function (scope, elm, attrs)
            {
                scope.isNoLoadingForced = false;
                scope.isLoading = function () {
                    return $http.pendingRequests.length > 0 && scope.isNoLoadingForced;
                };

                $rootScope.$on('stopLoader', function(){
                    scope.isNoLoadingForced = true;
                })

                scope.$watch(scope.isLoading, function (v)
                {
                    if(v){
                        elm.show();
                    }else{
                        elm.hide();
                    }
                });
            }
        };

    }]);

This is definatly not the best solution but it would still works.


问:
implement toString for enum typeScript
I would like to know if it is possible to redefine toString() for an enum.

Here is my enum:

enum Person{
  FOO = 10,
  FAA = 1,
  FII = 2
}
```

I want to redefine toString so that when Person.FOO.toString() is called, that return "FOO". Is that possible?

答: No it is not possible. Enum is not type which could be extended in JavaScript/TypeScript. I recommend you to write simple method/function which will expect Person as parameter and do what you need.</p>

Title: implement toString for enum typeScript

Body:
I would like to know if it is possible to redefine toString() for an enum.

Here is my enum:

enum Person{
  FOO = 10,
  FAA = 1,
  FII = 2
}

I want to redefine toString so that when Person.FOO.toString() is called, that return "FOO". Is that possible?


问:
Angularjs second dropdown depend on first
Please i have a question. how could i create a second dropdown depend on select item from first dropdown.

```<code><div ng-app="myapp">
<fieldset ng-controller="FirstCtrl">
    <select
        ng-options="p.id for p in jobs"
        ng-model="selectedPerson"></select>
    {{ selectedPerson }}
</fieldset>
</code>```

答:
You can only select one select option at a time. other wise you can use multiple in your select box

```<code><div ng-app="myapp">
    <fieldset ng-controller="FirstCtrl">
        <select multiple
            ng-options="p.id for p in jobs"
            ng-model="selectedPerson" ng-change="addItems()"></select>

        <select
            ng-options="p.id for p in selectedPerson"
            ng-model="selecteditems" ng-change="addItems()"></select>
    </fieldset>
</div>
</code>```

Demo

Body:
Please i have a question. how could i create a second dropdown depend on select item from first dropdown.

<fieldset ng-controller="FirstCtrl">
    <select
        ng-options="p.id for p in jobs"
        ng-model="selectedPerson"></select>
    {{ selectedPerson }}
</fieldset>

Body:
You can only select one select option at a time. other wise you can use multiple in your select box

<div ng-app="myapp">
    <fieldset ng-controller="FirstCtrl">
        <select multiple
            ng-options="p.id for p in jobs"
            ng-model="selectedPerson" ng-change="addItems()"></select>

        <select
            ng-options="p.id for p in selectedPerson"
            ng-model="selecteditems" ng-change="addItems()"></select>
    </fieldset>
</div>

Demo


问:
If I delete an image in my application it has to be deleted in the gallery too (using objective C)
I have developed a camera application with all basic functionalities. When you take a picture that image will be saved in the newly created folder but if I delete an image in my application its not getting deleted in that folder. I need to delete it permanently using objective C</p>

答:
FOR iOS 8.0+

You can only delete the ALAsset which is created by your app with document API [ALAsset setImageData:metadata:completionBlock:]

Saving Image photo.jpg to gallery by,

```<code>ALAssetsLibrary *lib = [ALAssetsLibrary new];
UIImage *image = [UIImage imageNamed:@"photo.jpg"];
[lib writeImageToSavedPhotosAlbum:image.CGImage metadata:@{} completionBlock:^(NSURL *assetURL, NSError *error) {
    NSLog(@"Write image %@ to asset library. (Error %@)", assetURL, error);
}];
</code>```

You can Find this in "Saved Photos" album.
To delete:

```<code>ALAssetsLibrary *lib = [ALAssetsLibrary new];
[lib enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
    [group enumerateAssetsUsingBlock:^(ALAsset *asset, NSUInteger index, BOOL *stop) {
        if(asset.isEditable) {
            [asset setImageData:nil metadata:nil completionBlock:^(NSURL *assetURL, NSError *error) {
                NSLog(@"Asset url %@ should be deleted. (Error %@)", assetURL, error);
            }];
        }
    }];
} failureBlock:^(NSError *error) {

}];
</code>```

ALAssetLibrary is Deprecated since iOS 9.0, you can use
  PHPhotoLibrary Instead.

iOS 9.0+

```<code>// Delete asset from library
      [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        [PHAssetChangeRequest deleteAssets:assetArray];

    } completionHandler:completionHandler];
</code>```

Body:
FOR iOS 8.0+

You can only delete the ALAsset which is created by your app with document API [ALAsset setImageData:metadata:completionBlock:]

Saving Image photo.jpg to gallery by,

ALAssetsLibrary *lib = [ALAssetsLibrary new];
UIImage *image = [UIImage imageNamed:@"photo.jpg"];
[lib writeImageToSavedPhotosAlbum:image.CGImage metadata:@{} completionBlock:^(NSURL *assetURL, NSError *error) {
    NSLog(@"Write image %@ to asset library. (Error %@)", assetURL, error);
}];

You can Find this in "Saved Photos" album.
To delete:

ALAssetsLibrary *lib = [ALAssetsLibrary new];
[lib enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
    [group enumerateAssetsUsingBlock:^(ALAsset *asset, NSUInteger index, BOOL *stop) {
        if(asset.isEditable) {
            [asset setImageData:nil metadata:nil completionBlock:^(NSURL *assetURL, NSError *error) {
                NSLog(@"Asset url %@ should be deleted. (Error %@)", assetURL, error);
            }];
        }
    }];
} failureBlock:^(NSError *error) {

}];

ALAssetLibrary is Deprecated since iOS 9.0, you can use
  PHPhotoLibrary Instead.

iOS 9.0+

// Delete asset from library
      [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        [PHAssetChangeRequest deleteAssets:assetArray];

    } completionHandler:completionHandler];


问:
Download a file in django with a button using xmlhttprequest
I looked at many same questions but none resolved my problem,
I'm trying to download a file generated in my view using a button.
Problem : I get an empty file while clicking on download button

My view:

```<code>class dumpView(View):

template_name = 'download.html'
def get(self, request):
    file = open("/home/test.pdf", "rwbt")
    response = HttpResponse(file.read(), content_type="application/pdf")
    response['Content-Disposition'] = 'attachement; filename=%s' % file
    return render(request, 'download.html')
</code>```

My url:

```<code>url(r'^dump/', dumpView.as_view()),
</code>```

My template:

```<code> {% extends 'base.html' %}
 {% load staticfiles %}
 {% block content %}
 <div class="container">
 <div class="row">
    <div class="jumbotron">
        <div class="row">
            <center>
                <a href="javascript:void(0)" class="btn btn-primary btn-lg dump">Download</a>
            </center>
        </div>
    </div>
</div>
</div>
{% endblock %}
{% block javascript %}
<script src="{% static 'js/home.js' %}"></script>
{% endblock %}
</code>```

My Django view is rendering the response. I did add an on click handler to the button with class dump in the UI to make a XHR request to the “/dump” URL  and recieve response as a blob and download the file with custom name and date.

My js :

```<code>$(".dump").on("click", function() {
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    var a, today;
    if (xhttp.readyState === 4 && xhttp.status === 200) {
        a = document.createElement('a');
        a.href = window.URL.createObjectURL(xhttp.response);
        today = new Date();
        a.download = "file_" + today.toDateString().split(" ").join("_") + ".pdf";
        a.style.display = 'none';
        document.body.appendChild(a);
        return a.click();
    }
};
xhttp.open("GET", "/dump", true);
xhttp.setRequestHeader("Content-Type", "application/json");
xhttp.responseType = 'blob';
xhttp.send();
});
</code>```

答:
In your view, you set Content-Disposition as attachment; filename=... but you append the file object. My guess is the browser might want a filename, preferably with the right extension.

I have a similar view in a Django project, and I'm quoting the filename as well, but I'm not sure if that is necessary

EDIT: also, there is a typo in "attachment", remove the extra "e" and see if that helps

Body:
I looked at many same questions but none resolved my problem,
I'm trying to download a file generated in my view using a button.
Problem : I get an empty file while clicking on download button

My view:

class dumpView(View):

template_name = 'download.html'
def get(self, request):
    file = open("/home/test.pdf", "rwbt")
    response = HttpResponse(file.read(), content_type="application/pdf")
    response['Content-Disposition'] = 'attachement; filename=%s' % file
    return render(request, 'download.html')

My url:

url(r'^dump/', dumpView.as_view()),

My template:

 {% extends 'base.html' %}
 {% load staticfiles %}
 {% block content %}

                Download

{% endblock %}
{% block javascript %}

{% endblock %}

My Django view is rendering the response. I did add an on click handler to the button with class dump in the UI to make a XHR request to the “/dump” URL  and recieve response as a blob and download the file with custom name and date.

My js :

$(".dump").on("click", function() {
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    var a, today;
    if (xhttp.readyState === 4 && xhttp.status === 200) {
        a = document.createElement('a');
        a.href = window.URL.createObjectURL(xhttp.response);
        today = new Date();
        a.download = "file_" + today.toDateString().split(" ").join("_") + ".pdf";
        a.style.display = 'none';
        document.body.appendChild(a);
        return a.click();
    }
};
xhttp.open("GET", "/dump", true);
xhttp.setRequestHeader("Content-Type", "application/json");
xhttp.responseType = 'blob';
xhttp.send();
});


问:
java gregoriancalendar off by an hour
I did:

```<code>GregorianCalendar gc = new GregorianCalendar(Locale.French);
</code>```

And the hour is off by one hour. I get 14:17 instead of 15:17.
My first thought was DST, but I think gregoriancalendar takes that into account.

The time is set correctly on my pc.

答: The constructor you use is creating a Calendar with the default Timezone (javadoc), this might not be the timezone correct fpr the given locale. At leasst, thats how i read the javadoc. Try using a different constructor and pass your TZ in.</p>

Title: java gregoriancalendar off by an hour

Body:
I did:

GregorianCalendar gc = new GregorianCalendar(Locale.French);

And the hour is off by one hour. I get 14:17 instead of 15:17.
My first thought was DST, but I think gregoriancalendar takes that into account.

The time is set correctly on my pc.


问:
Azure. URL Rewrite. Authentication mode forms.
This is the final episode (I hope) of the long story named "How I usually handle iis related stuff"

Previous episodes:
Ep1.
Ep2.

So.

I've set up URL rewrite to handle the all main websites api requests with the reverse proxy and pass them to the new api behind the scene.

All works great except the case when the api (the new web app) returns status 401 (Because of the wrong token etc.).

The user should see the 401 Unauthorized but it tries to redirect him instead to the "/login?returnUrl=some/api/url/which/returns/401/status".

As I understand It happened because of the fact that I have such authentication setup in web.config of the main website.

```<code><authentication mode="Forms">
      <forms loginUrl="~/login" timeout="100000" requireSSL="false" />
</authentication>
</code>```

So the request workflow looks like this:

User requests mainapp.com/api/some/endpoint.

IIS handles it with URL rewrite and redirects to the apiapp.com/api/some/endpoint

apiapp.com handles it and returns 401 status

mainapp.com handles 401 status and returns 302 status with /login?returnUrl=api/some/endpoint

Why the p.4 happend? I just need to pass the response and make mainapp.com do not think of it at all.

Is it possible to solve it somehow?

答:
So according to your setup this is the request flow:

client ----> mainapp.com ----> apiapp.com

According to your details Mainapp.com is setup as a reverse proxy. However, point 4 suggests otherwise. In order to be sure, can you enable Failed Request Tracing on both the web apps and review the logs.

This is a 2 step process,

Enable Failed Request tracing in the portal

Add the following section to the web.config of your web app (Root):

This will help you understand what happened to the request.

Body:
This is the final episode (I hope) of the long story named "How I usually handle iis related stuff"

Previous episodes:
Ep1.
Ep2.

So.

I've set up URL rewrite to handle the all main websites api requests with the reverse proxy and pass them to the new api behind the scene.

All works great except the case when the api (the new web app) returns status 401 (Because of the wrong token etc.).

The user should see the 401 Unauthorized but it tries to redirect him instead to the "/login?returnUrl=some/api/url/which/returns/401/status".

As I understand It happened because of the fact that I have such authentication setup in web.config of the main website.

<authentication mode="Forms">
      <forms loginUrl="~/login" timeout="100000" requireSSL="false" />
</authentication>

So the request workflow looks like this:

User requests mainapp.com/api/some/endpoint.

IIS handles it with URL rewrite and redirects to the apiapp.com/api/some/endpoint

apiapp.com handles it and returns 401 status

mainapp.com handles 401 status and returns 302 status with /login?returnUrl=api/some/endpoint

Why the p.4 happend? I just need to pass the response and make mainapp.com do not think of it at all.

Is it possible to solve it somehow?


问:
Java, MalformedChunkCodingException
I have an Android Application that gives me this exception:

```<code>org.apache.http.MalformedChunkCodingException: CRLF expected at end of chunk
</code>```

The exception is thrown from this method:  (Purpose is to write out the response received from the server to a file.)

```<code>public static void getResponseBodyForServerData(
    final HttpEntity entity) throws IOException, ParseException {

    if (entity == null) {
        throw new IllegalArgumentException("HTTP entity may not be null");
    }
    InputStream instream = entity.getContent();

    if (instream == null) {
        return;
    }
    File file = new File(Environment.getExternalStorageDirectory() +
        "/foo/Response.txt");

    if (!file.exists()) {
        file.createNewFile();
    }
    OutputStream out = new FileOutputStream(file);
    byte buf[] = new byte[1024];
    int len;
    while ((len = instream.read(buf)) > 0)
        out.write(buf, 0, len);
    out.flush();
    out.close();
}
</code>```

So then I modified the above code to:

```<code>public static void getResponseBodyForServerData(
    final HttpEntity entity) throws IOException, ParseException {

    if (entity == null) {
        throw new IllegalArgumentException("HTTP entity may not be null");
    }
    InputStream instream = entity.getContent();
    InputStreamReader inputStreamReader = new InputStreamReader(
        instream, "UNICODE") ;

    if (instream == null) {
        return;
    }
    File file = new File(Environment.getExternalStorageDirectory() +
        "/foo/Response.txt");
    if (!file.exists()) {
        file.createNewFile();
    }

    BufferedReader bufferedReader = new BufferedReader(inputStreamReader) ;
    BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(
        new FileOutputStream(file),"UNICODE")) ;

    String singleLine = null ;

    while((singleLine = bufferedReader.readLine()) != null) {
        bufferedWriter.write(singleLine) ;
    }

    bufferedWriter.flush() ;
    bufferedWriter.close() ;
}
</code>```

And then the code works, What causes that error and what is wrong with the original code?

答:
I see that the question is rather old, nevertheless it showed up, when I searched for MalformedChunkCodingException. So here are some hints what's going on.

I can only guess what your problem was since you don't tell us in which line the exception occured and which version of org.apache.http.HttpEntity you use.

First MalformedChunkCodingException: CRLF expected at end of chunk really is the problem.
It occures when you have a chunked http transfer and at least one \r\n is missing in that transfer.

There are two possible errors. First the server does not send them or the client looses them.

To check if the server is ok check if the request response is ok. For example you can use curl to see the response in hex:

```<code>curl -ivs --raw http://host:port/somePath/toResource --trace /dev/stdout
</code>```

Here is some sample output:

```<code>00a0: 30 31 22 7d 5d 0d 0a 30 0d 0a 0d 0a             01"}]..0....
</code>```

See the \r\n as 0d 0a in the output?
That means the server actually sends a correct message.

So you probably loose some bytes while reading the response.

I used a debugger and set a breakpoint for MalformedChunkCodingException (Java Exception Breakpoint in Eclipse). I looked in the stack where the incoming response was processed the first time and really there was only half of the response in the buffer.

A chunked message is a streaming message. So it may be that you close the socket before the InputStream has read the complete message.
This for example happened in the jersey apache connector.

They had this code:

```<code>return new FilterInputStream(inputStream) {
    @Override
    public void close() throws IOException {
        response.close();
        super.close();
    }
</code>```

which failed:

JulijanasJezov on 18 Oct 2016

This change does not work with the org.apache.httpcomponents:
  httpclient: 4.5.1+ when using chunked transfer encoding. This is
  because they have changed the way they close the connection.

In this case when response.close() is called the connection is closed
  and the input stream's buffer is cleared, then super.close() function
  is not able to close the ChunkedInputStream and results in
  org.apache.http.ConnectionClosedException: Premature end of chunk
  coded message body: closing chunk expected.

The reason of the exception occurring is that upon close of
  ChunkedInputStream, the close() function reads the remainder of the
  chunked message and it fails because the buffer of the stream has been
  cleared when the connection has been closed in response.close() call.
  Reference:
  https://hc.apache.org/httpclient-3.x/apidocs/org/apache/commons/httpclient/ChunkedInputStream.html#close()

The fix to this problem is putting super.close() line of code before
  the response.close(). This allows for the stream to be closed
  correctly before its buffer has been cleared.

So my problem was solved when I found out that in our project we used incompatible versions of jersey-apache-connector (old) and http-client (new) in our maven pom. (Depenency Hierachy said: httpclient:4.5.3 (managed from 4.5) (ommitted for conflict with 4.5.3))

Title: Java, MalformedChunkCodingException

Body:
I have an Android Application that gives me this exception:

org.apache.http.MalformedChunkCodingException: CRLF expected at end of chunk

The exception is thrown from this method:  (Purpose is to write out the response received from the server to a file.)

public static void getResponseBodyForServerData(
    final HttpEntity entity) throws IOException, ParseException {

    if (entity == null) {
        throw new IllegalArgumentException("HTTP entity may not be null");
    }
    InputStream instream = entity.getContent();

    if (instream == null) {
        return;
    }
    File file = new File(Environment.getExternalStorageDirectory() +
        "/foo/Response.txt");

    if (!file.exists()) {
        file.createNewFile();
    }
    OutputStream out = new FileOutputStream(file);
    byte buf[] = new byte[1024];
    int len;
    while ((len = instream.read(buf)) > 0)
        out.write(buf, 0, len);
    out.flush();
    out.close();
}

So then I modified the above code to:

public static void getResponseBodyForServerData(
    final HttpEntity entity) throws IOException, ParseException {

    if (entity == null) {
        throw new IllegalArgumentException("HTTP entity may not be null");
    }
    InputStream instream = entity.getContent();
    InputStreamReader inputStreamReader = new InputStreamReader(
        instream, "UNICODE") ;

    if (instream == null) {
        return;
    }
    File file = new File(Environment.getExternalStorageDirectory() +
        "/foo/Response.txt");
    if (!file.exists()) {
        file.createNewFile();
    }

    BufferedReader bufferedReader = new BufferedReader(inputStreamReader) ;
    BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(
        new FileOutputStream(file),"UNICODE")) ;

    String singleLine = null ;

    while((singleLine = bufferedReader.readLine()) != null) {
        bufferedWriter.write(singleLine) ;
    }

    bufferedWriter.flush() ;
    bufferedWriter.close() ;
}

And then the code works, What causes that error and what is wrong with the original code?

Body:
I see that the question is rather old, nevertheless it showed up, when I searched for MalformedChunkCodingException. So here are some hints what's going on.

I can only guess what your problem was since you don't tell us in which line the exception occured and which version of org.apache.http.HttpEntity you use.

First MalformedChunkCodingException: CRLF expected at end of chunk really is the problem.
It occures when you have a chunked http transfer and at least one \r\n is missing in that transfer.

There are two possible errors. First the server does not send them or the client looses them.

To check if the server is ok check if the request response is ok. For example you can use curl to see the response in hex:

curl -ivs --raw http://host:port/somePath/toResource --trace /dev/stdout

Here is some sample output:

00a0: 30 31 22 7d 5d 0d 0a 30 0d 0a 0d 0a             01"}]..0....

See the \r\n as 0d 0a in the output?
That means the server actually sends a correct message.

So you probably loose some bytes while reading the response.

I used a debugger and set a breakpoint for MalformedChunkCodingException (Java Exception Breakpoint in Eclipse). I looked in the stack where the incoming response was processed the first time and really there was only half of the response in the buffer.

A chunked message is a streaming message. So it may be that you close the socket before the InputStream has read the complete message.
This for example happened in the jersey apache connector.

They had this code:

return new FilterInputStream(inputStream) {
    @Override
    public void close() throws IOException {
        response.close();
        super.close();
    }

which failed:

JulijanasJezov on 18 Oct 2016

This change does not work with the org.apache.httpcomponents:
  httpclient: 4.5.1+ when using chunked transfer encoding. This is
  because they have changed the way they close the connection.

In this case when response.close() is called the connection is closed
  and the input stream's buffer is cleared, then super.close() function
  is not able to close the ChunkedInputStream and results in
  org.apache.http.ConnectionClosedException: Premature end of chunk
  coded message body: closing chunk expected.

The reason of the exception occurring is that upon close of
  ChunkedInputStream, the close() function reads the remainder of the
  chunked message and it fails because the buffer of the stream has been
  cleared when the connection has been closed in response.close() call.
  Reference:
  https://hc.apache.org/httpclient-3.x/apidocs/org/apache/commons/httpclient/ChunkedInputStream.html#close()

The fix to this problem is putting super.close() line of code before
  the response.close(). This allows for the stream to be closed
  correctly before its buffer has been cleared.

So my problem was solved when I found out that in our project we used incompatible versions of jersey-apache-connector (old) and http-client (new) in our maven pom. (Depenency Hierachy said: httpclient:4.5.3 (managed from 4.5) (ommitted for conflict with 4.5.3))


问:
Kubernetes Job: exactly one pod
I want to run only one pod of my kubernetes app at a time(relaunch in case of failure), I am using job controller.

But as per documentations, kubernetes may launch more than one pods and will eventually achieve specified replicas. Is there any way to achieve exactly one pod at a time or any recommended design pattern for such use cases.

My app is reading data from HDFS and writing it to a message queue. It exits after processing all the files. I want to minimize possibility of writing duplicate records.

答:
If I understand your question correctly I think you are looking for: .spec.strategy.rollingUpdate.maxSurge

If you set this to 0 then the existing pods will be killed before starting an new one.

Title: Kubernetes Job: exactly one pod


问:
AngularJS jQuery include old project
I have a very large project written with jQuery. Now I'm using AngularJS, but I need to load (possibly in a div tag) my old project. It seems to use ng-include, but my old project includes many scripts and some JS code generated by PHP. So using ng-include isn't helpful because the JS code inside this old-project.php doesn't work. Is there any way to open my old-project.php in a div in my AngularJS app?

答:
You have to follow four steps:

Step 1: Create simple html page. Ex: new.html .

Step 2: You need to create a .htaccess file in your root web directory and add this line to it:

```<code>AddType application/x-httpd-php .htm .html
</code>```

This will tell Apache to process files with a .htm or .html file extension as PHP files.

Step 3: in 'new.html' file include this within php tag :

```<code>include '<old-project>.php';
</code>```

Step 4: Now you can add 'new.html' file with <ng-include> .

Title: AngularJS jQuery include old project

Body:
You have to follow four steps:

Step 1: Create simple html page. Ex: new.html .

Step 2: You need to create a .htaccess file in your root web directory and add this line to it:

AddType application/x-httpd-php .htm .html

This will tell Apache to process files with a .htm or .html file extension as PHP files.

Step 3: in 'new.html' file include this within php tag :

include '<old-project>.php';

Step 4: Now you can add 'new.html' file with <ng-include> .


问:
Checking if process still running?
As a way to build a poor-man's watchdog and make sure an application is restarted in case it crashes (until I figure out why), I need to write a PHP CLI script that will be run by cron every 5mn to check whether the process is still running.

Based on this page, I tried the following code, but it always returns True even if I call it with bogus data:

```<code>function processExists($file = false) {
    $exists= false;
    $file= $file ? $file : __FILE__;

    // Check if file is in process list
    exec("ps -C $file -o pid=", $pids);
    if (count($pids) > 1) {
    $exists = true;
    }
    return $exists;
}

#if(processExists("lighttpd"))
if(processExists("dummy"))
    print("Exists\n")
else
    print("Doesn't exist\n");
</code>```

Next, I tried this code...

```<code>(exec("ps -A | grep -i 'lighttpd -D' | grep -v grep", $output);)
print $output;
</code>```

... but don't get what I expect:

```<code>/tmp> ./mycron.phpcli
Arrayroot:/tmp>
</code>```

FWIW, this script is run with the CLI version of PHP 5.2.5, and the OS is uClinux 2.6.19.3.

Thank you for any hint.

Edit: This seems to work fine

```<code>exec("ps aux | grep -i 'lighttpd -D' | grep -v grep", $pids);
if(empty($pids)) {
        print "Lighttpd not running!\n";
} else {
        print "Lighttpd OK\n";
}
</code>```

答:
To check whether process is running by its name, you can use pgrep, e.g.

```<code>$is_running = shell_exec("pgrep -f lighttpd");
</code>```

or:

```<code>exec("pgrep lighttpd", $output, $return);
if ($return == 0) {
    echo "Ok, process is running\n";
}
</code>```

as per this post.

If you know the PID of the process, you can use one the following functions:

```<code>  /**
   * Checks whether the process is running.
   *
   * @param int $pid Process PID.
   * @return bool
   */
  public static function isProcessRunning($pid) {
    // Calling with 0 kill signal will return true if process is running.
    return posix_kill((int) $pid, 0);
  }

  /**
   * Get the command of the process.
   * For example apache2 in case that's the Apache process.
   *
   * @param int $pid Process PID.
   * @return string
   */
  public static function getProcessCommand($pid) {
    $pid = (int) $pid;
    return trim(shell_exec("ps o comm= $pid"));
  }
</code>```

Related: How to check whether specified PID is currently running without invoking ps from PHP?

Title: Checking if process still running?

Body:
As a way to build a poor-man's watchdog and make sure an application is restarted in case it crashes (until I figure out why), I need to write a PHP CLI script that will be run by cron every 5mn to check whether the process is still running.

Based on this page, I tried the following code, but it always returns True even if I call it with bogus data:

function processExists($file = false) {
    $exists= false;
    $file= $file ? $file : __FILE__;

    // Check if file is in process list
    exec("ps -C $file -o pid=", $pids);
    if (count($pids) > 1) {
    $exists = true;
    }
    return $exists;
}

#if(processExists("lighttpd"))
if(processExists("dummy"))
    print("Exists\n")
else
    print("Doesn't exist\n");

Next, I tried this code...

(exec("ps -A | grep -i 'lighttpd -D' | grep -v grep", $output);)
print $output;

... but don't get what I expect:

/tmp> ./mycron.phpcli
Arrayroot:/tmp>

FWIW, this script is run with the CLI version of PHP 5.2.5, and the OS is uClinux 2.6.19.3.

Thank you for any hint.

Edit: This seems to work fine

exec("ps aux | grep -i 'lighttpd -D' | grep -v grep", $pids);
if(empty($pids)) {
        print "Lighttpd not running!\n";
} else {
        print "Lighttpd OK\n";
}

Body:
To check whether process is running by its name, you can use pgrep, e.g.

$is_running = shell_exec("pgrep -f lighttpd");

or:

exec("pgrep lighttpd", $output, $return);
if ($return == 0) {
    echo "Ok, process is running\n";
}

as per this post.

If you know the PID of the process, you can use one the following functions:

  /**
   * Checks whether the process is running.
   *
   * @param int $pid Process PID.
   * @return bool
   */
  public static function isProcessRunning($pid) {
    // Calling with 0 kill signal will return true if process is running.
    return posix_kill((int) $pid, 0);
  }

  /**
   * Get the command of the process.
   * For example apache2 in case that's the Apache process.
   *
   * @param int $pid Process PID.
   * @return string
   */
  public static function getProcessCommand($pid) {
    $pid = (int) $pid;
    return trim(shell_exec("ps o comm= $pid"));
  }

Related: How to check whether specified PID is currently running without invoking ps from PHP?


问:
Is there a way to index an array by enums in Rust?
I want to represent a table of data in the memory like the following:

     | USD | EUR |
-----+-----+-----+
John | 100 | 50  |
-----+-----+-----+
Tom  | 300 | 200 |
-----+-----+-----+
Nick | 200 | 0   |
-----+-----+-----+
```

<p>There is a known set of people, each of them owns some currency.</p>

<p>And I have the following enums:</p>

```enum Person {
    John,
    Tom,
    Nick
}

enum Currency {
    USD,
    EUR
}
```

<p>I'd like to encode this data as 2D array, and it would be cool to be able to index array elements not by <code>usize</code> but by <code>enum</code>. E.g.:</p>

```data[Person::John][Currency::USD] = 100;
```

Is it possible to do with arrays and enums in Rust? Or is there any other data structure that would serve for this?

I am aware of HashMap, but it's not exactly what I want because:

HashMap works on the heap (what makes it much slower than regular stack allocated array)

HashMap gives me no guarantee that item exist. E.g. every time I want to get something I have to unwrap it and handle None case, what is not very handy in comparison with usage of normal array.

This is different from How do I match enum values with an integer? because I am not interested in converting enum to usize; I just want a handy way to access array/map items by enum.

答:
ljedrz provided a good solution.
Another way to approach the problem is to use existing crate enum-map.

Add the following to your Cargo.toml:

```<code>[dependencies]
enum-map = "*"
enum-map-derive = "*"
</code>```

Then, in src/main.rs:

```<code>extern crate enum_map;
#[macro_use] extern crate enum_map_derive;

#[derive(Debug, EnumMap)]
enum Person { John, Tom, Nick }

#[derive(Debug, EnumMap)]
enum Currency { USD, EUR }

use enum_map::EnumMap;
use Person::*;
use Currency::*;

fn main() {
    // Create 2D EnumMap populated with f64::default(), which is 0.0
    let mut table : EnumMap<Person, EnumMap<Currency, f64>> = EnumMap::default();

    table[John][EUR] = 15.25;

    println!("table = {:?}", table);
    println!("table[John][EUR] = {:?}", table[John][EUR]);
}
</code>```

The output:

```<code>table = EnumMap { array: [EnumMap { array: [0, 15.25] }, EnumMap { array: [0, 0] }, EnumMap { array: [0, 0] }] }
table[John][EUR] = 15.25
</code>```

Body:
I want to represent a table of data in the memory like the following:

     | USD | EUR |
-----+-----+-----+
John | 100 | 50  |
-----+-----+-----+
Tom  | 300 | 200 |
-----+-----+-----+
Nick | 200 | 0   |
-----+-----+-----+

There is a known set of people, each of them owns some currency.

And I have the following enums:

enum Person {
    John,
    Tom,
    Nick
}

enum Currency {
    USD,
    EUR
}

I'd like to encode this data as 2D array, and it would be cool to be able to index array elements not by usize but by enum. E.g.:

data[Person::John][Currency::USD] = 100;

Is it possible to do with arrays and enums in Rust? Or is there any other data structure that would serve for this?

I am aware of HashMap, but it's not exactly what I want because:

HashMap works on the heap (what makes it much slower than regular stack allocated array)

HashMap gives me no guarantee that item exist. E.g. every time I want to get something I have to unwrap it and handle None case, what is not very handy in comparison with usage of normal array.

This is different from How do I match enum values with an integer? because I am not interested in converting enum to usize; I just want a handy way to access array/map items by enum.

Body:
ljedrz provided a good solution.
Another way to approach the problem is to use existing crate enum-map.

Add the following to your Cargo.toml:

[dependencies]
enum-map = "*"
enum-map-derive = "*"

Then, in src/main.rs:

extern crate enum_map;
#[macro_use] extern crate enum_map_derive;

#[derive(Debug, EnumMap)]
enum Person { John, Tom, Nick }

#[derive(Debug, EnumMap)]
enum Currency { USD, EUR }

use enum_map::EnumMap;
use Person::*;
use Currency::*;

fn main() {
    // Create 2D EnumMap populated with f64::default(), which is 0.0
    let mut table : EnumMap<Person, EnumMap<Currency, f64>> = EnumMap::default();

    table[John][EUR] = 15.25;

    println!("table = {:?}", table);
    println!("table[John][EUR] = {:?}", table[John][EUR]);
}

The output:

table = EnumMap { array: [EnumMap { array: [0, 15.25] }, EnumMap { array: [0, 0] }, EnumMap { array: [0, 0] }] }
table[John][EUR] = 15.25


问:
COM Integration from ALBPM - Cannot find IDispatch for '{00020906-0000-0000-C000-000000000046}'
I am trying to use the Office COM components in order to create Word and Excel documents. Unfortunately I can not achieve this because I am getting an error.

Cannot find IDispatch for
  '{00020906-0000-0000-C000-000000000046}'
  in module
  '{00020905-0000-0000-C000-000000000046}',
  v8.3

I tried reinstalling Office, my application (ALBPM) and my interface (combsvc) but it is not working.

I want to know how can I install IDispatch, or how can I know if it is installed in the correct module. Some times the error says:

Cannot find IDispatch for
  '{000209FF-0000-0000-C000-000000000046}'
  ... instead of
  00020906-0000-0000-C000-000000000046

The code I'm using generate these errors is:

```<code>wordAppl.visible = false
wordDocs = wordAppl.documents

contratoTemplate = "C:\\albpmFiles\\mandatory\\aTemplate.doc"
// .doc template
convenioTemplate = "C:\\albpmFiles\\mandatory\\ConvenioModificatorio.doc"
// .doc template
saveContrato = "C:\\albpmFiles\\temp\\"
// where to save.
saveConvenio = "C:\\albpmFiles\\temp\\"

contratoName = "NewContact.doc"
wordDoc = open(wordDocs, fileName : contratoTemplate)
bookmark = item(wordDoc.bookmarks, index : "atrDescripcion")

insertAfter bookmark.range
using text = instSolicitud.atrDescripcion
bookmark = item(wordDoc.bookmarks, index : "atrObjProveedor_atrNombre")
insertAfter bookmark.range
using text = instSolicitud.atrObjProveedor.atrNombre
bookmark = item(wordDoc.bookmarks, index : "atrObjProveedor_atrDireccion")
insertAfter bookmark.range
using text = instSolicitud.atrObjProveedor.atrDireccion
filename = saveContrato + contratoName

end

// Extras - Fin
saveAs wordDoc
using fileName = filename
</code>```

Any information you have about the IDispatch, or these registry entries, well be very appreciated, even if you can tell me where to find more info about this.

Thanks a lot.
Daniel.

答:
From the error you get I assume that you are using Word 2003.

Have you made sure that the COM brigde service is correctly installed and running?

```<code>combsvc -install
combsvc -start
</code>```

will register combsvc as service and then start it.

Please also have a look at the example for Word at the bottom of page 150 in the ALBPM Reference Guide.

The fact that it is sometimes working and sometimes could be an issue with ALBPM. Are you using the latest version and updates?

Another option - and quite frequent problem with Word automation - would be that the automated instance of Word is displaying a modal dialog box and is waiting for user interaction. You can switch of the display of modal dialogs by setting

```<code>Application.DisplayAlerts = 0
</code>```

However, this will unfortunately not prevent all popups from being displayed.

Is there actually an instance of Word started? If so, can you make the Window visible and see if documents can be opened or if there is a popup blocking the application?

OwnerDisplayName: Daniel M

LastEditorDisplayName: warren

Body:
I am trying to use the Office COM components in order to create Word and Excel documents. Unfortunately I can not achieve this because I am getting an error.

Cannot find IDispatch for
  '{00020906-0000-0000-C000-000000000046}'
  in module
  '{00020905-0000-0000-C000-000000000046}',
  v8.3

I tried reinstalling Office, my application (ALBPM) and my interface (combsvc) but it is not working.

I want to know how can I install IDispatch, or how can I know if it is installed in the correct module. Some times the error says:

Cannot find IDispatch for
  '{000209FF-0000-0000-C000-000000000046}'
  ... instead of
  00020906-0000-0000-C000-000000000046

The code I'm using generate these errors is:

wordAppl.visible = false
wordDocs = wordAppl.documents

contratoTemplate = "C:\\albpmFiles\\mandatory\\aTemplate.doc"
// .doc template
convenioTemplate = "C:\\albpmFiles\\mandatory\\ConvenioModificatorio.doc"
// .doc template
saveContrato = "C:\\albpmFiles\\temp\\"
// where to save.
saveConvenio = "C:\\albpmFiles\\temp\\"

contratoName = "NewContact.doc"
wordDoc = open(wordDocs, fileName : contratoTemplate)
bookmark = item(wordDoc.bookmarks, index : "atrDescripcion")

insertAfter bookmark.range
using text = instSolicitud.atrDescripcion
bookmark = item(wordDoc.bookmarks, index : "atrObjProveedor_atrNombre")
insertAfter bookmark.range
using text = instSolicitud.atrObjProveedor.atrNombre
bookmark = item(wordDoc.bookmarks, index : "atrObjProveedor_atrDireccion")
insertAfter bookmark.range
using text = instSolicitud.atrObjProveedor.atrDireccion
filename = saveContrato + contratoName

end

// Extras - Fin
saveAs wordDoc
using fileName = filename

Any information you have about the IDispatch, or these registry entries, well be very appreciated, even if you can tell me where to find more info about this.

Thanks a lot.
Daniel.

Body:
From the error you get I assume that you are using Word 2003.

Have you made sure that the COM brigde service is correctly installed and running?

combsvc -install
combsvc -start

will register combsvc as service and then start it.

Please also have a look at the example for Word at the bottom of page 150 in the ALBPM Reference Guide.

The fact that it is sometimes working and sometimes could be an issue with ALBPM. Are you using the latest version and updates?

Another option - and quite frequent problem with Word automation - would be that the automated instance of Word is displaying a modal dialog box and is waiting for user interaction. You can switch of the display of modal dialogs by setting

Application.DisplayAlerts = 0

However, this will unfortunately not prevent all popups from being displayed.

Is there actually an instance of Word started? If so, can you make the Window visible and see if documents can be opened or if there is a popup blocking the application?

OwnerDisplayName: divo

LastEditorDisplayName: divo


问:
Import data in Excel from SQL
How to import data into Excel from SQL table (Compiled Data) containing "935269" rows. I am unable to copy paste in Excel. Kindly let me know if I can import the data in Excel with the query or any other method.</p>

答: Go to Data tab, select New Query and then select From database. Select the database engine you need. Then in a Wizard select your table.

Title: Import data in Excel from SQL


问:
Sort WooCommerce variations by custom date field
I want to display a list of upcoming concerts.
Every concert has two attributes: date and location.

I've tried to show the next concerts by display all variations.
This is what I've done so far:

```<code><?php
    global $woocommerce, $product, $post, $re_wcvt_options;
    $available_variations = $product->get_available_variations();
    $attributes = $product->get_attributes();
?>
<ul>
    <?php foreach ($available_variations as $prod_variation) : ?>
        <?php
            // get some vars to work with
            $post_id = $prod_variation['variation_id'];
            $post_object = get_post($post_id);
        ?>
        <li>
        <?php foreach ($prod_variation['attributes'] as $attr_name => $attr_value) : ?>
            <?php
                // Get the correct variation values
                if (strpos($attr_name, '_pa_')){ // variation is a pre-definted attribute
                    $attr_name = substr($attr_name, 10);
                    $attr = get_term_by('slug', $attr_value, $attr_name);
                    $attr_value = $attr->name;
                } else { // variation is a custom attribute
                }
                echo $attr_value;
            ?>
        <?php endforeach;?>
        </li>
    <?php endforeach;?>
</ul>
</code>```

The proplem with this solution is that it only works within a product and only for one product. I couldn't show a list of multiple concerts (products) with differnt locations and dates (variations).

So I tried to use the loop to display the products/concerts and sort by a custom field with a date in it.

I've done that for a simple custom post type in the past.
This was the solution for that:

```<code><?php
$today_query = date ('Ymd');
$args = array(
    'post_type'              => array( 'concert' ),
    'posts_per_page'         => '10',
    'meta_key' => 'date',
    'meta_compare' => '>=',
    'meta_value' => $today_query,
    'orderby' => 'meta_value',
    'order' => 'ASC',
);
$query = new WP_Query( $args ); ?>
</code>```

The code orders the posts by meta field and shows only concerts in the future.
The only thing I don't understand is how I could use the meta fields from a single variation?!

Does anyone have a solution for this?

答:
Try to use pre_get_posts hook</p>

```<code>add_action( 'pre_get_posts', 'sort_products' );

function sort_products( $query )
{
    // If inside dashboard, skip sorting
    if (is_admin()){
        return;
    }
    // Check of query have woocommerce post type
   if (is_post_type_archive('product')){
        $query->set('meta_key', 'date');
        $query->set('meta_compare' , '>=');
        $query->set('meta_value' , time());
        $query->set('orderby', 'meta_value');
    }
    return $query;
}
</code>```

Body:
I want to display a list of upcoming concerts.
Every concert has two attributes: date and location.

I've tried to show the next concerts by display all variations.
This is what I've done so far:

<?php
    global $woocommerce, $product, $post, $re_wcvt_options;
    $available_variations = $product->get_available_variations();
    $attributes = $product->get_attributes();
?>

    <?php foreach ($available_variations as $prod_variation) : ?>
        <?php
            // get some vars to work with
            $post_id = $prod_variation['variation_id'];
            $post_object = get_post($post_id);
        ?>

        <?php foreach ($prod_variation['attributes'] as $attr_name => $attr_value) : ?>
            <?php
                // Get the correct variation values
                if (strpos($attr_name, '_pa_')){ // variation is a pre-definted attribute
                    $attr_name = substr($attr_name, 10);
                    $attr = get_term_by('slug', $attr_value, $attr_name);
                    $attr_value = $attr->name;
                } else { // variation is a custom attribute
                }
                echo $attr_value;
            ?>
        <?php endforeach;?>

    <?php endforeach;?>

The proplem with this solution is that it only works within a product and only for one product. I couldn't show a list of multiple concerts (products) with differnt locations and dates (variations).

So I tried to use the loop to display the products/concerts and sort by a custom field with a date in it.

I've done that for a simple custom post type in the past.
This was the solution for that:

<?php
$today_query = date ('Ymd');
$args = array(
    'post_type'              => array( 'concert' ),
    'posts_per_page'         => '10',
    'meta_key' => 'date',
    'meta_compare' => '>=',
    'meta_value' => $today_query,
    'orderby' => 'meta_value',
    'order' => 'ASC',
);
$query = new WP_Query( $args ); ?>

The code orders the posts by meta field and shows only concerts in the future.
The only thing I don't understand is how I could use the meta fields from a single variation?!

Does anyone have a solution for this?

Body:
Try to use pre_get_posts hook

add_action( 'pre_get_posts', 'sort_products' );

function sort_products( $query )
{
    // If inside dashboard, skip sorting
    if (is_admin()){
        return;
    }
    // Check of query have woocommerce post type
   if (is_post_type_archive('product')){
        $query->set('meta_key', 'date');
        $query->set('meta_compare' , '>=');
        $query->set('meta_value' , time());
        $query->set('orderby', 'meta_value');
    }
    return $query;
}


问:
RecyclerView Item Getting Clicked When Click on FloatingActionButton in Android
I have a FloatingActionButton over a RecyclerView in my app. The Button is showing ok, but when I click on it, the RecyclerView item below it is getting the click event, instead of the button. If I set the RecyclerView to show over the FloatingActionButton, the Button works as intended.

How to solve this, and make the Button to get the click event?

Thank you.

答:
Use FrameLayout for screen. you can get all click event,item or floating button.</p>

```<code><FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/white">
 <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </android.support.v7.widget.RecyclerView>
<android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@android:drawable/ic_dialog_email" />
</FrameLayout>
</code>```

Body:
Use FrameLayout for screen. you can get all click event,item or floating button.

<FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/white">
 <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </android.support.v7.widget.RecyclerView>
<android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@android:drawable/ic_dialog_email" />
</FrameLayout>


问:
create database constraint assertion in laravel
In my shopping cart table I want to check that each user only can have one cart with false value of paid column
for example in carts table:</p>

```<code>id         user_id         paid
1             1           false
2             1           false  ========> this should give me an error
---------------------------------------------------------------------
3             1           true
4             1           true
5             1           false  ========> But these rows are ok
6             1           true
</code>```

答:
Get the count using query, count the number of rows where paid = false and store that to a variable falseCount.
Then assert </p>

```<code>$this->assertLessThan(1, falseCount);
</code>```

Body:
In my shopping cart table I want to check that each user only can have one cart with false value of paid column
for example in carts table:

id         user_id         paid
1             1           false
2             1           false  ========> this should give me an error
---------------------------------------------------------------------
3             1           true
4             1           true
5             1           false  ========> But these rows are ok
6             1           true

Body:
Get the count using query, count the number of rows where paid = false and store that to a variable falseCount.
Then assert

$this->assertLessThan(1, falseCount);


问:
Count non-letters in string in Javascript
How to count non letter characters in given string in Javascript, chars like numbers and white spaces, and dashes, all except letters? Thanks.</p>

答:
You can remove all letters in the string and check the length of the result:

var a = 'asdflkj12398123!@$!@$1%#$252%$@3 2354 23$%@5$@%$ '
console.log(a.replace(/[a-z]/gi, '').length)```


问:
Autoresize cell after adding subview
I am creating a table with custom cells - in the last cell in the table I need to change the UItextField for a UILabel - which I am doing with this code in cellForRowAt:

```<code>case "Notes":
    if viewing == true {
        for subview in cell.contentView.subviews {
            if subview.description.contains("UITextField") {
                let newField = UILabel()
                 cell.contentView.addSubview(newField)

                 newField.frame = cell.infoField.frame
                 newField.text = profileToShow.notes
                 newField.font = cell.infoField.font
                 newField.addConstraints(cell.infoField.constraints)
                 newField.lineBreakMode = NSLineBreakMode.byWordWrapping

                 for constraint in cell.infoField.constraints {
                     cell.infoField.removeConstraint(constraint)
                 }

                 cell.infoField.isHidden = true
                 newField.numberOfLines = 0
             }
         }
     }
 break
</code>```

I am checking to see if the cell is the correct cell, which it is, adding the label and hiding the UITextField, which all works.  However when I run the program the label is resizing to fit the lines, but the cell is not resizing to fit the label.
What do I need to change to make this cell re-size with the added label, i am using the UITableViewAutomaticDimension already.

答:
Try changing the order in the cellForRowAtIndexPath and add layoutIfNeeded after adding constraints

```<code>case "Notes":
    if viewing == true {
        for subview in cell.contentView.subviews {
            if subview.description.contains("UITextField") {
                let newField = UILabel()
                 cell.contentView.addSubview(newField)

                 newField.frame = cell.infoField.frame
                 newField.numberOfLines = 0
                 newField.font = cell.infoField.font
                 newField.addConstraints(cell.infoField.constraints)
                 newField.lineBreakMode = NSLineBreakMode.byWordWrapping

                 for constraint in cell.infoField.constraints {
                     cell.infoField.removeConstraint(constraint)
                 }

                 cell.infoField.isHidden = true
                 newField.text = profileToShow.notes
                 cell.layoutIfNeeded()
             }
         }
     }
 break
</code>```

Title: Autoresize cell after adding subview

Body:
I am creating a table with custom cells - in the last cell in the table I need to change the UItextField for a UILabel - which I am doing with this code in cellForRowAt:

case "Notes":
    if viewing == true {
        for subview in cell.contentView.subviews {
            if subview.description.contains("UITextField") {
                let newField = UILabel()
                 cell.contentView.addSubview(newField)

                 newField.frame = cell.infoField.frame
                 newField.text = profileToShow.notes
                 newField.font = cell.infoField.font
                 newField.addConstraints(cell.infoField.constraints)
                 newField.lineBreakMode = NSLineBreakMode.byWordWrapping

                 for constraint in cell.infoField.constraints {
                     cell.infoField.removeConstraint(constraint)
                 }

                 cell.infoField.isHidden = true
                 newField.numberOfLines = 0
             }
         }
     }
 break

I am checking to see if the cell is the correct cell, which it is, adding the label and hiding the UITextField, which all works.  However when I run the program the label is resizing to fit the lines, but the cell is not resizing to fit the label.
What do I need to change to make this cell re-size with the added label, i am using the UITableViewAutomaticDimension already.

Body:
Try changing the order in the cellForRowAtIndexPath and add layoutIfNeeded after adding constraints

case "Notes":
    if viewing == true {
        for subview in cell.contentView.subviews {
            if subview.description.contains("UITextField") {
                let newField = UILabel()
                 cell.contentView.addSubview(newField)

                 newField.frame = cell.infoField.frame
                 newField.numberOfLines = 0
                 newField.font = cell.infoField.font
                 newField.addConstraints(cell.infoField.constraints)
                 newField.lineBreakMode = NSLineBreakMode.byWordWrapping

                 for constraint in cell.infoField.constraints {
                     cell.infoField.removeConstraint(constraint)
                 }

                 cell.infoField.isHidden = true
                 newField.text = profileToShow.notes
                 cell.layoutIfNeeded()
             }
         }
     }
 break