问:
How to get the left chain of points of a polygon?
I am trying to get the left polygonal chain given a set of consecutive points. (NOTE: edges are non-intersecting.)

Image 1. Sample polygon and its bound.

What I did was:

Get the minY, maxY and minX. (Bound.)

Find the point that contains minY (or maxY) then save it as the first point.

Save any points until point with minY or maxY is found while checking for  point with minX.

If the same Y is found first, save it as the new first point and repeat from #3.

If other Y is found first and the saved points has minX, this is the chain. Otherwise, save as the new first point and repeat from #3.

Image 2. The left chain of points.

But using this steps might give wrong result for some polygon, like this:

Since one point is (minX, maxY), either of the side will be returned.

EDIT:
With the idea of the left-bottom- and left-top-most points, here is the current code that I am using:

Get the min (left-bottom-most) and max (left-top-most) point.

```<code>std::vector<Coord> ret;
size_t i = 0;
Coord minCoord = poly[i];
Coord maxCoord = poly[i];
size_t minIdx = -1;
size_t maxIdx = -1;
size_t cnt = poly.size();
i++;
for (; i < cnt; i++)
{
    Coord c = poly[i];
    if (c.y < minCoord.y)   // new bottom
    {
        minCoord = c;
        minIdx = i;
    }
    else if (c.y == minCoord.y) // same bottom
    {
        if (c.x < minCoord.x)   // left most
        {
            minCoord = c;
            minIdx = i;
        }
    }
    if (c.y > maxCoord.y)   // new top
    {
        maxCoord = c;
        maxIdx = i;
    }
    else if (c.y == maxCoord.y) // same top
    {
        if (c.x < maxCoord.x)   // left most
        {
            maxCoord = c;
            maxIdx = i;
        }
    }
}
</code>```

Get the points connected to the max point.

```<code>i = maxIdx;
Coord mid = poly[i];
Coord ray1 = poly[(i + cnt - 1) % cnt];
Coord ray2 = poly[(i + 1) % cnt];
</code>```

Get which has smallest angle. This will be the path we will follow.

```<code>double rad1 = Pts2Rad(mid, ray1);
double rad2 = Pts2Rad(mid, ray2);
int step = 1;
if (rad1 < rad2)
    step = cnt - 1;
</code>```

Save the points.

```<code>while (i != minIdx)
{
    ret.push_back(poly[i]);
    i = (i + step) % cnt;
}
ret.push_back(poly[minIdx]);
</code>```

答:
To be specific, I am assuming that no vertex is duplicated and define the "left chain" as the sequence of vertices from the original polygon loop that goes from the leftmost vertex in the top side of the bounding box, to the leftmost vertex in the bottom side of the bounding box. [In case the top and bottom sides coincide, these two vertices also coincide; I leave it to you what to return in this case.]

To obtain these, you can scan all vertices and keep the left-topmost so far and left-bottommost so far. Then compare to the next vertex. If above the left-topmost, becomes the new lef-topmost. If at the same level and to the left, becomes the new left-topmost. Similarly for the left-bottommost.

Body:
I am trying to get the left polygonal chain given a set of consecutive points. (NOTE: edges are non-intersecting.)

Image 1. Sample polygon and its bound.

What I did was:

Get the minY, maxY and minX. (Bound.)

Find the point that contains minY (or maxY) then save it as the first point.

Save any points until point with minY or maxY is found while checking for  point with minX.

If the same Y is found first, save it as the new first point and repeat from #3.

If other Y is found first and the saved points has minX, this is the chain. Otherwise, save as the new first point and repeat from #3.

Image 2. The left chain of points.

But using this steps might give wrong result for some polygon, like this:

Since one point is (minX, maxY), either of the side will be returned.

EDIT:
With the idea of the left-bottom- and left-top-most points, here is the current code that I am using:

Get the min (left-bottom-most) and max (left-top-most) point.

std::vector<Coord> ret;
size_t i = 0;
Coord minCoord = poly[i];
Coord maxCoord = poly[i];
size_t minIdx = -1;
size_t maxIdx = -1;
size_t cnt = poly.size();
i++;
for (; i < cnt; i++)
{
    Coord c = poly[i];
    if (c.y < minCoord.y)   // new bottom
    {
        minCoord = c;
        minIdx = i;
    }
    else if (c.y == minCoord.y) // same bottom
    {
        if (c.x < minCoord.x)   // left most
        {
            minCoord = c;
            minIdx = i;
        }
    }
    if (c.y > maxCoord.y)   // new top
    {
        maxCoord = c;
        maxIdx = i;
    }
    else if (c.y == maxCoord.y) // same top
    {
        if (c.x < maxCoord.x)   // left most
        {
            maxCoord = c;
            maxIdx = i;
        }
    }
}

Get the points connected to the max point.

i = maxIdx;
Coord mid = poly[i];
Coord ray1 = poly[(i + cnt - 1) % cnt];
Coord ray2 = poly[(i + 1) % cnt];

Get which has smallest angle. This will be the path we will follow.

double rad1 = Pts2Rad(mid, ray1);
double rad2 = Pts2Rad(mid, ray2);
int step = 1;
if (rad1 < rad2)
    step = cnt - 1;

Save the points.

while (i != minIdx)
{
    ret.push_back(poly[i]);
    i = (i + step) % cnt;
}
ret.push_back(poly[minIdx]);


来源: stackexchange

问:
Converting List<Point2D.Double> to List<Point>
So, I need to call a method, which implements scanLine. It takes 3 arguments into parameter

rasterImage

List of Points

color

Another method returns a List of Point2D.Double. I pass the return value to new List:

```<code>ArrayList<Point2D.Double> outPolygon = clip.clipPolygon(cPoints, clipper);
</code>```

Now I need to use the outPolygon list as an parameter of scanLine. However Wrong argument type pops out, because It needs List of Point and I am passing List of Point2D.Double.

How to convert it so I can pass it as an argument of scanLine?

I tried this:

```<code>// prevedení z PointDouble na PointInt
for(int i=0; i<outPolygon.size(); i++)
{
    int x = (int)(outPolygon.get(i).x *(img.getWidth() - 1));
    int y = (int)((1 - outPolygon.get(i).y) * (img.getHeight() - 1));
    // uložení bodu do nového seznamu
    pointsInInteger.add(new Point(x,y));
}
</code>```

答:
Create a new list containing a new Point2D.Double for each Point. Something like this would be an option.

```<code>List<Point> points = ...
List<Point2D.Double> points2s = points.stream()
    .map(point -> new Point2D.Double(point.getX(), point.getY()))
    .collect(Collectors.toList());
</code>```

or with a loop

```<code>    final List<Point2D.Double> list = new ArrayList<>(points.size());
    for (Point point : points) {
        Point2D.Double aDouble = new Point2D.Double(point.getX(), point.getY());
        list.add(aDouble);
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
So, I need to call a method, which implements scanLine. It takes 3 arguments into parameter

rasterImage

List of Points

color

Another method returns a List of Point2D.Double. I pass the return value to new List:

ArrayList<Point2D.Double> outPolygon = clip.clipPolygon(cPoints, clipper);

Now I need to use the outPolygon list as an parameter of scanLine. However Wrong argument type pops out, because It needs List of Point and I am passing List of Point2D.Double.

How to convert it so I can pass it as an argument of scanLine?

I tried this:

// prevedení z PointDouble na PointInt
for(int i=0; i<outPolygon.size(); i++)
{
    int x = (int)(outPolygon.get(i).x *(img.getWidth() - 1));
    int y = (int)((1 - outPolygon.get(i).y) * (img.getHeight() - 1));
    // uložení bodu do nového seznamu
    pointsInInteger.add(new Point(x,y));
}

Body:
Create a new list containing a new Point2D.Double for each Point. Something like this would be an option.

List<Point> points = ...
List<Point2D.Double> points2s = points.stream()
    .map(point -> new Point2D.Double(point.getX(), point.getY()))
    .collect(Collectors.toList());

or with a loop

    final List<Point2D.Double> list = new ArrayList<>(points.size());
    for (Point point : points) {
        Point2D.Double aDouble = new Point2D.Double(point.getX(), point.getY());
        list.add(aDouble);
    }


问:
Displaying react components in carousel using react-slick
I am trying to use react-slick for displaying my custom Components inside carousel:

```<code>    <Slider {...settings}>
        <Hello />
        <Hello />
    </Slider>
</code>```

But seems that react-slick doens't support such way of using.

JsFiddle demo

https://jsfiddle.net/jqLzpewm/

答:
You need to wrap your React component with
:

```<code> <Slider {...settings}>
    <div>
        <Hello />
    </div>
    <div>
        <Hello />
    </div>
 </Slider>
</code>```

Or:

```<code><Slider {...settings}>
    {
        slideItems.map((slideItem) => (
            <div key={slideItem.id}>
                <Slide title={slideItem.title}/>
            </div>
        ))
    }
</Slider>
</code>```

data-index, class, tabindex and style attributes will be added to that

Body:
I am trying to use react-slick for displaying my custom Components inside carousel:

    <Slider {...settings}>
        <Hello />
        <Hello />
    </Slider>

But seems that react-slick doens't support such way of using.

JsFiddle demo

https://jsfiddle.net/jqLzpewm/

Body:
You need to wrap your React component with <div>:

 <Slider {...settings}>
    <div>
        <Hello />
    </div>
    <div>
        <Hello />
    </div>
 </Slider>

Or:

<Slider {...settings}>
    {
        slideItems.map((slideItem) => (
            <div key={slideItem.id}>
                <Slide title={slideItem.title}/>
            </div>
        ))
    }
</Slider>

data-index, class, tabindex and style attributes will be added to that <div>


问:
Django Form save - circular dependency
I have 2 models Account and User. An Account can have multiple users.

When the first User(Owner) is created at the same time the Account will be created.

Because User have a ForeignKey to Account, I need first to create the Account, and after the User.

But Account had a field created_by which is request.user. So is a circular problem.

I think I need to create first the Account and created_by to be a superuser(first) and than create the User, and update the Account with the new user.

```<code>class Account(MetaData):
    name = models.CharField(max_length=255)
created_by = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True,
                                   related_name='%(app_label)s_%(class)s_created_by', on_delete=models.CASCADE)

class User(AbstractBaseUser):
    account = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, related_name='owner')
</code>```

How can I do that ?

I need this only first time, for the first user, because after that for the other users the Account will exist.

When I'm saying first user, I'm not referring to staff users (as superusers), but normal users for which an account is mandatory thru a register form.

blank=True is just for staff members.

答:
Your User model's account field allows nulls, so nothing prevents you from first creating the user without an account, then creating the account with this user, and finally updating the user with the account:

```<code> with transaction.atomic():
     user = User.objects.create(account=None, ...)
     account = Account.objects.create("test", created_by=user)
     user.account = account
     user.save(update_fields=["account"])
</code>```

Title: Django Form save - circular dependency

Body:
I have 2 models Account and User. An Account can have multiple users.

When the first User(Owner) is created at the same time the Account will be created.

Because User have a ForeignKey to Account, I need first to create the Account, and after the User.

But Account had a field created_by which is request.user. So is a circular problem.

I think I need to create first the Account and created_by to be a superuser(first) and than create the User, and update the Account with the new user.

class Account(MetaData):
    name = models.CharField(max_length=255)
created_by = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True,
                                   related_name='%(app_label)s_%(class)s_created_by', on_delete=models.CASCADE)

class User(AbstractBaseUser):
    account = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, related_name='owner')

How can I do that ?

I need this only first time, for the first user, because after that for the other users the Account will exist.

When I'm saying first user, I'm not referring to staff users (as superusers), but normal users for which an account is mandatory thru a register form.

blank=True is just for staff members.

Body:
Your User model's account field allows nulls, so nothing prevents you from first creating the user without an account, then creating the account with this user, and finally updating the user with the account:

 with transaction.atomic():
     user = User.objects.create(account=None, ...)
     account = Account.objects.create("test", created_by=user)
     user.account = account
     user.save(update_fields=["account"])


问:
Using software from a c++ program
I downloaded a c++ program for a software that i want to use, with the following directories :
CHANGELOG  LICENSE  README.md  build  doc  include  src

The code is a bit old , and i want to compile it from a linux terminal , i know that i have to use gcc and make for that( that's all the install details says) but the src directories containing cpp files doesnt have a 'main.cpp' file , the build contains one file : Makefile
What are the steps to follow to use this software , and how can i compile this with no main.cpp
I'm using gcc version 4.8.4 (Ubuntu 4.8.4-2ubuntu1~14.04.3) and GNU Make 3.81 ; but the program is a bit old ( 2011)

答:
Most likely, just run make in the build folder

If that doesn't work, try reading the readme file.

You may have link errors, in which case you'll have to figure out which libraries are missing.

Title: Using software from a c++ program


问:
Is it possible to skip license agreement page when splunk starts on first time in docker container?
I have created a Dockerfile when the container builds during that time I need to create multiple login users on backside of Splunk.

I am getting splunk agreement issue unable to skip/accept agreement on build container as shown below.

Dockerfile

```<code>FROM splunk/splunk:latest
ENV SPLUNK_HOME /opt/splunk
RUN apt-get update && apt-get install -y wget
COPY ./splunk-launch.conf /opt/splunk/etc/splunk-launch.conf
COPY ./splunk.license /opt/splunk/etc/licenses/enterprise/splunk.license
COPY ./My-app1 / /opt/splunk/etc/apps/My-app1
COPY ./My-app2 /opt/splunk/etc/apps/My-app2
COPY ./My-app3 /opt/splunk/etc/apps/My-app3
COPY ./splunk_user.sh /opt/splunk/bin/splunk_user.sh
RUN chmod +x /opt/splunk/bin/splunk_user.sh
RUN chown -R splunk:splunk /opt/splunk/bin/splunk_user.sh
EXPOSE 8000/tcp 8089/tcp 8191/tcp 9997/tcp 1514 8088/tcp
VOLUME [ “/opt/splunk/etc”, “/opt/splunk/var” ]
WORKDIR /opt/splunk/bin
CMD [“./splunk_user.sh”]
</code>```

splunk_user.sh

```<code>./splunk add user pradeep -password passwd123 -role admin -email pradeep@gmail.com -full-name Pradeep -auth admin:changeme
./splunk add user sankar -password passwd123 -role admin -email sankar@gmail.com -full-name Sankar -auth admin:changeme
</code>```

Error

答:
Not sure try this

CMD ["y | ./splunk_user.sh"]

Body:
I have created a Dockerfile when the container builds during that time I need to create multiple login users on backside of Splunk.

I am getting splunk agreement issue unable to skip/accept agreement on build container as shown below.

Dockerfile

FROM splunk/splunk:latest
ENV SPLUNK_HOME /opt/splunk
RUN apt-get update && apt-get install -y wget
COPY ./splunk-launch.conf /opt/splunk/etc/splunk-launch.conf
COPY ./splunk.license /opt/splunk/etc/licenses/enterprise/splunk.license
COPY ./My-app1 / /opt/splunk/etc/apps/My-app1
COPY ./My-app2 /opt/splunk/etc/apps/My-app2
COPY ./My-app3 /opt/splunk/etc/apps/My-app3
COPY ./splunk_user.sh /opt/splunk/bin/splunk_user.sh
RUN chmod +x /opt/splunk/bin/splunk_user.sh
RUN chown -R splunk:splunk /opt/splunk/bin/splunk_user.sh
EXPOSE 8000/tcp 8089/tcp 8191/tcp 9997/tcp 1514 8088/tcp
VOLUME [ “/opt/splunk/etc”, “/opt/splunk/var” ]
WORKDIR /opt/splunk/bin
CMD [“./splunk_user.sh”]

splunk_user.sh

./splunk add user pradeep -password passwd123 -role admin -email pradeep@gmail.com -full-name Pradeep -auth admin:changeme
./splunk add user sankar -password passwd123 -role admin -email sankar@gmail.com -full-name Sankar -auth admin:changeme

Error


问:
Gmail smtp is not working in phpmailer
This my code,

```<code>require_once("PHPMailer/class.PHPMailer.php");
$mail = new PHPMailer();
/* receiver details and message - start */
$toid = "example@gmail.com";
$toname = "Example";

$msg = "First name : ".$_POST["fname"] . "<br>";
$msg .= "Last name : ".$_POST["lname"]. "<br>";;
$msg .= "Email : ".$_POST["email"]. "<br>";;
$msg .= "Mobile : ".$_POST["mobile"]. "<br>";;
$msg .= "Message : ".$_POST["msg"];
$subject = "sample subject";
/* receiver details and message - end */

$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 1;  // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true;  // authentication enabled
$mail->SMTPKeepAlive = true;

/* mail smtp configuration - start */
$mail->SMTPSecure = 'tls'; // secure transfer enabled REQUIRED for GMail
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->Username = 'test@gmail.com';
$mail->Password = 'xxxxxx';
/* mail smtp configuration - end */

$mail->From = "test@gmail.com";
$mail->FromName = "from name";

$mail->AddAddress($toid, $toname);

$mail->Subject = $subject;
$mail->Body    = $msg;
$mail->IsHTML(true);
if($mail->Send()){
echo "success";
}else{
echo "Failure";
}
</code>```

When run the above , it throws

stream_socket_enable_crypto(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in C:\xampp\htdocs\mail\PHPMailer\class.smtp.php on line 200

答:
For GMail, change your setup to:</p>

```<code>$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
</code>```

Title: Gmail smtp is not working in phpmailer

Body:
This my code,

require_once("PHPMailer/class.PHPMailer.php");
$mail = new PHPMailer();
/* receiver details and message - start */
$toid = "example@gmail.com";
$toname = "Example";

$msg = "First name : ".$_POST["fname"] . "
";
$msg .= "Last name : ".$_POST["lname"]. "
";;
$msg .= "Email : ".$_POST["email"]. "
";;
$msg .= "Mobile : ".$_POST["mobile"]. "
";;
$msg .= "Message : ".$_POST["msg"];
$subject = "sample subject";
/* receiver details and message - end */

$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 1;  // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true;  // authentication enabled
$mail->SMTPKeepAlive = true;

/* mail smtp configuration - start */
$mail->SMTPSecure = 'tls'; // secure transfer enabled REQUIRED for GMail
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->Username = 'test@gmail.com';
$mail->Password = 'xxxxxx';
/* mail smtp configuration - end */

$mail->From = "test@gmail.com";
$mail->FromName = "from name";

$mail->AddAddress($toid, $toname);

$mail->Subject = $subject;
$mail->Body    = $msg;
$mail->IsHTML(true);
if($mail->Send()){
echo "success";
}else{
echo "Failure";
}

When run the above , it throws

stream_socket_enable_crypto(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in C:\xampp\htdocs\mail\PHPMailer\class.smtp.php on line 200

Body:
For GMail, change your setup to:

$mail->SMTPSecure = 'ssl';
$mail->Port = 465;


问:
A task was cancelled error in context.postAsync() and while sending the typing activity Bot Framework
I am getting the task was cancelled error intermittently in two lines of code.

Code Example

```<code>await connector.Conversations.ReplyToActivityAsync(isTypingReply);
</code>```

and

```<code>await context.PostAsync("The flow has been stopped, please type Hi/Hello to start again.");
</code>```

Reproduction Steps

Happens intermittently, not able to reproduce on will

Actual Results

Getting below errors in the mentioned lines of code

```
Time: 04-12-2017 12:15:11 PM
Message: A task was canceled.
Stack Trace: at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Connector.Conversations.d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Connector.ConversationsExtensions.d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at ParentServiceContoller.MessagesController.d__4.MoveNext() in D:\Dev\INDIGOHR_BOT\ParentServiceContoller\Controllers\MessagesController.cs:line 34
Source: mscorlib

Time: 04-12-2017 12:44:56 PM
Message: A task was canceled.
Stack Trace: at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Connector.Conversations.d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Connector.ConversationsExtensions.d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Builder.Dialogs.Internals.AlwaysSendDirect_BotToUser.d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Builder.Dialogs.Internals.InputHintQueue.d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Builder.Dialogs.Internals.AutoInputHint_BotToUser.d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Builder.Dialogs.Internals.MapToChannelData_BotToUser.d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Builder.Dialogs.Internals.LogBotToUser.d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Builder.Dialogs.Internals.DialogContext.d__12.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Builder.Dialogs.Extensions.d__10.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at ParentServiceContoller.Dialogs.RegistrationDialog.d__11.MoveNext() in D:\Dev\INDIGOHR_BOT\ParentServiceContoller\Dialogs\RegistrationDialog.cs:line 216
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Builder.Dialogs.Internals.DialogTask.ThunkResume1.d__5.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Bot.Builder.Internals.Fibers.Wait2.d__19.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Builder.Internals.Fibers.Frame1.-PollAsync>d__9.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Bot.Builder.Internals.Fibers.Fiber1.d__16.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.Bot.Builder.Internals.Fibers.Wait2.Microsoft.Bot.Builder.Internals.Fibers.IAwaiter.GetResult() at ParentServiceContoller.Dialogs.RootDialog.d__9.MoveNext() in D:\Dev\INDIGOHR_BOT\ParentServiceContoller\Dialogs\RootDialog.cs:line 211 --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Bot.Builder.Dialogs.Internals.DialogTask.ThunkResume1.d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Builder.Internals.Fibers.Wait2.-PollAsync>d__19.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Bot.Builder.Internals.Fibers.Frame1.d__9.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Builder.Internals.Fibers.Fiber1.-PollAsync>d__16.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at Microsoft.Bot.Builder.Internals.Fibers.Wait2.Microsoft.Bot.Builder.Internals.Fibers.IAwaiter.GetResult()
at Microsoft.Bot.Builder.Dialogs.Chain.LoopDialog1.d__3.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Bot.Builder.Dialogs.Internals.DialogTask.ThunkResume1.d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Builder.Internals.Fibers.Wait2.-PollAsync>d__19.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Bot.Builder.Internals.Fibers.Frame1.d__9.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Builder.Internals.Fibers.Fiber1.-PollAsync>d__16.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Bot.Builder.Dialogs.Internals.DialogTask.d__23.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Bot.Builder.Dialogs.Internals.DialogTask.d__172.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Builder.Dialogs.Internals.DialogContext.d__18`2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at ParentServiceContoller.Dialogs.RootDialog.d__8.MoveNext() in D:\Dev\INDIGOHR_BOT\ParentServiceContoller\Dialogs\RootDialog.cs:line 182
Source: mscorlib
```

答:
you can use the below code:

```<code>ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));
Activity isActivityTyping = activity.CreateReply();
isActivityTyping.Type = ActivityTypes.Typing;
await connector.Conversations.ReplyToActivityAsync(isActivityTyping);
</code>```

then use

```<code>await context.PostAsync("The flow has been stopped, please type Hi/Hello to start again.");
</code>```

i hope this will help you out.
do let me know in case of more help required.

Body:
I am getting the task was cancelled error intermittently in two lines of code.

Code Example

await connector.Conversations.ReplyToActivityAsync(isTypingReply);

and

await context.PostAsync("The flow has been stopped, please type Hi/Hello to start again.");

Reproduction Steps

Happens intermittently, not able to reproduce on will

Actual Results

Getting below errors in the mentioned lines of code

Time: 04-12-2017 12:15:11 PM
Message: A task was canceled.
Stack Trace: at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Connector.Conversations.d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Connector.ConversationsExtensions.d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at ParentServiceContoller.MessagesController.d__4.MoveNext() in D:\Dev\INDIGOHR_BOT\ParentServiceContoller\Controllers\MessagesController.cs:line 34
Source: mscorlib

Time: 04-12-2017 12:44:56 PM
Message: A task was canceled.
Stack Trace: at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Connector.Conversations.d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Connector.ConversationsExtensions.d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Builder.Dialogs.Internals.AlwaysSendDirect_BotToUser.d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Builder.Dialogs.Internals.InputHintQueue.d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Builder.Dialogs.Internals.AutoInputHint_BotToUser.d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Builder.Dialogs.Internals.MapToChannelData_BotToUser.d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Builder.Dialogs.Internals.LogBotToUser.d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Builder.Dialogs.Internals.DialogContext.d__12.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Builder.Dialogs.Extensions.d__10.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at ParentServiceContoller.Dialogs.RegistrationDialog.d__11.MoveNext() in D:\Dev\INDIGOHR_BOT\ParentServiceContoller\Dialogs\RegistrationDialog.cs:line 216
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Builder.Dialogs.Internals.DialogTask.ThunkResume1.d__5.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Bot.Builder.Internals.Fibers.Wait2.d__19.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Builder.Internals.Fibers.Frame1.-PollAsync>d__9.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Bot.Builder.Internals.Fibers.Fiber1.d__16.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.Bot.Builder.Internals.Fibers.Wait2.Microsoft.Bot.Builder.Internals.Fibers.IAwaiter.GetResult() at ParentServiceContoller.Dialogs.RootDialog.d__9.MoveNext() in D:\Dev\INDIGOHR_BOT\ParentServiceContoller\Dialogs\RootDialog.cs:line 211 --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Bot.Builder.Dialogs.Internals.DialogTask.ThunkResume1.d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Builder.Internals.Fibers.Wait2.-PollAsync>d__19.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Bot.Builder.Internals.Fibers.Frame1.d__9.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Builder.Internals.Fibers.Fiber1.-PollAsync>d__16.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at Microsoft.Bot.Builder.Internals.Fibers.Wait2.Microsoft.Bot.Builder.Internals.Fibers.IAwaiter.GetResult()
at Microsoft.Bot.Builder.Dialogs.Chain.LoopDialog1.d__3.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Bot.Builder.Dialogs.Internals.DialogTask.ThunkResume1.d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Builder.Internals.Fibers.Wait2.-PollAsync>d__19.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Bot.Builder.Internals.Fibers.Frame1.d__9.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Builder.Internals.Fibers.Fiber1.-PollAsync>d__16.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Bot.Builder.Dialogs.Internals.DialogTask.d__23.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Bot.Builder.Dialogs.Internals.DialogTask.d__172.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Builder.Dialogs.Internals.DialogContext.d__18`2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at ParentServiceContoller.Dialogs.RootDialog.d__8.MoveNext() in D:\Dev\INDIGOHR_BOT\ParentServiceContoller\Dialogs\RootDialog.cs:line 182
Source: mscorlib

Body:
you can use the below code:

ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));
Activity isActivityTyping = activity.CreateReply();
isActivityTyping.Type = ActivityTypes.Typing;
await connector.Conversations.ReplyToActivityAsync(isActivityTyping);

then use

await context.PostAsync("The flow has been stopped, please type Hi/Hello to start again.");

i hope this will help you out.
do let me know in case of more help required.


问:
Dividing monthly rate between Start and End Dates
I have Monthly rate for each employee in one table which I need to distribute equally based on the Employee Start and End date in the particular project.
For e.g. The monthly rate for employee X is $4300 which is stored in Table A. The employee start & end date in the project is '2017-11-03' & '2017-12-12' respectively and is stored in Table B. I need the employee cost for both Nov and Dec months.

Appreciate any help on this.

Edits:

Table 1:Employee Details
Col1-Employee name
Col2-Start date
Col3- End date

Table 2: Rate Card
Col1-Location
Col2-Grade
Col3- Cost Per Month

Table 3: Employee Billing
Col1-Year
Col2-Month
Col3- Employee
Col4- Cost per month

So if Employee worked from 4-Nov-17 to 31-Dec-17 and Cost per month is $4000, then in Billing table there should be 2 entries like:

2017,Nov,Emp1,(4000/30)*((30-4)+1)
2017,Dec,Emp1,4000

I was ale to insert 2 entries in table 3 based on input from table 1 but not able to calculate the customized cost

```<code>case
       when (webResource_Details_ESS_recurrent_entries.recurrent_month<>DATEPART(mm, l.start_date) or
      webResource_Details_ESS_recurrent_entries.recurrent_month<>DATEPART(mm, l.end_date))
      then
       l.Employee_Cost

       when DATEPART(day, l.start_date) <> 1 and Eomonth(l.start_date) = Eomonth(l.end_date)  then
        (Datediff(day, l.start_date, l.end_date) *
            (l.Employee_Cost / Datediff(day,Eomonth(l.start_date), Dateadd(month,1, Eomonth(l.start_date))) ) )
       when  DATEPART(day, l.start_date) <> 1 and Eomonth(l.start_date) <> Eomonth(l.end_date)  then ( Datediff(day, l.start_date, Eomonth(l.start_date)) *
            ( l.Employee_Cost /Datediff(day, Eomonth(l.start_date), Dateadd(month, 1,Eomonth(l.start_date))) ) )
            when DATEPART(day, l.end_date) <> (DATEPART(day, DATEADD(second,-1,DATEADD(month, DATEDIFF(month,0,l.end_date)+1,0)))) and Eomonth(l.start_date) <> Eomonth(l.end_date) then (Datediff(day, ( Dateadd(month, Datediff(month, 0,l.end_date),0) ),l.end_date)
            *(l.Employee_Cost /Datediff(day, Eomonth(l.end_date),Dateadd(month, 1, Eomonth(l.end_date)))))

      end as Employee_Cost
</code>```

答:
```<code>SELECT em.employeed,
       CASE
         WHEN Eomonth(startdate) = Eomonth(enddate)
         THEN   (Datediff(day, startdate, enddate) *
                (rate / Datediff(day,Eomonth(startdate), Dateadd(month,1, Eomonth(startdate))) ) )
         ELSE   ( ( Datediff(day, startdate, Eomonth(startdate)) *
                ( rate /Datediff(day, Eomonth(startdate), Dateadd(month, 1,Eomonth(startdate))) ) ) +
                (Datediff(day, ( Dateadd(month, Datediff(month, 0,enddate),0) ),enddate)
                *(rate /Datediff(day, Eomonth(enddate),Dateadd(month, 1, Eomonth(enddate))))))
       END AS wage
FROM   employeemaster em
INNER JOIN employeerate AS er
ON ( em.employeed = er.employeed )
</code>```

First Case will handle case when both start date and end date are in same month

```<code>eomonth(startdate) = eomonth(enddate) then (datediff(day,startdate,enddate)*(rate/datediff(day, eomonth(startdate), dateadd(month, 1, eomonth(startdate)))))
</code>```

This calculate days and rate for month of start date

```<code>datediff(day,startdate,eomonth(startdate)) * (rate/datediff(day, eomonth(startdate), dateadd(month, 1, eomonth(startdate)))))
</code>```

This calculate days and rate for month of end date

```<code>(datediff(day,(DATEADD(month, DATEDIFF(month, 0, enddate), 0)),enddate)* rate/datediff(day, eomonth(enddate), dateadd(month, 1, eomonth(enddate))))
</code>```

Body:
I have Monthly rate for each employee in one table which I need to distribute equally based on the Employee Start and End date in the particular project.
For e.g. The monthly rate for employee X is $4300 which is stored in Table A. The employee start & end date in the project is '2017-11-03' & '2017-12-12' respectively and is stored in Table B. I need the employee cost for both Nov and Dec months.

Appreciate any help on this.

Edits:

Table 1:Employee Details
Col1-Employee name
Col2-Start date
Col3- End date

Table 2: Rate Card
Col1-Location
Col2-Grade
Col3- Cost Per Month

Table 3: Employee Billing
Col1-Year
Col2-Month
Col3- Employee
Col4- Cost per month

So if Employee worked from 4-Nov-17 to 31-Dec-17 and Cost per month is $4000, then in Billing table there should be 2 entries like:

2017,Nov,Emp1,(4000/30)*((30-4)+1)
2017,Dec,Emp1,4000

I was ale to insert 2 entries in table 3 based on input from table 1 but not able to calculate the customized cost

case
       when (webResource_Details_ESS_recurrent_entries.recurrent_month<>DATEPART(mm, l.start_date) or
      webResource_Details_ESS_recurrent_entries.recurrent_month<>DATEPART(mm, l.end_date))
      then
       l.Employee_Cost

       when DATEPART(day, l.start_date) <> 1 and Eomonth(l.start_date) = Eomonth(l.end_date)  then
        (Datediff(day, l.start_date, l.end_date) *
            (l.Employee_Cost / Datediff(day,Eomonth(l.start_date), Dateadd(month,1, Eomonth(l.start_date))) ) )
       when  DATEPART(day, l.start_date) <> 1 and Eomonth(l.start_date) <> Eomonth(l.end_date)  then ( Datediff(day, l.start_date, Eomonth(l.start_date)) *
            ( l.Employee_Cost /Datediff(day, Eomonth(l.start_date), Dateadd(month, 1,Eomonth(l.start_date))) ) )
            when DATEPART(day, l.end_date) <> (DATEPART(day, DATEADD(second,-1,DATEADD(month, DATEDIFF(month,0,l.end_date)+1,0)))) and Eomonth(l.start_date) <> Eomonth(l.end_date) then (Datediff(day, ( Dateadd(month, Datediff(month, 0,l.end_date),0) ),l.end_date)
            *(l.Employee_Cost /Datediff(day, Eomonth(l.end_date),Dateadd(month, 1, Eomonth(l.end_date)))))

      end as Employee_Cost

Body:
SELECT em.employeed,
       CASE
         WHEN Eomonth(startdate) = Eomonth(enddate)
         THEN   (Datediff(day, startdate, enddate) *
                (rate / Datediff(day,Eomonth(startdate), Dateadd(month,1, Eomonth(startdate))) ) )
         ELSE   ( ( Datediff(day, startdate, Eomonth(startdate)) *
                ( rate /Datediff(day, Eomonth(startdate), Dateadd(month, 1,Eomonth(startdate))) ) ) +
                (Datediff(day, ( Dateadd(month, Datediff(month, 0,enddate),0) ),enddate)
                *(rate /Datediff(day, Eomonth(enddate),Dateadd(month, 1, Eomonth(enddate))))))
       END AS wage
FROM   employeemaster em
INNER JOIN employeerate AS er
ON ( em.employeed = er.employeed )

First Case will handle case when both start date and end date are in same month

eomonth(startdate) = eomonth(enddate) then (datediff(day,startdate,enddate)*(rate/datediff(day, eomonth(startdate), dateadd(month, 1, eomonth(startdate)))))

This calculate days and rate for month of start date

datediff(day,startdate,eomonth(startdate)) * (rate/datediff(day, eomonth(startdate), dateadd(month, 1, eomonth(startdate)))))

This calculate days and rate for month of end date

(datediff(day,(DATEADD(month, DATEDIFF(month, 0, enddate), 0)),enddate)* rate/datediff(day, eomonth(enddate), dateadd(month, 1, eomonth(enddate))))


问:
Where to stop timer when user stop the app while timer is running
newBie in swift.

If user stop the app or swipe to stop the app WHILE the timer is running. Do I need to garbage collect the timer or where to stop the timer. If this is not handle, will it cause any problem?

```<code>Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.setUpTimerCountDown), userInfo: nil, repeats: true)
</code>```

Thanks

答:
```<code>import UIKit

class ViewController: UIViewController {

    var timer: Timer!

    override func viewDidLoad() {
       super.viewDidLoad()

        self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.updateValue), userInfo: nil, repeats: true)
    }

    override func viewWillDisappear(_ animated: Bool) {

        if self.timer != nil{

            self.timer.invaidate()

            self.timer = nil
        }
    }

    func updateValue(){

        print("Timer is call")
    }
}
</code>```

Body:
newBie in swift.

If user stop the app or swipe to stop the app WHILE the timer is running. Do I need to garbage collect the timer or where to stop the timer. If this is not handle, will it cause any problem?

Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.setUpTimerCountDown), userInfo: nil, repeats: true)

Thanks


问:
Need to pass array to route and controller
I need to pass array to route and controller from view.

I get the error:

Missing required parameters for [Route: actBook] [URI: bookfromindex/actBook/{id}/{array}].

I have my route defined as:

```<code>Route::get('/bookfromindex/actBook/{id}/{array}', 'BookController@actBook')->name('actBook');
</code>```

My controller function is defined as:

```<code>public function actBook(Request $request, $id, $array){
</code>```

And I call this route in my view using:

```<code><a href="{{ route('actBook', $room->id, $array) }}" class="btn btn-default">დაჯავშნა</a>
</code>```

How do I prevent this error?

答:
First, you need to serialize your array then you can pass into the parameter

Example :

```<code>{{  $serializeArray = serialize($array) }}
<a href="{{ route('actBook', $room->id, $serializeArray) }}" class="btn btn-default">
</code>```

Controller :

```<code>public function actBook(Request $request, $id, $array){
</code>```

Route :

```<code>Route::get('/bookfromindex/actBook/{id}/{array}', 'BookController@actBook')->name('actBook');
</code>```

Hope this will help you.

Body:
I need to pass array to route and controller from view.

I get the error:

Missing required parameters for [Route: actBook] [URI: bookfromindex/actBook/{id}/{array}].

I have my route defined as:

Route::get('/bookfromindex/actBook/{id}/{array}', 'BookController@actBook')->name('actBook');

My controller function is defined as:

public function actBook(Request $request, $id, $array){

And I call this route in my view using:

id, $array) }}" class="btn btn-default">დაჯავშნა

How do I prevent this error?

Body:
First, you need to serialize your array then you can pass into the parameter

Example :

{{  $serializeArray = serialize($array) }}
<a href="{{ route('actBook', $room->id, $serializeArray) }}" class="btn btn-default">

Controller :

public function actBook(Request $request, $id, $array){

Route :

Route::get('/bookfromindex/actBook/{id}/{array}', 'BookController@actBook')->name('actBook');

Hope this will help you.


问:
Merge two bitmaps in android
I want to merge two bitmaps, here is my code

```<code>// Camera arg conversion to Bitmap
                    Bitmap cameraBitmap = BitmapFactory.decodeByteArray(arg0, 0,
                            arg0.length);
                    Bitmap back = Bitmap.createBitmap(cameraBitmap.getWidth(),
                        cameraBitmap.getHeight(), Bitmap.Config.ARGB_8888);
                    Canvas cam = new Canvas(back);
                    cam.drawBitmap(cameraBitmap, matrix, null);

                    // FrameLayout to Bitmap
                    FrameLayout mainLayout = (FrameLayout) findViewById(R.id.frame);
                    Bitmap foreground = Bitmap.createBitmap(mainLayout.getWidth(),
                            mainLayout.getHeight(), Bitmap.Config.ARGB_8888);
                    Canvas c = new Canvas(foreground);
                    mainLayout.draw(c);

                    Bitmap cs = null;
                    cs = Bitmap.createBitmap(foreground.getWidth(), cameraBitmap.getHeight(), Bitmap.Config.ARGB_8888);

                    Canvas comboImage = new Canvas(cs);
                    comboImage.drawBitmap(cameraBitmap, 0f, 0f, null);
                    comboImage.drawBitmap(foreground, 0f, cameraBitmap.getHeight(), null);

                    FileOutputStream fos = null;
                    try {
                        fos = new FileOutputStream(file);
                        if (fos != null) {
                            cs.compress(Bitmap.CompressFormat.PNG, 90, fos);
                            fos.close();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
</code>```

The camera image should become background, and foreground as top image. I've tried from
Combining 2 Images in Android using Canvas  but it didn't help me. Any idea.? Thanks

答:
Merging Two Bitmap vertically  when one is large and second is small

 follow this method

```<code> public Bitmap finalcombieimage(Bitmap c, Bitmap s) {
    Bitmap cs = null;
    DisplayMetrics metrics = getBaseContext().getResources().getDisplayMetrics();
    int width = metrics.widthPixels;
    int height = metrics.heightPixels;
    cs = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas comboImage = new Canvas(cs);
    Rect dest1 = new Rect(0, 0, width, height); // left,top,right,bottom
    comboImage.drawBitmap(c, null, dest1, null);
    Rect dest2 = new Rect(0, height-400 / 2, width, height);
    comboImage.drawBitmap(s, null, dest2, null);
    return cs;
}
</code>```

Title: Merge two bitmaps in android

Body:
I want to merge two bitmaps, here is my code

// Camera arg conversion to Bitmap
                    Bitmap cameraBitmap = BitmapFactory.decodeByteArray(arg0, 0,
                            arg0.length);
                    Bitmap back = Bitmap.createBitmap(cameraBitmap.getWidth(),
                        cameraBitmap.getHeight(), Bitmap.Config.ARGB_8888);
                    Canvas cam = new Canvas(back);
                    cam.drawBitmap(cameraBitmap, matrix, null);

                    // FrameLayout to Bitmap
                    FrameLayout mainLayout = (FrameLayout) findViewById(R.id.frame);
                    Bitmap foreground = Bitmap.createBitmap(mainLayout.getWidth(),
                            mainLayout.getHeight(), Bitmap.Config.ARGB_8888);
                    Canvas c = new Canvas(foreground);
                    mainLayout.draw(c);

                    Bitmap cs = null;
                    cs = Bitmap.createBitmap(foreground.getWidth(), cameraBitmap.getHeight(), Bitmap.Config.ARGB_8888);

                    Canvas comboImage = new Canvas(cs);
                    comboImage.drawBitmap(cameraBitmap, 0f, 0f, null);
                    comboImage.drawBitmap(foreground, 0f, cameraBitmap.getHeight(), null);

                    FileOutputStream fos = null;
                    try {
                        fos = new FileOutputStream(file);
                        if (fos != null) {
                            cs.compress(Bitmap.CompressFormat.PNG, 90, fos);
                            fos.close();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

The camera image should become background, and foreground as top image. I've tried from
Combining 2 Images in Android using Canvas  but it didn't help me. Any idea.? Thanks

Body:
Merging Two Bitmap vertically  when one is large and second is small

 follow this method

 public Bitmap finalcombieimage(Bitmap c, Bitmap s) {
    Bitmap cs = null;
    DisplayMetrics metrics = getBaseContext().getResources().getDisplayMetrics();
    int width = metrics.widthPixels;
    int height = metrics.heightPixels;
    cs = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas comboImage = new Canvas(cs);
    Rect dest1 = new Rect(0, 0, width, height); // left,top,right,bottom
    comboImage.drawBitmap(c, null, dest1, null);
    Rect dest2 = new Rect(0, height-400 / 2, width, height);
    comboImage.drawBitmap(s, null, dest2, null);
    return cs;
}


问:
How can we hide the tableHeaderView and tableFooterView?
I have  two buttons which i add it in one in table-footer and other one in table-header,i know how to hide the headerview of the table using this codetable.tableHeaderView.hidden = YES;
but the problem is there is still space in the top portion of the table.That space is equal to the header-view size,but the view is hidden .It still has the space.How can we disable the table-header by removing this space.I hope you genius developers understand my question.Please help me.
Thanks in advance.

答:
```<code>//hidden sectionFooter

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:    (NSInteger)section {
    return 0.0;
}
</code>```


问:
how to set local time in project irrespective of server location
I have my project based in India and my hosting server located somewhere that is at a difference of -5:30 HRs from Indian time.

So my time being stored in database is coming as based on there timings. How can I rectify this in PHP so that the time actually gets stored on India.

I tried using date_default_timezone_set('Asia/Kolkata');

but still the time gets stored with a difference of -30mins to -45mins. What could be possible code fort his so that the time sets exactly according to Indian timings. Any advice will be very helpful.

答:
As you said your server is running at -5.30 hours from India, get the dates like this:</p>

```<code>date('d-m-Y H:i:s',strtotime('+330 minutes'));  // this adds 5.30 hours to the current time.
</code>```

Body:
As you said your server is running at -5.30 hours from India, get the dates like this:

date('d-m-Y H:i:s',strtotime('+330 minutes'));  // this adds 5.30 hours to the current time.


问:
How to make groups of symbols bold with Mathjax
I want to be able to make several symbols bold by grouping them within some sort of bolding command.  I can make a single symbol bold by using (for example)

```<code>\boldsymbol \phi
</code>```

but I want to be able to bold several symbols, something like:

```<code>{\boldsymbol \phi \vee \psi}
</code>```

This doesn't work.  I've tried \bf in a group as well, which Mathjax says it supports, but it doesn't.

How can I achieve this, I don't want to have to put \boldsymbol on every single symbol!

答: Use \boldsymbol{\phi \vee \psi}.  Note that \boldsymbol is a macro that takes an argument (like \mathbf{}), not a switch (like \bf).  Also, note that in TeX, \bf only affects certain symbols (basically, just the letters and numbers), and MathJax does the same.  So in TeX, as well as MathJax, {\bf \phi \vee \psi} will produce the same thing as \phi \vee \psi.

Body:
I want to be able to make several symbols bold by grouping them within some sort of bolding command.  I can make a single symbol bold by using (for example)

\boldsymbol \phi

but I want to be able to bold several symbols, something like:

{\boldsymbol \phi \vee \psi}

This doesn't work.  I've tried \bf in a group as well, which Mathjax says it supports, but it doesn't.

How can I achieve this, I don't want to have to put \boldsymbol on every single symbol!


问:
Find the the value of one field that matches the maximum value of data in another field
I'm trying to write a query that gets the value of one field that's associated with the maximum value of another field (or fields).  Let's say I have the following table of data:

```<code>OrderID CustomerID  OrderDate   LocationID
1       4           1/1/2001    1001
2       4           1/2/2001    1003
3       4           1/3/2001    1001
4       5           1/4/2001    1001
5       5           1/5/2001    1001
6       5           1/6/2001    1003
7       5           1/7/2001    1002
8       5           1/8/2001    1003
9       5           1/8/2001    1002
</code>```

Grouping by CustomerID, I want to get the maximum OrderDate and then the LocationID associated with whatever is the maximum OrderDate.  If there are several records that share the maximum order date, then take the LocationID associated with the maximum OrderID from among those records with the maximum date.

The final set of data should look like this:

```<code>CustomerID  OrderDate   LocationID
4           1/3/2001    1001
5           1/8/2001    1002
</code>```

I had been trying to write a query with lots of nested subqueries and ugly joins, but I'm not really getting anywhere.  What SQL do I need to write to help me get this result.

答:
```<code>SELECT
   C.Name,
   C.CustomerID,
   X.*
FROM
   Customers C
   CROSS APPLY (
      SELECT TOP 1 OrderDate, LocationID
      FROM Orders O
      WHERE C.CustomerID = O.CustomerID
      ORDER BY OrderDate Desc, OrderID Desc
   ) X
</code>```

If you will pull any columns from the Customers table, this will probably outperform other methods.

If not, then the Row_Number answer, pulling only from Orders, will probably be best. But if you restrict by Customer in any way, then the CROSS APPLY will again be best. Possibly by a big margin.

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to write a query that gets the value of one field that's associated with the maximum value of another field (or fields).  Let's say I have the following table of data:

OrderID CustomerID  OrderDate   LocationID
1       4           1/1/2001    1001
2       4           1/2/2001    1003
3       4           1/3/2001    1001
4       5           1/4/2001    1001
5       5           1/5/2001    1001
6       5           1/6/2001    1003
7       5           1/7/2001    1002
8       5           1/8/2001    1003
9       5           1/8/2001    1002

Grouping by CustomerID, I want to get the maximum OrderDate and then the LocationID associated with whatever is the maximum OrderDate.  If there are several records that share the maximum order date, then take the LocationID associated with the maximum OrderID from among those records with the maximum date.

The final set of data should look like this:

CustomerID  OrderDate   LocationID
4           1/3/2001    1001
5           1/8/2001    1002

I had been trying to write a query with lots of nested subqueries and ugly joins, but I'm not really getting anywhere.  What SQL do I need to write to help me get this result.

Body:
SELECT
   C.Name,
   C.CustomerID,
   X.*
FROM
   Customers C
   CROSS APPLY (
      SELECT TOP 1 OrderDate, LocationID
      FROM Orders O
      WHERE C.CustomerID = O.CustomerID
      ORDER BY OrderDate Desc, OrderID Desc
   ) X

If you will pull any columns from the Customers table, this will probably outperform other methods.

If not, then the Row_Number answer, pulling only from Orders, will probably be best. But if you restrict by Customer in any way, then the CROSS APPLY will again be best. Possibly by a big margin.


问:
Store a second-line output in a variable
I am making a little script to get users public/external IP address to cmd!
So it goes:

```<code>C:\...>nslookup myip.opendns.com resolver1.opendns.com | find /I "Address" > %temp%\_W___1.log

C:\...>set /p GPIPLOG=<%temp%\_W___1.log

C:\...>echo %gpiplog%
Address:  208.67.222.222

C:\...>type %temp%\_W___1.log
Address:  208.67.222.222
Address:  X.X.X.X

C:\...>echo %gpiplog:~2,50%
dress:  208.67.222.222
</code>```

I'm thinking that echo %gpiplog:~2,50% will jump to second line and show everything until it reaches 50 characters, but I'm wrong!

What I want:

```<code>C:\...>echo %gpiplog:~2,10,50%
X.X.X.X
</code>```

答:
@echo off
    cd %~dp0</p>

```<code>if "%~1"=="-h" goto :help
if "%~1"=="-help" goto :help
if "%~1"=="/?" goto :help

type nul > %temp%\_W___getpipData.log
type nul > %temp%\_W___getpipDataL.log
type nul > %temp%\_W___getpipDataN.log

.\nslookup.emod myip.opendns.com resolver1.opendns.com | find /I "Address" > "%temp%\_W___getpipDataN.log"
more +01 "%temp%\_W___getpipDataN.log" > "%temp%\_W___getpipDataL.log"
del /F /Q "%temp%\_W___getpipDataN.log"
type "%temp%\_W___getpipDataL.log" | find /I "Address" > "%temp%\_W___getpipData.log"
del /F /Q "%temp%\_W___getpipDataL.log"
set /p GPIPLOG=<"%temp%\_W___getpipData.log"
echo %GPIPLOG:~10,50%
set /p GPIPLOG=
del /F /Q "%temp%\_W___getpipData.log"
exit /B

:help
echo.getpip - Get Public IP
echo.
echo.Usage: getpip
exit /B
</code>```

Body:
I am making a little script to get users public/external IP address to cmd!
So it goes:

C:\...>nslookup myip.opendns.com resolver1.opendns.com | find /I "Address" > %temp%\_W___1.log

C:\...>set /p GPIPLOG=<%temp%\_W___1.log

C:\...>echo %gpiplog%
Address:  208.67.222.222

C:\...>type %temp%\_W___1.log
Address:  208.67.222.222
Address:  X.X.X.X

C:\...>echo %gpiplog:~2,50%
dress:  208.67.222.222

I'm thinking that echo %gpiplog:~2,50% will jump to second line and show everything until it reaches 50 characters, but I'm wrong!

What I want:

C:\...>echo %gpiplog:~2,10,50%
X.X.X.X

Body:
@echo off
    cd %~dp0

if "%~1"=="-h" goto :help
if "%~1"=="-help" goto :help
if "%~1"=="/?" goto :help

type nul > %temp%\_W___getpipData.log
type nul > %temp%\_W___getpipDataL.log
type nul > %temp%\_W___getpipDataN.log

.\nslookup.emod myip.opendns.com resolver1.opendns.com | find /I "Address" > "%temp%\_W___getpipDataN.log"
more +01 "%temp%\_W___getpipDataN.log" > "%temp%\_W___getpipDataL.log"
del /F /Q "%temp%\_W___getpipDataN.log"
type "%temp%\_W___getpipDataL.log" | find /I "Address" > "%temp%\_W___getpipData.log"
del /F /Q "%temp%\_W___getpipDataL.log"
set /p GPIPLOG=<"%temp%\_W___getpipData.log"
echo %GPIPLOG:~10,50%
set /p GPIPLOG=
del /F /Q "%temp%\_W___getpipData.log"
exit /B

:help
echo.getpip - Get Public IP
echo.
echo.Usage: getpip
exit /B

ContentLicense: CC BY-SA 4.0


问:
In fabric js, how to get the original image source from image object
In fabric js, I am trying to get the original source of an image, when I use the getElement() and getSrc() methods it shows the correct output, but after applying some image filters the same methods
return the new image src (encoded image data) not the original image source.how can I get the original image source after applying the image filters.</p>

答:
You can use getSrc() method:

```<code>var someUrlOrDataUrl = image.getSrc();
</code>```

Docs: http://fabricjs.com/docs/fabric.Image.html#getSrc

Body:
You can use getSrc() method:

var someUrlOrDataUrl = image.getSrc();

Docs: http://fabricjs.com/docs/fabric.Image.html#getSrc


问:
Error : Metadata contains reference that cannot be resolved: Dynamics 365 online
I'm trying to create web service (ASMX) to connect with the D365.
But when I'm trying to connect to the D365, I got this error message :-

I tried to change the DLL to the latest version but still gave me same error. For more details about my code :-

```<code>public class CRMConnection
{
    public OrganizationServiceProxy service;
    private ClientCredentials credentials;
    private String UserName = WebConfigurationManager.AppSettings["CRM_Username"];
    private String Password = WebConfigurationManager.AppSettings["CRM_Password"];

    public CRMConnection()
    {
        Uri OrganizationUri = new Uri(WebConfigurationManager.AppSettings["CRM_URL"]);

        credentials = new ClientCredentials();
        credentials.UserName.UserName = UserName;
        credentials.UserName.Password = Password;

        service = new OrganizationServiceProxy(OrganizationUri, null, credentials, null);
    }
}
</code>```

Error comes in this line :

```<code>service = new OrganizationServiceProxy(OrganizationUri, null, credentials, null);
</code>```

My project Target Framework is 4.5.2

Note : I used same code with other project (Windows Application) and it's working fine.

Your help in this regard will be highly appreciated!

Thanks ..

答: This case has been resolved. The issue was because of the proxy settings .</p>

Body:
I'm trying to create web service (ASMX) to connect with the D365.
But when I'm trying to connect to the D365, I got this error message :-

I tried to change the DLL to the latest version but still gave me same error. For more details about my code :-

public class CRMConnection
{
    public OrganizationServiceProxy service;
    private ClientCredentials credentials;
    private String UserName = WebConfigurationManager.AppSettings["CRM_Username"];
    private String Password = WebConfigurationManager.AppSettings["CRM_Password"];

    public CRMConnection()
    {
        Uri OrganizationUri = new Uri(WebConfigurationManager.AppSettings["CRM_URL"]);

        credentials = new ClientCredentials();
        credentials.UserName.UserName = UserName;
        credentials.UserName.Password = Password;

        service = new OrganizationServiceProxy(OrganizationUri, null, credentials, null);
    }
}

Error comes in this line :

service = new OrganizationServiceProxy(OrganizationUri, null, credentials, null);

My project Target Framework is 4.5.2

Note : I used same code with other project (Windows Application) and it's working fine.

Your help in this regard will be highly appreciated!

Thanks ..


问:
Vagrant : An AMI must be configured via "ami" (region: #{region})
I got an error as below when run vagrant command,

```<code> # vagrant up --provider=aws
</code>```

There are errors in the configuration of this machine. Please fix
the following errors and try again:

AWS Provider:
* An AMI must be configured via "ami" (region: #{region})

I'm using Vagrant 2.0.1 with vagrant-aws 0.7.2

Vagrant file:

```<code>Vagrant.configure("2") do |config|
    require 'vagrant-aws'
    Vagrant.configure('2') do |config|
        config.vm.box = 'Vagarent'
        config.vm.provider 'aws' do |aws, override|
        aws.access_key_id = "xxxxxxxxxxxxxxxxxx"
        aws.secret_access_key = "xxxxxxxxxxxxxxxxxxxxxxxx"
        aws.keypair_name = 'ssh-keypair-name'
        aws.instance_type = "t2.micro"
        aws.region = 'us-west-2a'
        aws.ami = 'ami-1122298f0'
        aws.security_groups = ['default']
        override.ssh.username = 'ubuntu'
        override.ssh.private_key_path = '~/.ssh/ssh-keypair-file'
      end
    end
</code>```

How to solve it?

答:
us-west-2a is not a valid region name, see https://docs.aws.amazon.com/general/latest/gr/rande.html#ec2_region for the full list of available region and end-points.

If you AMI is location in US West (Oregon), then you need to replace with us-west-2 in your Vagrantfile

Body:
I got an error as below when run vagrant command,

 # vagrant up --provider=aws

There are errors in the configuration of this machine. Please fix
the following errors and try again:

AWS Provider:
* An AMI must be configured via "ami" (region: #{region})

I'm using Vagrant 2.0.1 with vagrant-aws 0.7.2

Vagrant file:

Vagrant.configure("2") do |config|
    require 'vagrant-aws'
    Vagrant.configure('2') do |config|
        config.vm.box = 'Vagarent'
        config.vm.provider 'aws' do |aws, override|
        aws.access_key_id = "xxxxxxxxxxxxxxxxxx"
        aws.secret_access_key = "xxxxxxxxxxxxxxxxxxxxxxxx"
        aws.keypair_name = 'ssh-keypair-name'
        aws.instance_type = "t2.micro"
        aws.region = 'us-west-2a'
        aws.ami = 'ami-1122298f0'
        aws.security_groups = ['default']
        override.ssh.username = 'ubuntu'
        override.ssh.private_key_path = '~/.ssh/ssh-keypair-file'
      end
    end

How to solve it?


问:
How to use Enum in Camel Route?
I have the following route:

```<code>.choise()
   .when()
      .simple("${body.messageType} == 105")
          .to(...)
   .when()
      .simple("${body.messageType} == 106")
          .to(...)
</code>```

I want to use this enum to compare.

```<code>  package myPackage;

  public enum Code {
     CODE_A("105"),
     CODE_B("106")

     private String value;

    Code(String value) {
        this.value = value;
    }

    public String value() {
        return value;
    }
}
</code>```

I tried to do something like this, but it doesn't works..

```<code>.simple("${body.messageType} == ${type:myPackage.Code.CODE_A.value()}")
</code>```

Any idea to solve this problem?

答:
My simple syntax looks like:

```<code>//one value
simple(String.format("${body.key} == '%1s'", Code.CODE_A.value())
// multiple values using 'in' operator
simple(String.format("${body.key} in '%1s,%2s'", Code.CODE_A.value(), Code.CODE_B.value())
</code>```

I like the use of String.format() instead of concatenating all parts as it makes the simple statement more readable

Title: How to use Enum in Camel Route?

Body:
I have the following route:

.choise()
   .when()
      .simple("${body.messageType} == 105")
          .to(...)
   .when()
      .simple("${body.messageType} == 106")
          .to(...)

I want to use this enum to compare.

  package myPackage;

  public enum Code {
     CODE_A("105"),
     CODE_B("106")

     private String value;

    Code(String value) {
        this.value = value;
    }

    public String value() {
        return value;
    }
}

I tried to do something like this, but it doesn't works..

.simple("${body.messageType} == ${type:myPackage.Code.CODE_A.value()}")

Any idea to solve this problem?

Body:
My simple syntax looks like:

//one value
simple(String.format("${body.key} == '%1s'", Code.CODE_A.value())
// multiple values using 'in' operator
simple(String.format("${body.key} in '%1s,%2s'", Code.CODE_A.value(), Code.CODE_B.value())

I like the use of String.format() instead of concatenating all parts as it makes the simple statement more readable


问:
Failed to load PDF document using aws-sdk in Node.js
I have a problem when uploading pdf files to S3.

I have no problems creating pdf files using PDFkit and storing them locally (I can view them in my browser).

But when I try to upload them to my S3 storage, I get this error Failed to load PDF document. when opening a pdf in my browser. You can check it out:
https://s3.us-east-2.amazonaws.com/pdf-twitter-bucket/twitter/HvkH98YA0p.pdf

```<code>        fs.readFile('../pdf/' + fileName, 'utf8', function (err, contents) {
          const buf = new Buffer(contents, 'base64');
          // define params
          const params = {
            Bucket: 'pdf-twitter-bucket',
            Key: 'twitter/' + fileName,
            Body: buf,
            ContentType: 'application/pdf',
            ACL: 'public-read'
          };

          s3bucket.upload(params, function (err) {
            if (err) {
              console.log('error in callback');
              console.log(err);
            }
            res.end(
              'https://s3.us-east-2.amazonaws.com/pdf-twitter-bucket/twitter/' +
              fileName
            ); // send the link to s3
          });
        });
</code>```

I've tried many options:
1) using Buffeer and not using Buffer
2) I have no problems uploading .txt files
3) I've even tried passing a string as a Body value

Before writing this question I've carried out a small research and found similar problems:

https://github.com/VeliovGroup/Meteor-Files/issues/406

Unfortunately, it didn't help me much...

答:
I've had the same issue with S3 upload. I couldn't open the PDF and it was just a few bytes in size (instead of a few KB). I think the problem was that I didn't wait for the write stream to complete.

This works for me now:

document.pipe(fs.createWriteStream(fileName));
document.end();
document.on('end', function () {
  fs.readFile(fileName, function (err, data) {
    if (err) {
      console.log(err);
    }
    s3.upload({
      Bucket: s3Bucket,
      Key: fileName,
      Body: data,
      ContentType: 'application/pdf',
      acl: 'private',
      contentDisposition: 'attachment',
      ServerSideEncryption: 'AES256'
    }, function(err, data) {
      if (err) {
        console.log(err);
      }
    });
  });
});```

Hope this helps!

Body:
I have a problem when uploading pdf files to S3.

I have no problems creating pdf files using PDFkit and storing them locally (I can view them in my browser).

But when I try to upload them to my S3 storage, I get this error Failed to load PDF document. when opening a pdf in my browser. You can check it out:
https://s3.us-east-2.amazonaws.com/pdf-twitter-bucket/twitter/HvkH98YA0p.pdf

        fs.readFile('../pdf/' + fileName, 'utf8', function (err, contents) {
          const buf = new Buffer(contents, 'base64');
          // define params
          const params = {
            Bucket: 'pdf-twitter-bucket',
            Key: 'twitter/' + fileName,
            Body: buf,
            ContentType: 'application/pdf',
            ACL: 'public-read'
          };

          s3bucket.upload(params, function (err) {
            if (err) {
              console.log('error in callback');
              console.log(err);
            }
            res.end(
              'https://s3.us-east-2.amazonaws.com/pdf-twitter-bucket/twitter/' +
              fileName
            ); // send the link to s3
          });
        });

I've tried many options:
1) using Buffeer and not using Buffer
2) I have no problems uploading .txt files
3) I've even tried passing a string as a Body value

Before writing this question I've carried out a small research and found similar problems:

https://github.com/VeliovGroup/Meteor-Files/issues/406

Unfortunately, it didn't help me much...

Body:
I've had the same issue with S3 upload. I couldn't open the PDF and it was just a few bytes in size (instead of a few KB). I think the problem was that I didn't wait for the write stream to complete.

This works for me now:

document.pipe(fs.createWriteStream(fileName));
document.end();
document.on('end', function () {
  fs.readFile(fileName, function (err, data) {
    if (err) {
      console.log(err);
    }
    s3.upload({
      Bucket: s3Bucket,
      Key: fileName,
      Body: data,
      ContentType: 'application/pdf',
      acl: 'private',
      contentDisposition: 'attachment',
      ServerSideEncryption: 'AES256'
    }, function(err, data) {
      if (err) {
        console.log(err);
      }
    });
  });
});

Hope this helps!


问:
Does Microsoft BOT Framework allows to develop interactive UIs?
I have a requirement to implement some interactive UIs using Microsoft Bot Framework for Cortana Channel but I have not found any way to implement this. I want to apply styles on buttons and importantly use graphs & charts (like web dashboard) on Cortana.</p>

答:
Indeed, you can use Hero card, adaptive cards, thumbnail cards, receipt cards etc.

below is the example for your reference.

public Task StartAsync(IDialogContext context)
        {
            context.Wait(MessageReceivedAsync);

```<code>        return Task.CompletedTask;
    }
    public virtual async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> result)
    {
        var reply = context.MakeMessage();

        reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
        reply.Attachments = GetCardsAttachments();

        await context.PostAsync(reply);

        context.Wait(this.MessageReceivedAsync);
    }

    private static IList<Attachment> GetCardsAttachments()
    {
        return new List<Attachment>()
        {
            GetHeroCard(
                "Add a webpage",
                "",
                "",
                new CardImage(url: "https://cdn.dribbble.com/users/22691/screenshots/1958250/attachments/340010/Button_800x600.gif?sz=328"),
                new CardAction(ActionTypes.ImBack, "Add a webpage", value: "Add a webpage")),
            GetHeroCard(
                "delete a webpage",
                "",
                "",
                new CardImage(url: "https://cdn.dribbble.com/users/22691/screenshots/1958250/attachments/340010/Button_800x600.gif?sz=328"),
                new CardAction(ActionTypes.ImBack, "delete a webpage", value: "delete a webpage")),
            GetHeroCard(
                "Display help",
                "",
                "",
                new CardImage(url: "https://cdn.dribbble.com/users/22691/screenshots/1958250/attachments/340010/Button_800x600.gif?sz=328"),
                new CardAction(ActionTypes.ImBack, "Display help", value: "Display help")),
            GetHeroCard(
                "etc",
                "",
                "",
                new CardImage(url: "https://cdn.dribbble.com/users/22691/screenshots/1958250/attachments/340010/Button_800x600.gif?sz=328"),
                new CardAction(ActionTypes.ImBack, "etc", value: "etc")),

        };
    }

    private static Attachment GetHeroCard(string title, string subtitle, string text, CardImage cardImage, CardAction cardAction)
    {
        var heroCard = new HeroCard
        {
            Title = title,
            Subtitle = subtitle,
            Text = text,
            Images = new List<CardImage>() { cardImage },
            Buttons = new List<CardAction>() { cardAction },
        };

        return heroCard.ToAttachment();
    }
</code>```

Screen shot for your reference

Body:
Indeed, you can use Hero card, adaptive cards, thumbnail cards, receipt cards etc.

below is the example for your reference.

public Task StartAsync(IDialogContext context)
        {
            context.Wait(MessageReceivedAsync);

        return Task.CompletedTask;
    }
    public virtual async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> result)
    {
        var reply = context.MakeMessage();

        reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
        reply.Attachments = GetCardsAttachments();

        await context.PostAsync(reply);

        context.Wait(this.MessageReceivedAsync);
    }

    private static IList<Attachment> GetCardsAttachments()
    {
        return new List<Attachment>()
        {
            GetHeroCard(
                "Add a webpage",
                "",
                "",
                new CardImage(url: "https://cdn.dribbble.com/users/22691/screenshots/1958250/attachments/340010/Button_800x600.gif?sz=328"),
                new CardAction(ActionTypes.ImBack, "Add a webpage", value: "Add a webpage")),
            GetHeroCard(
                "delete a webpage",
                "",
                "",
                new CardImage(url: "https://cdn.dribbble.com/users/22691/screenshots/1958250/attachments/340010/Button_800x600.gif?sz=328"),
                new CardAction(ActionTypes.ImBack, "delete a webpage", value: "delete a webpage")),
            GetHeroCard(
                "Display help",
                "",
                "",
                new CardImage(url: "https://cdn.dribbble.com/users/22691/screenshots/1958250/attachments/340010/Button_800x600.gif?sz=328"),
                new CardAction(ActionTypes.ImBack, "Display help", value: "Display help")),
            GetHeroCard(
                "etc",
                "",
                "",
                new CardImage(url: "https://cdn.dribbble.com/users/22691/screenshots/1958250/attachments/340010/Button_800x600.gif?sz=328"),
                new CardAction(ActionTypes.ImBack, "etc", value: "etc")),

        };
    }

    private static Attachment GetHeroCard(string title, string subtitle, string text, CardImage cardImage, CardAction cardAction)
    {
        var heroCard = new HeroCard
        {
            Title = title,
            Subtitle = subtitle,
            Text = text,
            Images = new List<CardImage>() { cardImage },
            Buttons = new List<CardAction>() { cardAction },
        };

        return heroCard.ToAttachment();
    }

Screen shot for your reference


问:
Can the intmax_t hold size_t?
Can the intmax_t hold size_t maximum decimal number?
And what size type in printf  have a biggest priority uintmax_t/intmax_t or size_t (ex. if i write printf("%zjd", x))? </p>

答:
No, since size_t is unsigned that risks dropping one bit.

I don't think you understand how printf() works, you can have "an optional length modifier" but not more than one.

Title: Can the intmax_t hold size_t?


问:
Is it possible to skip license agreement page when splunk starts on first time in docker container?
I have created a Dockerfile when the container builds during that time I need to create multiple login users on backside of Splunk.

I am getting splunk agreement issue unable to skip/accept agreement on build container as shown below.

Dockerfile

```<code>FROM splunk/splunk:latest
ENV SPLUNK_HOME /opt/splunk
RUN apt-get update && apt-get install -y wget
COPY ./splunk-launch.conf /opt/splunk/etc/splunk-launch.conf
COPY ./splunk.license /opt/splunk/etc/licenses/enterprise/splunk.license
COPY ./My-app1 / /opt/splunk/etc/apps/My-app1
COPY ./My-app2 /opt/splunk/etc/apps/My-app2
COPY ./My-app3 /opt/splunk/etc/apps/My-app3
COPY ./splunk_user.sh /opt/splunk/bin/splunk_user.sh
RUN chmod +x /opt/splunk/bin/splunk_user.sh
RUN chown -R splunk:splunk /opt/splunk/bin/splunk_user.sh
EXPOSE 8000/tcp 8089/tcp 8191/tcp 9997/tcp 1514 8088/tcp
VOLUME [ “/opt/splunk/etc”, “/opt/splunk/var” ]
WORKDIR /opt/splunk/bin
CMD [“./splunk_user.sh”]
</code>```

splunk_user.sh

```<code>./splunk add user pradeep -password passwd123 -role admin -email pradeep@gmail.com -full-name Pradeep -auth admin:changeme
./splunk add user sankar -password passwd123 -role admin -email sankar@gmail.com -full-name Sankar -auth admin:changeme
</code>```

Error

答:
From the image readme, you need to run the image with:

```<code>-e "SPLUNK_START_ARGS=--accept-license"
</code>```

In your Dockerfile, that would be the equivalent of:

```<code>ENV SPLUNK_START_ARGS=--accept-license
</code>```

This flag gets passed to the splunk command in their entrypoint.sh:

```<code> sudo -HEu ${SPLUNK_USER} ${SPLUNK_HOME}/bin/splunk start ${SPLUNK_START_ARGS}
</code>```

Body:
I have created a Dockerfile when the container builds during that time I need to create multiple login users on backside of Splunk.

I am getting splunk agreement issue unable to skip/accept agreement on build container as shown below.

Dockerfile

FROM splunk/splunk:latest
ENV SPLUNK_HOME /opt/splunk
RUN apt-get update && apt-get install -y wget
COPY ./splunk-launch.conf /opt/splunk/etc/splunk-launch.conf
COPY ./splunk.license /opt/splunk/etc/licenses/enterprise/splunk.license
COPY ./My-app1 / /opt/splunk/etc/apps/My-app1
COPY ./My-app2 /opt/splunk/etc/apps/My-app2
COPY ./My-app3 /opt/splunk/etc/apps/My-app3
COPY ./splunk_user.sh /opt/splunk/bin/splunk_user.sh
RUN chmod +x /opt/splunk/bin/splunk_user.sh
RUN chown -R splunk:splunk /opt/splunk/bin/splunk_user.sh
EXPOSE 8000/tcp 8089/tcp 8191/tcp 9997/tcp 1514 8088/tcp
VOLUME [ “/opt/splunk/etc”, “/opt/splunk/var” ]
WORKDIR /opt/splunk/bin
CMD [“./splunk_user.sh”]

splunk_user.sh

./splunk add user pradeep -password passwd123 -role admin -email pradeep@gmail.com -full-name Pradeep -auth admin:changeme
./splunk add user sankar -password passwd123 -role admin -email sankar@gmail.com -full-name Sankar -auth admin:changeme

Error

Body:
From the image readme, you need to run the image with:

-e "SPLUNK_START_ARGS=--accept-license"

In your Dockerfile, that would be the equivalent of:

ENV SPLUNK_START_ARGS=--accept-license

This flag gets passed to the splunk command in their entrypoint.sh:

 sudo -HEu ${SPLUNK_USER} ${SPLUNK_HOME}/bin/splunk start ${SPLUNK_START_ARGS}