问:
Dialogflow html/js card json value v1
I am trying to access the card json value, to no avail.

In my scenario, I am asking the bot about "weather in London" and it replies back with "It is currently 9 degrees celcius in London." via the webhook.

Which is correct and dynamic.

However, I am trying to also pass the values to a card too.

In the json reply, I do get the card as so

```<code>{
  "id": "REMOVED",
  "timestamp": "2017-12-05T11:10:52.033Z",
  "lang": "en",
  "result": {
    "source": "agent",
    "resolvedQuery": "weather in london",
    "action": "sayWeather",
    "actionIncomplete": false,
    "parameters": {
      "geo-city": "London"
    },
    "contexts": [],
    "metadata": {
      "intentId": "REMOVED",
      "webhookUsed": "true",
      "webhookForSlotFillingUsed": "false",
      "webhookResponseTime": 626,
      "intentName": "Weather"
    },
    "fulfillment": {
      "speech": "It is currently 9 degrees celcius in London.",
      "source": "agent",
      "displayText": "It is currently 9 degrees celcius in London.",
      "messages": [
        {
          "type": 0,
          "speech": "It is currently 9 degrees celcius in London."
        }
      ],
      "data": {
        "items": [
          {
            "simpleResponse": {
              "textToSpeech": "This is the first simple response for a basic card"
            }
          },
          {
            "basicCard": {
              "title": "Title: this is a title",
              "formattedText": "This is a basic card.  Text in a\n      basic card can include \"quotes\" and most other unicode characters\n      including emoji .  Basic cards also support some markdown\n      formatting like *emphasis* or _italics_, **strong** or __bold__,\n      and ***bold itallic*** or ___strong emphasis___ as well as other things\n      like line  \nbreaks",
              "subtitle": "This is a subtitle",
              "image": {
                "url": "https://developers.google.com/actions/images/badges/XPM_BADGING_GoogleAssistant_VER.png",
                "accessibilityText": "Image alternate text"
              },
              "buttons": [
                {
                  "title": "This is a button",
                  "openUrlAction": {
                    "url": "https://assistant.google.com/"
                  }
                }
              ]
            }
          },
          {
            "simpleResponse": {
              "textToSpeech": "This is the 2nd simple response ",
              "displayText": "This is the 2nd simple response"
            }
          }
        ]
      }
    },
    "score": 1
  },
  "status": {
    "code": 200,
    "errorType": "success",
    "webhookTimedOut": false
  },

  "sessionId": "REMOVED"
}
</code>```

Accessing the value of speech using data.result.fulfillment.speech works fine.

However, when using data.result.fulfillment.data.items.basicCard.image.url it just doesnt work. And if I go up several levels, I do get:

[object Object]

Your help is appreciated.

答:
The items attribute is a list and not an object.  As such, you'll have to use a numerical index to retrive the data.  In the example you provided the index of the basicCard object is second so your code should look something like this:

data.result.fulfillment.data.items[1].basicCard.image.url

Notice the [1] after items.

Bear in mind that if the order of this list changes you may no longer be retrieving a basicCard object so you may want to add some checking to make sure you're retrieving the data you want.

Title: Dialogflow html/js card json value v1

Body:
I am trying to access the card json value, to no avail.

In my scenario, I am asking the bot about "weather in London" and it replies back with "It is currently 9 degrees celcius in London." via the webhook.

Which is correct and dynamic.

However, I am trying to also pass the values to a card too.

In the json reply, I do get the card as so

{
  "id": "REMOVED",
  "timestamp": "2017-12-05T11:10:52.033Z",
  "lang": "en",
  "result": {
    "source": "agent",
    "resolvedQuery": "weather in london",
    "action": "sayWeather",
    "actionIncomplete": false,
    "parameters": {
      "geo-city": "London"
    },
    "contexts": [],
    "metadata": {
      "intentId": "REMOVED",
      "webhookUsed": "true",
      "webhookForSlotFillingUsed": "false",
      "webhookResponseTime": 626,
      "intentName": "Weather"
    },
    "fulfillment": {
      "speech": "It is currently 9 degrees celcius in London.",
      "source": "agent",
      "displayText": "It is currently 9 degrees celcius in London.",
      "messages": [
        {
          "type": 0,
          "speech": "It is currently 9 degrees celcius in London."
        }
      ],
      "data": {
        "items": [
          {
            "simpleResponse": {
              "textToSpeech": "This is the first simple response for a basic card"
            }
          },
          {
            "basicCard": {
              "title": "Title: this is a title",
              "formattedText": "This is a basic card.  Text in a\n      basic card can include \"quotes\" and most other unicode characters\n      including emoji .  Basic cards also support some markdown\n      formatting like *emphasis* or _italics_, **strong** or __bold__,\n      and ***bold itallic*** or ___strong emphasis___ as well as other things\n      like line  \nbreaks",
              "subtitle": "This is a subtitle",
              "image": {
                "url": "https://developers.google.com/actions/images/badges/XPM_BADGING_GoogleAssistant_VER.png",
                "accessibilityText": "Image alternate text"
              },
              "buttons": [
                {
                  "title": "This is a button",
                  "openUrlAction": {
                    "url": "https://assistant.google.com/"
                  }
                }
              ]
            }
          },
          {
            "simpleResponse": {
              "textToSpeech": "This is the 2nd simple response ",
              "displayText": "This is the 2nd simple response"
            }
          }
        ]
      }
    },
    "score": 1
  },
  "status": {
    "code": 200,
    "errorType": "success",
    "webhookTimedOut": false
  },

  "sessionId": "REMOVED"
}

Accessing the value of speech using data.result.fulfillment.speech works fine.

However, when using data.result.fulfillment.data.items.basicCard.image.url it just doesnt work. And if I go up several levels, I do get:

[object Object]

Your help is appreciated.


来源: stackexchange

问:
How to use Where operator in Linq
```<code>SomeObject.Where(p => FunctionOn(p.I));
<<>>
public bool FunctionOn(int i){
    return (i == 1);}
<<>>
error message : The method FunctionOn is not supported
</code>```

but why when I use number instead of parameter it works fine ?

```<code>SomeObject.Where(p => FunctionOn(1));
</code>```

I was wondering if there is a way to implement this code in Linq , because it gives me an error .
 Thank you .

答:
This might work, Try :

```<code>SomeObject.AsEnumerable().Where(p => FunctionOn(p.I))
</code>```

It would work for Linq-To-Entities and Linq-To-SQL too!

Why! How?

Because like stakx explains. IQueryable stores your expression. If you check out the docs for IQueryable it has an Expression property, this stores the Linq you write in your code, and then a LinqProvider then translates it into the right thing, in your case that would be MongoDB syntax/SQL IDK? For linq-to-sql this would turn into an T-SQL expression. So there is no SQL-way to write FunctionOn(). Can it magically call your function written in C# from SQL? Nope!

Now, IEnumerable is an object collection in memory. When you say AsEnumerable() you get the objects in memory, then when you do Where(x=> func(x)) Linq-To-Objects can handle it no problem.

Like @Will on the comments rightly says, this gets every single object into memory and then queries it. At times it may not be what you want to do, but I wanted you to understand why your code doesn't work and also if you needed there is sorta a workaround

Hope it gave you the same insight I discovered a few weeks ago while watching lots of channel9 Linq Videos. =)

ContentLicense: CC BY-SA 2.5

Title: How to use Where operator in Linq

Body:
SomeObject.Where(p => FunctionOn(p.I));
<<>>
public bool FunctionOn(int i){
    return (i == 1);}
<<>>
error message : The method FunctionOn is not supported

but why when I use number instead of parameter it works fine ?

SomeObject.Where(p => FunctionOn(1));

I was wondering if there is a way to implement this code in Linq , because it gives me an error .
 Thank you .

Body:
This might work, Try :

SomeObject.AsEnumerable().Where(p => FunctionOn(p.I))

It would work for Linq-To-Entities and Linq-To-SQL too!

Why! How?

Because like stakx explains. IQueryable stores your expression. If you check out the docs for IQueryable it has an Expression property, this stores the Linq you write in your code, and then a LinqProvider then translates it into the right thing, in your case that would be MongoDB syntax/SQL IDK? For linq-to-sql this would turn into an T-SQL expression. So there is no SQL-way to write FunctionOn(). Can it magically call your function written in C# from SQL? Nope!

Now, IEnumerable is an object collection in memory. When you say AsEnumerable() you get the objects in memory, then when you do Where(x=> func(x)) Linq-To-Objects can handle it no problem.

Like @Will on the comments rightly says, this gets every single object into memory and then queries it. At times it may not be what you want to do, but I wanted you to understand why your code doesn't work and also if you needed there is sorta a workaround

Hope it gave you the same insight I discovered a few weeks ago while watching lots of channel9 Linq Videos. =)


问:
Lambda Cloudformation Encountered unsupported property Value Error
The cloudformation is failing when  trying to create lambda function with the error message "Encountered unsupported property Value"

There is no reference to the unsupported value and I couldn't find any incorrect value. All the values were used from AWS lambda cloud formation template only.

Also for the Dev I get the error indicating security group is string type but for QA doesn't get the error.

Can you please check point out what's causing unsupported value error and how to resolve security group related error for Dev environment.

```<code>{
    "AWSTemplateFormatVersion": "2010-09-09",
    "Description": "Create Lambda Function For abc",
    "Parameters": {
        "ID" : {
            "Description" : "OwnerContact Value",
            "Type" : "String",
            "Default" : "abc@xyz.com"
        },
        "abcVPCNAME": {
          "Description": "abc VPC NAME",
          "Type": "String",
          "Default": "abc-e-dev",
          "AllowedValues": [
              "abc-e-dev",
              "abc-e-qa",
              "abc-e-prod",
              "abc-w-qa",
              "abc-w-prod",
            ]
        }
    },
   "Mappings" : {
        "params" : {
            "abc-e-dev" : {
                "S3bukcet" : "abc-dev-east",
                "S3Key" : "/lambda/abc_S3.zip",
                "TicketSNS" : "arn:aws:sns:us-east-1:212:abc",
                "HOSTNAME" : "abc.com",
                "ROLENAME" : "arn:aws:iam::454:role/Lambda-role",
                "Subnets" : ["subnet-1","subnet-2","subnet-3"],
                "SecGrps" : ["sg-1","sg-2"],
                "TAG1" : "xyz",
                "TAG2" : "123"
            },
            "abc-e-qa" : {
                "S3bukcet" : "abc-qa-east",
                "S3Key" : "/lambda/abc_S3.zip",
                "TicketSNS" : "arn:aws:sns:us-east-1:212:abc",
                "HOSTNAME" : "xyz.com",
                "ROLENAME" : "arn:aws:iam::454:role/Lambda-role",
                "Subnets" : ["subnet-1","subnet-2","subnet-3"],
                "SecGrps" : "sg-123",
                "TAG1" : "xyz",
                "TAG2" : "123"
            },
        }
    },
    "Resources": {
      "abcS3Get": {
        "Type" : "AWS::Lambda::Function",
        "Properties" : {
          "Code" : {
            "S3Bucket" : { "Fn::FindInMap" : [ "params", {"Ref":"abcVPCNAME"}, "S3bukcet" ]},
            "S3Key" : { "Fn::FindInMap" : [ "params", {"Ref":"abcVPCNAME"}, "S3Key" ]}
          },
          "DeadLetterConfig" : { "Fn::FindInMap" : [ "params", {"Ref":"abcVPCNAME"}, "TicketSNS" ]},
          "Description" : "abc Lambda Function For File Pickup",
          "Environment" : {
            "Key": "abcHOST",
            "Value": { "Fn::FindInMap" : [ "params", {"Ref":"abcVPCNAME"}, "HOSTNAME" ]}
          },
          "FunctionName" : "abc-S3-Pickup",
          "Handler" : "abc_S3_Get.lambda_handler",
          "MemorySize" : 128,
          "Role" : { "Fn::FindInMap" : [ "params", {"Ref":"abcVPCNAME"}, "ROLENAME" ]},
          "Runtime" : "python2.7",
          "Timeout" : 3,
          "VpcConfig" : {
            "SecurityGroupIds" : { "Fn::FindInMap" : [ "params", {"Ref":"abcVPCNAME"}, "SecGrps" ]},
            "SubnetIds" : { "Fn::FindInMap" : [ "params", {"Ref":"abcVPCNAME"}, "Subnets" ]}
          },
          "Tags" : [{
            "Key" : "KEY1",
            "Value" : { "Fn::FindInMap" : [ "params", {"Ref":"abcVPCNAME"}, "TAG1" ]}
            },
            {
            "Key" : "KEY2",
            "Value" : { "Fn::FindInMap" : [ "params", {"Ref":"abcVPCNAME"}, "TAG2" ]}
            },
            {
            "Key" : "KEY3",
            "Value" : {"Ref":"ID"}
            }
          ]
        }
      }
    }
}
</code>```

答:
Found the resolution. It was issue with Value parameter in Environment which is incorrect.

Corrected to below and resolved the issue.

```<code>"Environment" : {
            "Variables" : {
              "abcHOST":  {
                "Fn::FindInMap" : [ "params", {"Ref":"abcVPCNAME"}, "HOSTNAME" ]
              }
            }
</code>```

There were couple of other issues as well.

```<code>"S3Key" : "/lambda/abc_S3.zip",
</code>```

should be

```<code>"S3Key" : "lambda/abc_S3.zip",
</code>```

Also Deadletterconfig parameter needs to be altered as well.

```<code>Current Value:

"DeadLetterConfig" : { "Fn::FindInMap" : [ "params", {"Ref":"abcVPCNAME"}, "TicketSNS" ]},

Correct Value:

"DeadLetterConfig" : {
            "TargetArn" : { "Fn::FindInMap" : [ "params", {"Ref":"abcVPCNAME"}, "TicketSNS" ]}
            },
</code>```

The CFT started working after all of the above changes.

ContentLicense: CC BY-SA 3.0

Body:
The cloudformation is failing when  trying to create lambda function with the error message "Encountered unsupported property Value"

There is no reference to the unsupported value and I couldn't find any incorrect value. All the values were used from AWS lambda cloud formation template only.

Also for the Dev I get the error indicating security group is string type but for QA doesn't get the error.

Can you please check point out what's causing unsupported value error and how to resolve security group related error for Dev environment.

{
    "AWSTemplateFormatVersion": "2010-09-09",
    "Description": "Create Lambda Function For abc",
    "Parameters": {
        "ID" : {
            "Description" : "OwnerContact Value",
            "Type" : "String",
            "Default" : "abc@xyz.com"
        },
        "abcVPCNAME": {
          "Description": "abc VPC NAME",
          "Type": "String",
          "Default": "abc-e-dev",
          "AllowedValues": [
              "abc-e-dev",
              "abc-e-qa",
              "abc-e-prod",
              "abc-w-qa",
              "abc-w-prod",
            ]
        }
    },
   "Mappings" : {
        "params" : {
            "abc-e-dev" : {
                "S3bukcet" : "abc-dev-east",
                "S3Key" : "/lambda/abc_S3.zip",
                "TicketSNS" : "arn:aws:sns:us-east-1:212:abc",
                "HOSTNAME" : "abc.com",
                "ROLENAME" : "arn:aws:iam::454:role/Lambda-role",
                "Subnets" : ["subnet-1","subnet-2","subnet-3"],
                "SecGrps" : ["sg-1","sg-2"],
                "TAG1" : "xyz",
                "TAG2" : "123"
            },
            "abc-e-qa" : {
                "S3bukcet" : "abc-qa-east",
                "S3Key" : "/lambda/abc_S3.zip",
                "TicketSNS" : "arn:aws:sns:us-east-1:212:abc",
                "HOSTNAME" : "xyz.com",
                "ROLENAME" : "arn:aws:iam::454:role/Lambda-role",
                "Subnets" : ["subnet-1","subnet-2","subnet-3"],
                "SecGrps" : "sg-123",
                "TAG1" : "xyz",
                "TAG2" : "123"
            },
        }
    },
    "Resources": {
      "abcS3Get": {
        "Type" : "AWS::Lambda::Function",
        "Properties" : {
          "Code" : {
            "S3Bucket" : { "Fn::FindInMap" : [ "params", {"Ref":"abcVPCNAME"}, "S3bukcet" ]},
            "S3Key" : { "Fn::FindInMap" : [ "params", {"Ref":"abcVPCNAME"}, "S3Key" ]}
          },
          "DeadLetterConfig" : { "Fn::FindInMap" : [ "params", {"Ref":"abcVPCNAME"}, "TicketSNS" ]},
          "Description" : "abc Lambda Function For File Pickup",
          "Environment" : {
            "Key": "abcHOST",
            "Value": { "Fn::FindInMap" : [ "params", {"Ref":"abcVPCNAME"}, "HOSTNAME" ]}
          },
          "FunctionName" : "abc-S3-Pickup",
          "Handler" : "abc_S3_Get.lambda_handler",
          "MemorySize" : 128,
          "Role" : { "Fn::FindInMap" : [ "params", {"Ref":"abcVPCNAME"}, "ROLENAME" ]},
          "Runtime" : "python2.7",
          "Timeout" : 3,
          "VpcConfig" : {
            "SecurityGroupIds" : { "Fn::FindInMap" : [ "params", {"Ref":"abcVPCNAME"}, "SecGrps" ]},
            "SubnetIds" : { "Fn::FindInMap" : [ "params", {"Ref":"abcVPCNAME"}, "Subnets" ]}
          },
          "Tags" : [{
            "Key" : "KEY1",
            "Value" : { "Fn::FindInMap" : [ "params", {"Ref":"abcVPCNAME"}, "TAG1" ]}
            },
            {
            "Key" : "KEY2",
            "Value" : { "Fn::FindInMap" : [ "params", {"Ref":"abcVPCNAME"}, "TAG2" ]}
            },
            {
            "Key" : "KEY3",
            "Value" : {"Ref":"ID"}
            }
          ]
        }
      }
    }
}

Body:
Found the resolution. It was issue with Value parameter in Environment which is incorrect.

Corrected to below and resolved the issue.

"Environment" : {
            "Variables" : {
              "abcHOST":  {
                "Fn::FindInMap" : [ "params", {"Ref":"abcVPCNAME"}, "HOSTNAME" ]
              }
            }

There were couple of other issues as well.

"S3Key" : "/lambda/abc_S3.zip",

should be

"S3Key" : "lambda/abc_S3.zip",

Also Deadletterconfig parameter needs to be altered as well.

Current Value:

"DeadLetterConfig" : { "Fn::FindInMap" : [ "params", {"Ref":"abcVPCNAME"}, "TicketSNS" ]},

Correct Value:

"DeadLetterConfig" : {
            "TargetArn" : { "Fn::FindInMap" : [ "params", {"Ref":"abcVPCNAME"}, "TicketSNS" ]}
            },

The CFT started working after all of the above changes.


问:
HttpContext.Response unreliable in Visual Studio Community 2017
Ever since I upgraded to VSC 2017 I've noticed that HttpContext.Response functions have become very tricky to work with, as the expected error, "The thread was being aborted" is rarely handled correctly. Sometimes it works, but it's just as likely that it will hit that error and just quit.

I've tried the usual steps for handling this error myself: adding

```<code>HttpContext.Current.ApplicationInstance.CompleteRequest();
</code>```

at the end of Response.Redirect commands for example, but these have no effect.

Specific example: I have an application that exports GridViews to Excel spreadsheets. Following the the steps to gather and format my data for the spreadsheet, the file is created with the below steps.

```<code>using (var memoryStream = new MemoryStream())
{
  var resp = System.Web.HttpContext.Current.Response;
  resp.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
  resp.AddHeader("content-disposition", "attachment;  filename=" + FileName + ".xlsx");
  excel.SaveAs(memoryStream);
  memoryStream.WriteTo(resp.OutputStream);
  resp.Flush();
  resp.End();
}
</code>```

You can see that Response is being explicitly ended, but it still fails with the same error. It doesn't matter what browser I'm on, and I'm using .NET Framework 4.5.2 -- it's the highest the server I deploy to supports. Does anyone have any ideas?

答:
In further investigation, I have determined that Response, in all its various applications, doesn't play well with the AJAX Update Panel control. When I moved the LinkButton that fires the gridview-to-spreadsheet function I described above out my update panel, it ran as expected.

So don't trigger Response.[whatever] inside an update panel.

Body:
Ever since I upgraded to VSC 2017 I've noticed that HttpContext.Response functions have become very tricky to work with, as the expected error, "The thread was being aborted" is rarely handled correctly. Sometimes it works, but it's just as likely that it will hit that error and just quit.

I've tried the usual steps for handling this error myself: adding

HttpContext.Current.ApplicationInstance.CompleteRequest();

at the end of Response.Redirect commands for example, but these have no effect.

Specific example: I have an application that exports GridViews to Excel spreadsheets. Following the the steps to gather and format my data for the spreadsheet, the file is created with the below steps.

using (var memoryStream = new MemoryStream())
{
  var resp = System.Web.HttpContext.Current.Response;
  resp.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
  resp.AddHeader("content-disposition", "attachment;  filename=" + FileName + ".xlsx");
  excel.SaveAs(memoryStream);
  memoryStream.WriteTo(resp.OutputStream);
  resp.Flush();
  resp.End();
}

You can see that Response is being explicitly ended, but it still fails with the same error. It doesn't matter what browser I'm on, and I'm using .NET Framework 4.5.2 -- it's the highest the server I deploy to supports. Does anyone have any ideas?


问:
OCaml directed graphs vertex module
I have seen some graphs vertex signatures and even come up with my own:

```<code>module type VERTEX = sig
    type t
    type label

    val equal : t -> t -> bool
    val create : label -> t
    val label : t -> label
end
</code>```

But I have completely no idea how to implement it as a module. What types should t and label be? How can I create a t based on a label? And how do I get the label from a t?

答:
I'm an author of Graphlib, so I can't pass by as this question hits me directly into my heart. Honestly, I was asked this question millions of times offline and never was able to provide a good answer.

The real problem is that the graph interfaces from the OCamlGraph library are all messed up. We started Graphlib as an attempt to fix them. However, OCamlGraph is a valuable repository of Graph algorithms, thus we have constrained ourselves to be compatible with the OCamlGraph interface. The main problem for us was and still is this Vertex interface that basically establishes a bijection between the set of labels and the set of nodes. People usually stumble on this, as this doesn't make sense - why do we need two different types, one for the label and another for the vertex, if they are the same?

Indeed, the simplest implementation of the VERTEX interface is the following module

```<code>module Int : VERTEX with type label = int = struct
  type t = int
  type label = int
  let create x = x
  let label x = x
end
</code>```

In that case, we indeed have a trivial bijection (via the identity endofunctor) between the set of labels and the set of vertices.

However, the deeper look, shows us that a signature

```<code>val create : label -> t
val label : t -> label
</code>```

Is not really a bijection, as the bijection is a one-to-one mapping. It is not really required or enforced by the type system. For example, the create function could be a surjection of label onto t, where label is some distinctive element of a family of vertices. Correspondingly, the label function, could be a forgetting functor that returns the distinctive label and forgetting everything else.

Given this approach, we can have another implementation:

```<code>  module Labeled = struct
    type label = int
    type t = {
      label : label;
      data : "";
    }

    let create label = {label; data = ""}
    let label n = n.label
    let data n = n.data
    let with_data n data = {n with data}
    let compare x y = compare x.label y.label
  end
</code>```

In that implementation, we use the label as an identity of a node, and arbitrary attribute can be attached to a node. In this interpretation, the create function partitions all sets of nodes into a set of equivalence classes, where all members of a class, share the same identity, i.e., they represent the same real-world entity in different points of time or space. For example,

```<code>type color = Red | Yellow | Green
module TrafficLight = struct
   type label = int
   type t = {
     id : label;
     color : color
   }

   let create id = {id; color=Red}
   let label t = t.id
   let compare x y = compare x.id y.id
   let switch t color = {t with color}
   let color t = t.color
end
</code>```

In this model, we represent a traffic light with its id number. The color attribute doesn't affect an identity of a traffic light (if a traffic light switches to another color it is still the same traffic light, although in a functional programming language it is represented with two different objects).

The main problem with the above representation is that in all graph textbooks the label is used in the opposite meaning - as an opaque attribute. In a textbook, they will refer to the color of a traffic light as a label. And the node itself will be represented as an int. That's why I'm saying that OCamlGraph interfaces are messed up (and consequently the Graphlib interfaces). So, if you don't want to fall in a contradiction with textbooks, then you should use unlabeled graphs (with int probably is the best representation of a node). And if you need to attach attributes to your nodes, you can use external finite maps, i.e., arrays, maps, associative lists, or any other dictionaries. Otherwise, you need to keep in mind that your label is not a label, but vice verse - the node.

With all this said, let's specify a better interface for a graph vertex:

```<code>module type VERTEX = sig
  type id
  type label
  type t

  val create : id -> t
  val id : t -> id
  val label : t -> label
  val with_label : t -> label -> label
end
</code>```

The proposed interface is compatible with your interface (and thus with the OCamlGraph), as it is isomorphic modulo renaming (i.e., we renamed label to id). It also allows us to create efficient unlabeled nodes, where id = t, as well as attach arbitrary information to a node without relying on external mappings.

Title: OCaml directed graphs vertex module

Body:
I have seen some graphs vertex signatures and even come up with my own:

module type VERTEX = sig
    type t
    type label

    val equal : t -> t -> bool
    val create : label -> t
    val label : t -> label
end

But I have completely no idea how to implement it as a module. What types should t and label be? How can I create a t based on a label? And how do I get the label from a t?

Body:
I'm an author of Graphlib, so I can't pass by as this question hits me directly into my heart. Honestly, I was asked this question millions of times offline and never was able to provide a good answer.

The real problem is that the graph interfaces from the OCamlGraph library are all messed up. We started Graphlib as an attempt to fix them. However, OCamlGraph is a valuable repository of Graph algorithms, thus we have constrained ourselves to be compatible with the OCamlGraph interface. The main problem for us was and still is this Vertex interface that basically establishes a bijection between the set of labels and the set of nodes. People usually stumble on this, as this doesn't make sense - why do we need two different types, one for the label and another for the vertex, if they are the same?

Indeed, the simplest implementation of the VERTEX interface is the following module

module Int : VERTEX with type label = int = struct
  type t = int
  type label = int
  let create x = x
  let label x = x
end

In that case, we indeed have a trivial bijection (via the identity endofunctor) between the set of labels and the set of vertices.

However, the deeper look, shows us that a signature

val create : label -> t
val label : t -> label

Is not really a bijection, as the bijection is a one-to-one mapping. It is not really required or enforced by the type system. For example, the create function could be a surjection of label onto t, where label is some distinctive element of a family of vertices. Correspondingly, the label function, could be a forgetting functor that returns the distinctive label and forgetting everything else.

Given this approach, we can have another implementation:

  module Labeled = struct
    type label = int
    type t = {
      label : label;
      data : "";
    }

    let create label = {label; data = ""}
    let label n = n.label
    let data n = n.data
    let with_data n data = {n with data}
    let compare x y = compare x.label y.label
  end

In that implementation, we use the label as an identity of a node, and arbitrary attribute can be attached to a node. In this interpretation, the create function partitions all sets of nodes into a set of equivalence classes, where all members of a class, share the same identity, i.e., they represent the same real-world entity in different points of time or space. For example,

type color = Red | Yellow | Green
module TrafficLight = struct
   type label = int
   type t = {
     id : label;
     color : color
   }

   let create id = {id; color=Red}
   let label t = t.id
   let compare x y = compare x.id y.id
   let switch t color = {t with color}
   let color t = t.color
end

In this model, we represent a traffic light with its id number. The color attribute doesn't affect an identity of a traffic light (if a traffic light switches to another color it is still the same traffic light, although in a functional programming language it is represented with two different objects).

The main problem with the above representation is that in all graph textbooks the label is used in the opposite meaning - as an opaque attribute. In a textbook, they will refer to the color of a traffic light as a label. And the node itself will be represented as an int. That's why I'm saying that OCamlGraph interfaces are messed up (and consequently the Graphlib interfaces). So, if you don't want to fall in a contradiction with textbooks, then you should use unlabeled graphs (with int probably is the best representation of a node). And if you need to attach attributes to your nodes, you can use external finite maps, i.e., arrays, maps, associative lists, or any other dictionaries. Otherwise, you need to keep in mind that your label is not a label, but vice verse - the node.

With all this said, let's specify a better interface for a graph vertex:

module type VERTEX = sig
  type id
  type label
  type t

  val create : id -> t
  val id : t -> id
  val label : t -> label
  val with_label : t -> label -> label
end

The proposed interface is compatible with your interface (and thus with the OCamlGraph), as it is isomorphic modulo renaming (i.e., we renamed label to id). It also allows us to create efficient unlabeled nodes, where id = t, as well as attach arbitrary information to a node without relying on external mappings.


问:
Network client simulator design

I am trying to design a software in c++ that will send request bytes (following a standard **application level** protocol whose fields to be populated will be taken from a text file) using **UDP protocol**.
Now this client must be able to send these requests at very high rate..upto **2000 transactions per second** and should also receive the response if it gets within a specified timeout else don't receive it

I will be using boost library for all the socket things but I am not sure about the design of it for such high speed application :(

I think I have to use a highly multi-threaded application (again Boost will be used). Am I right ? Do I have to create a seperate thread for each request ? But I think only one thread must be waiting to recieve the response else if many threads are waiting for a response how can we distinguish for which threads request we have got the response for !!

Hope that question is clear. I just need some help regarding the design points and suspected problems that I may face.

答:
I'm not sure you need to go "heavy" multi-thread. Most high speed applications use the polling mechanisms of the operating system, which generally scale better than threads.

The architecture will depend a lot on how reactive your application needs to be, in terms of what components are responsible for generating inputs and outputs, and doing the actual processing.

A way to approach your problem using boost::asio would be to have a communication thread that runs the boost::asio::io_service::run method. The io_service listens on the various UDP sockets, and processes messages as they arrive, possibly sending them down a queue so that the application can process them in the main thread. From the main thread, you can post messages to the io_services for them to be sent by the main system.

This should allow you to climb up to 2000 messages per seconds without much difficulties.

An alternative would be to start several communication threads by calling the boost::asio::io_service::run method several times from several threads, allowing for messages to be processed in parallel by their communication thread.

One word of advice with Asio, though: because of its asynchronous architecture, it works better if you go within its logic and use it the way it is meant to. If you find out that you are using a lot of locks and managing many threads yourself, then you are probably doing it wrong. Look closely at the thread safety guarantees of the various methods, and study the provided examples.

Title: Network client simulator design


问:
If a cells are selected (from more than one sheet) then show message box
For starters, I am self taught and still learning (I learn a great deal from this website). That being said, please do not assume something is obvious. I will need help altering the code if your solution is too complex.

What I want to accomplish is; if you select cell A10 on "Sheet3", "Sheet4", and "Sheet5" then I want a message box to appear with the information from Sheets("Sheet6").Range("A1").

```<code>Option Explicit

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Selection.Count = 1 Then
        If Not Intersect(Target, Range("A10")) Is Nothing Then ' this range is where you click to get the msgbox
                Dim rng As Range, s As String, x As String
                Set rng = Sheets("Sheet6").Range("A1") ' this defines x
                 s = "Define: " ' s is what appears first
                 x = s & rng.Value ' x is what appears after s

                 MsgBox x
        End If
    End If
End Sub
</code>```

What I would like to happen; if you are in "Sheet3", "Sheet4", and "Sheet5" and select A10 in any of those three sheets, it will appear with the message box that is defined in the code.

What is working; currently this is a private sub that is directly in "Sheet5". When it is here, if cell A10 (in "Sheet5") is selected the information from "Sheet6" A1 appears in the message box as I want.

What is not working; because this is a private sub and is inside "Sheet5" I am struggling to get it to work with A10 from "Sheet3" and "Sheet4".

I attempted to alter the code by moving it and declaring it a public sub to work for all sheets but so far am unsuccessful.

答:
For a different approach, this only needs to be entered once, inside the ThisWorkbook object.

```<code>Option Explicit

Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)

    Select Case Sh.Name

        Case Is = "Sheet3", "Sheet4", "Sheet5"

            If Target.Address = "$A$10" Then

                    MsgBox Worksheets("Sheet6").Range("A1").Value

            End If

    End Select

End Sub
</code>```

Body:
For starters, I am self taught and still learning (I learn a great deal from this website). That being said, please do not assume something is obvious. I will need help altering the code if your solution is too complex.

What I want to accomplish is; if you select cell A10 on "Sheet3", "Sheet4", and "Sheet5" then I want a message box to appear with the information from Sheets("Sheet6").Range("A1").

Option Explicit

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Selection.Count = 1 Then
        If Not Intersect(Target, Range("A10")) Is Nothing Then ' this range is where you click to get the msgbox
                Dim rng As Range, s As String, x As String
                Set rng = Sheets("Sheet6").Range("A1") ' this defines x
                 s = "Define: " ' s is what appears first
                 x = s & rng.Value ' x is what appears after s

                 MsgBox x
        End If
    End If
End Sub

What I would like to happen; if you are in "Sheet3", "Sheet4", and "Sheet5" and select A10 in any of those three sheets, it will appear with the message box that is defined in the code.

What is working; currently this is a private sub that is directly in "Sheet5". When it is here, if cell A10 (in "Sheet5") is selected the information from "Sheet6" A1 appears in the message box as I want.

What is not working; because this is a private sub and is inside "Sheet5" I am struggling to get it to work with A10 from "Sheet3" and "Sheet4".

I attempted to alter the code by moving it and declaring it a public sub to work for all sheets but so far am unsuccessful.

Body:
For a different approach, this only needs to be entered once, inside the ThisWorkbook object.

Option Explicit

Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)

    Select Case Sh.Name

        Case Is = "Sheet3", "Sheet4", "Sheet5"

            If Target.Address = "$A$10" Then

                    MsgBox Worksheets("Sheet6").Range("A1").Value

            End If

    End Select

End Sub


问:
Response.WriteFile
There is one URL with specific syntax to download a file.

http://www.hddownloader.com/?url=http://www.youtube.com/watch?v=N-HbxNtY1g8&feature=featured&dldtype=128

The user enters the file name in the textbox and presses the download button.In the click event the Response.WriteFile is called which sends the file to the client.

Now I want to create another website with a page, in which the user enters the filename and presses the download button to download that file.

Now I want to utilise the first URL for that. I dont want to use Response.Redirect, because by that way, the user will come to know that I am using mydownload.com.

How can I acheieve that.

One way is : When we download something from microsoft's website, a small popup window(with no close, maximise and minimise button) and then the save dialog box appears.

How to achieve this or another to achieve the same ?

答:
You could first download the file from the remote location on your server using WebClient.DownloadFile:

```<code>using (var client = new WebClient())
{
    client.DownloadFile("http://remotedomain.com/somefile.pdf", "somefile.pdf");
    Response.WriteFile("somefile.pdf");
}
</code>```

or if you don't want to save the file temporary to the disk you could use the DownloadData method and then stream the buffer into the response.

UPDATE:

Example with the second method:

```<code>using (var client = new WebClient())
{
    var buffer = client.DownloadData("http://remotedomain.com/somefile.pdf");
    Response.ContentType = "application/pdf";
    Response.AppendHeader("Content-Disposition", "attachment;filename=somefile.pdf");
    Response.Clear();
    Response.OutputStream.Write(buffer, 0, buffer.Length);
    Response.Flush();
}
</code>```

Title: Response.WriteFile

Body:
You could first download the file from the remote location on your server using WebClient.DownloadFile:

using (var client = new WebClient())
{
    client.DownloadFile("http://remotedomain.com/somefile.pdf", "somefile.pdf");
    Response.WriteFile("somefile.pdf");
}

or if you don't want to save the file temporary to the disk you could use the DownloadData method and then stream the buffer into the response.

UPDATE:

Example with the second method:

using (var client = new WebClient())
{
    var buffer = client.DownloadData("http://remotedomain.com/somefile.pdf");
    Response.ContentType = "application/pdf";
    Response.AppendHeader("Content-Disposition", "attachment;filename=somefile.pdf");
    Response.Clear();
    Response.OutputStream.Write(buffer, 0, buffer.Length);
    Response.Flush();
}


问:
LDAP installation error
when i try to npm install ldapauth, it displays many errors. I spend the last 2 days checking for a solution but nothing. I tried to uninstall/ reinstall node & npm, same with node-gyp, and still got the error and also installed python but still getting below error :

i am getting error in console like this :

```<code>C:\Ruby24-x64\Files\MDash>npm install ldapauth

> buffertools@1.1.0 install C:\Ruby24-x64\Files\MDash\node_modules\buffertools
> node-gyp rebuild

C:\Ruby24-x64\Files\MDash\node_modules\buffertools>if not defined npm_config_node_gyp (node "C:\Program Files\nodejs\node_modules\npm\bin\node-gyp-bin\\..\..\node_modules\node-gyp\bin\node-gyp.js" rebuild )  else (node "" rebuild )
Building the projects in this solution one at a time. To enable parallel build, please add the "/m" switch.
C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Platforms\x64\PlatformToolsets\v140\Toolset.targets(36,5): error
MSB8036: The Windows SDK version 8.1 was not found. Install the required version of Windows SDK or change the SDK vers
ion in the project property pages or by right-clicking the solution and selecting "Retarget solution". [C:\Ruby24-x64\F
iles\MDash\node_modules\buffertools\build\buffertools.vcxproj]
gyp ERR! build error
gyp ERR! stack Error: `C:\Program Files (x86)\MSBuild\14.0\bin\msbuild.exe` failed with exit code: 1
gyp ERR! stack     at ChildProcess.onExit (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\build.js:258:23)
gyp ERR! stack     at emitTwo (events.js:125:13)
gyp ERR! stack     at ChildProcess.emit (events.js:213:7)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:200:12)
gyp ERR! System Windows_NT 10.0.15063
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild"
gyp ERR! cwd C:\Ruby24-x64\Files\MDash\node_modules\buffertools
gyp ERR! node -v v8.4.0
gyp ERR! node-gyp -v v3.6.2
gyp ERR! not ok
npm WARN minovate@1.2.0 No description
npm WARN minovate@1.2.0 No repository field.
npm WARN minovate@1.2.0 No license field.

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! buffertools@1.1.0 install: `node-gyp rebuild`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the buffertools@1.1.0 install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\miracle\AppData\Roaming\npm-cache\_logs\2017-12-06T14_44_34_406Z-debug.log
</code>```

can you help me.

答:
looks like you miss something : MSB8036: The Windows SDK version 8.1 was not found. You may need to install microsoft visual c++ http://landinghub.visualstudio.com/visual-cpp-build-tools

try to follow the option 1 from this procedure https://github.com/nodejs/node-gyp#on-windows

Title: LDAP installation error

Body:
when i try to npm install ldapauth, it displays many errors. I spend the last 2 days checking for a solution but nothing. I tried to uninstall/ reinstall node & npm, same with node-gyp, and still got the error and also installed python but still getting below error :

i am getting error in console like this :

C:\Ruby24-x64\Files\MDash>npm install ldapauth

> buffertools@1.1.0 install C:\Ruby24-x64\Files\MDash\node_modules\buffertools
> node-gyp rebuild

C:\Ruby24-x64\Files\MDash\node_modules\buffertools>if not defined npm_config_node_gyp (node "C:\Program Files\nodejs\node_modules\npm\bin\node-gyp-bin\\..\..\node_modules\node-gyp\bin\node-gyp.js" rebuild )  else (node "" rebuild )
Building the projects in this solution one at a time. To enable parallel build, please add the "/m" switch.
C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Platforms\x64\PlatformToolsets\v140\Toolset.targets(36,5): error
MSB8036: The Windows SDK version 8.1 was not found. Install the required version of Windows SDK or change the SDK vers
ion in the project property pages or by right-clicking the solution and selecting "Retarget solution". [C:\Ruby24-x64\F
iles\MDash\node_modules\buffertools\build\buffertools.vcxproj]
gyp ERR! build error
gyp ERR! stack Error: `C:\Program Files (x86)\MSBuild\14.0\bin\msbuild.exe` failed with exit code: 1
gyp ERR! stack     at ChildProcess.onExit (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\build.js:258:23)
gyp ERR! stack     at emitTwo (events.js:125:13)
gyp ERR! stack     at ChildProcess.emit (events.js:213:7)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:200:12)
gyp ERR! System Windows_NT 10.0.15063
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild"
gyp ERR! cwd C:\Ruby24-x64\Files\MDash\node_modules\buffertools
gyp ERR! node -v v8.4.0
gyp ERR! node-gyp -v v3.6.2
gyp ERR! not ok
npm WARN minovate@1.2.0 No description
npm WARN minovate@1.2.0 No repository field.
npm WARN minovate@1.2.0 No license field.

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! buffertools@1.1.0 install: `node-gyp rebuild`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the buffertools@1.1.0 install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\miracle\AppData\Roaming\npm-cache\_logs\2017-12-06T14_44_34_406Z-debug.log

can you help me.


问:
need to store ajax response to a global variable
I am using ajax to get some values from a database. In my java script file I have a global variable that some functions need to access it. I need to fill that variable from the values from the database. When I use ajax then the variable stays empty. If I use the async:false in my ajax code I get that warning message in my browser's dev tools:

jquery-3.2.1.min.js:4 [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.

Moreover using the above it doesn't fill the variable resulting to errors in the other functions. Plus, from what I read this is deprecated and should not be used in any circumstances.

my code

```<code>var array ={};
var flag = 'true';
        $.ajax({
            url: "name.php",
            method: "post",
            data:{flag:JSON.stringify(flag)},
            success: function(data) {
                array = JSON.parse(data);

            },
             async: false,
            error: function(xhr, ajaxOptions, thrownError) {
            console.log(thrownError);
            }
        });
</code>```

What, basically I'm trying to do, is to fill the array variable and make it an proper array.

the data from the the database is like this

{
'something': { 'act1': 'act1a','act2': 'act2a'},
 'something2': { 'act1': 'act1a','act2': 'act2a'}
}

anyone have any suggestions on how to achieve that?

PS:
I need to fill a variable with the ajax response which will be accessible by other functions... not Convert a JSON Object into Javascript array...Im retrieving the data in string format

答:
Based on your question and code, I think you are trying to access your array object before it is loaded with data. First of all, you will need to remove async:false. You want this to be asynchronous. That's the nature of ajax. Secondly, make sure you "do stuff" with array after the ajax call completes. For example, this will not work:

```<code>var array ={};
var flag = 'true';
$.ajax({
    url: "name.php",
    method: "post",
    data:{flag:JSON.stringify(flag)},
    success: function(data) {
        array = JSON.parse(data);
    },
    error: function(xhr, ajaxOptions, thrownError) {
        console.log(thrownError);
    }
});
//DO STUFF WITH array here.. will not work
</code>```

But this will work:

```<code>var array ={};
var flag = 'true';
$.ajax({
    url: "name.php",
    method: "post",
    data:{flag:JSON.stringify(flag)},
    success: function(data) {
        array = JSON.parse(data);
        //DO STUFF WITH array here..
    },
    error: function(xhr, ajaxOptions, thrownError) {
        console.log(thrownError);
    }
});
</code>```

One more thing to consider here - It's common practice to create a function outside your ajax success function to do something with your data (array), and call that function from inside your success function:

```<code>var array ={};
var flag = 'true';
$.ajax({
    url: "name.php",
    method: "post",
    data:{flag:JSON.stringify(flag)},
    success: function(data) {
        array = JSON.parse(data);
        doStuffWithArray(array);
    },
    error: function(xhr, ajaxOptions, thrownError) {
        console.log(thrownError);
    }
});

function doStuffWithArray(myArray) {
    //DO STUFF HERE...
}
</code>```

Body:
I am using ajax to get some values from a database. In my java script file I have a global variable that some functions need to access it. I need to fill that variable from the values from the database. When I use ajax then the variable stays empty. If I use the async:false in my ajax code I get that warning message in my browser's dev tools:

jquery-3.2.1.min.js:4 [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.

Moreover using the above it doesn't fill the variable resulting to errors in the other functions. Plus, from what I read this is deprecated and should not be used in any circumstances.

my code

var array ={};
var flag = 'true';
        $.ajax({
            url: "name.php",
            method: "post",
            data:{flag:JSON.stringify(flag)},
            success: function(data) {
                array = JSON.parse(data);

            },
             async: false,
            error: function(xhr, ajaxOptions, thrownError) {
            console.log(thrownError);
            }
        });

What, basically I'm trying to do, is to fill the array variable and make it an proper array.

the data from the the database is like this

{
'something': { 'act1': 'act1a','act2': 'act2a'},
 'something2': { 'act1': 'act1a','act2': 'act2a'}
}

anyone have any suggestions on how to achieve that?

PS:
I need to fill a variable with the ajax response which will be accessible by other functions... not Convert a JSON Object into Javascript array...Im retrieving the data in string format

Body:
Based on your question and code, I think you are trying to access your array object before it is loaded with data. First of all, you will need to remove async:false. You want this to be asynchronous. That's the nature of ajax. Secondly, make sure you "do stuff" with array after the ajax call completes. For example, this will not work:

var array ={};
var flag = 'true';
$.ajax({
    url: "name.php",
    method: "post",
    data:{flag:JSON.stringify(flag)},
    success: function(data) {
        array = JSON.parse(data);
    },
    error: function(xhr, ajaxOptions, thrownError) {
        console.log(thrownError);
    }
});
//DO STUFF WITH array here.. will not work

But this will work:

var array ={};
var flag = 'true';
$.ajax({
    url: "name.php",
    method: "post",
    data:{flag:JSON.stringify(flag)},
    success: function(data) {
        array = JSON.parse(data);
        //DO STUFF WITH array here..
    },
    error: function(xhr, ajaxOptions, thrownError) {
        console.log(thrownError);
    }
});

One more thing to consider here - It's common practice to create a function outside your ajax success function to do something with your data (array), and call that function from inside your success function:

var array ={};
var flag = 'true';
$.ajax({
    url: "name.php",
    method: "post",
    data:{flag:JSON.stringify(flag)},
    success: function(data) {
        array = JSON.parse(data);
        doStuffWithArray(array);
    },
    error: function(xhr, ajaxOptions, thrownError) {
        console.log(thrownError);
    }
});

function doStuffWithArray(myArray) {
    //DO STUFF HERE...
}


问:
How get list of named objects in boost interprocess shared memory
According to guide on Boost docs

It is possible to create named vectors of some type (for instance double)

```<code>  using namespace boost::interprocess;
  typedef allocator<int, managed_shared_memory::segment_manager>  ShmemAllocator;
  managed_shared_memory segment(create_only, "MySharedMemory", 65536);

  //Initialize shared memory STL-compatible allocator
  const ShmemAllocator alloc_inst (segment.get_segment_manager());

  //Construct a vector named "values_A" in shared memory with argument alloc_inst
  MyVector *vA= segment.construct<MyVector>("values_A")(alloc_inst);
  MyVector *vB= segment.construct<MyVector>("values_B")(alloc_inst);

  for(int i = 0; i < 100; ++i)  //Insert data in the vector
     vA->push_back(i);
</code>```

And then if client process knows the names of shared objects ("values_A" and "values_B") it is easy to access them.

```<code>  managed_shared_memory segment(open_only, "MySharedMemory");
  MyVector *vA_client = segment.find<MyVector>("values_A").first;
  MyVector *vB_client = segment.find<MyVector>("values_B").first;

  //Use vector in reverse order
  std::sort(vA_client->rbegin(), vA_client->rend());
</code>```

But if client doesn't know the names of those objects?

How to get list of those objects? {"values_A" , "values_B"}.

If there was some objects of other type ("MyVector2") registered (named "intA", "intB") - How would you filter only those, whose type is MyVector?

I have a suspicion that it has to do with method named_begin and named_end but I don't know how to use it.

Thank You for your help :)

答:
These methods are part of the segment manager interface.

Beware of race conditions when using these directly. find_or_construct does something else than find and construct sequentially in a multi-process situation.

Example:

Live On Coliru

```<code>#include <boost/interprocess/managed_mapped_file.hpp>
#include <boost/interprocess/containers/vector.hpp>
#include <iostream>
namespace bip = boost::interprocess;

using Shared = bip::managed_mapped_file;
using Manager = Shared::segment_manager;
template <typename T> using Alloc = bip::allocator<T, Manager>;
template <typename T> using V = boost::container::vector<T, Alloc<T> >;

int main() {
    bip::managed_mapped_file mmf(bip::open_or_create, "test.bin", 10ull<<10);
    auto* segment = mmf.get_segment_manager();

    for (auto it = segment->named_begin(); it != segment->named_end(); ++it) {
        std::cout << "before: " << std::string(it->name(), it->name_length()) << "\n";
    }

    for (auto next : { "foo", "bar", "qux" }) {
        if (!mmf.find<V<int> >(next).first)
        {
            mmf.find_or_construct<V<int> >(next)(segment);
            break;
        }
    }

    for (auto it = segment->named_begin(); it != segment->named_end(); ++it) {
        std::cout << "after:  " << std::string(it->name(), it->name_length()) << "\n";
    }
}
</code>```

Prints (first run):

```<code>after:  foo
</code>```

Second run:

```<code>before: foo
after:  bar
after:  foo
</code>```

Third run:

```<code>before: bar
before: foo
after:  bar
after:  foo
after:  qux
</code>```

Fourth (and later) run:

```<code>before: bar
before: foo
before: qux
after:  bar
after:  foo
after:  qux
</code>```

Body:
According to guide on Boost docs

It is possible to create named vectors of some type (for instance double)

  using namespace boost::interprocess;
  typedef allocator<int, managed_shared_memory::segment_manager>  ShmemAllocator;
  managed_shared_memory segment(create_only, "MySharedMemory", 65536);

  //Initialize shared memory STL-compatible allocator
  const ShmemAllocator alloc_inst (segment.get_segment_manager());

  //Construct a vector named "values_A" in shared memory with argument alloc_inst
  MyVector *vA= segment.construct<MyVector>("values_A")(alloc_inst);
  MyVector *vB= segment.construct<MyVector>("values_B")(alloc_inst);

  for(int i = 0; i < 100; ++i)  //Insert data in the vector
     vA->push_back(i);

And then if client process knows the names of shared objects ("values_A" and "values_B") it is easy to access them.

  managed_shared_memory segment(open_only, "MySharedMemory");
  MyVector *vA_client = segment.find<MyVector>("values_A").first;
  MyVector *vB_client = segment.find<MyVector>("values_B").first;

  //Use vector in reverse order
  std::sort(vA_client->rbegin(), vA_client->rend());

But if client doesn't know the names of those objects?

How to get list of those objects? {"values_A" , "values_B"}.

If there was some objects of other type ("MyVector2") registered (named "intA", "intB") - How would you filter only those, whose type is MyVector?

I have a suspicion that it has to do with method named_begin and named_end but I don't know how to use it.

Thank You for your help :)

Body:
These methods are part of the segment manager interface.

Beware of race conditions when using these directly. find_or_construct does something else than find and construct sequentially in a multi-process situation.

Example:

Live On Coliru

#include <boost/interprocess/managed_mapped_file.hpp>
#include <boost/interprocess/containers/vector.hpp>
#include <iostream>
namespace bip = boost::interprocess;

using Shared = bip::managed_mapped_file;
using Manager = Shared::segment_manager;
template <typename T> using Alloc = bip::allocator<T, Manager>;
template <typename T> using V = boost::container::vector<T, Alloc<T> >;

int main() {
    bip::managed_mapped_file mmf(bip::open_or_create, "test.bin", 10ull<<10);
    auto* segment = mmf.get_segment_manager();

    for (auto it = segment->named_begin(); it != segment->named_end(); ++it) {
        std::cout << "before: " << std::string(it->name(), it->name_length()) << "\n";
    }

    for (auto next : { "foo", "bar", "qux" }) {
        if (!mmf.find<V<int> >(next).first)
        {
            mmf.find_or_construct<V<int> >(next)(segment);
            break;
        }
    }

    for (auto it = segment->named_begin(); it != segment->named_end(); ++it) {
        std::cout << "after:  " << std::string(it->name(), it->name_length()) << "\n";
    }
}

Prints (first run):

after:  foo

Second run:

before: foo
after:  bar
after:  foo

Third run:

before: bar
before: foo
after:  bar
after:  foo
after:  qux

Fourth (and later) run:

before: bar
before: foo
before: qux
after:  bar
after:  foo
after:  qux


问:
VBA Error Subscript out of range in for loop used to copy/paste
I keep getting an error message for my for loop. What it is supposed to do is compare a variable to the first column for every row for a given worksheet and copy it if it matches, then paste it to a worksheet in a different workbook but for some reason I keep getting "Run-time error '9': Subscript out of Range" for the line referencing the new workbook/worksheet.

My for loop so far:

```<code>For i = 1 To Sheets(1).UsedRange.Rows.Count

    If Sheets(1).Cells(i, 1).Value Like dateRange & "*" Then
       Sheets(1).Rows(i).Copy
       Workbooks(destinationWorkbook).Worksheets("Sheet2").Rows(i).Paste 'Debug shows the error is here
    End If

Next i
</code>```

In the previous code I define the variable as:

```<code>destinationWorkbook = "C:\Users\lbran\Desktop\Book1.xlsm"
</code>```

I have also tried using Workbooks(destinationWorkbook).Worksheets("Sheet2").Cells(i, 1).Paste

I'm very new to VBA so I'm not sure if I'm referencing the pasting to worksheet correctly but I know it does exist as a new, empty sheet in the workbook

答:
Once you've opened a workbook it's name is just the filename it was saved under, not the path. So you would do

```<code>  Workbooks.open(destinationWorkbook)
</code>```

But then refer to it as

```<code>  Workbooks("Book1.xlsm")
</code>```

But I wonder if you are trying to copy to a new workbook that isn't on your hard drive? In which case you would write

```<code>     Workbooks.add
     WorkBooks("book1")
</code>```

There wouldn't be a file extension because you haven't saved it yet.
You can avoid all these problems by using an object variable

```<code> Dim wb as workbook
Set wb = workbooks.open(destinationworkbook)
or
Set wb = workbooks.add
</code>```

and then just wb to refer to the workbook

Body:
I keep getting an error message for my for loop. What it is supposed to do is compare a variable to the first column for every row for a given worksheet and copy it if it matches, then paste it to a worksheet in a different workbook but for some reason I keep getting "Run-time error '9': Subscript out of Range" for the line referencing the new workbook/worksheet.

My for loop so far:

For i = 1 To Sheets(1).UsedRange.Rows.Count

    If Sheets(1).Cells(i, 1).Value Like dateRange & "*" Then
       Sheets(1).Rows(i).Copy
       Workbooks(destinationWorkbook).Worksheets("Sheet2").Rows(i).Paste 'Debug shows the error is here
    End If

Next i

In the previous code I define the variable as:

destinationWorkbook = "C:\Users\lbran\Desktop\Book1.xlsm"

I have also tried using Workbooks(destinationWorkbook).Worksheets("Sheet2").Cells(i, 1).Paste

I'm very new to VBA so I'm not sure if I'm referencing the pasting to worksheet correctly but I know it does exist as a new, empty sheet in the workbook

Body:
Once you've opened a workbook it's name is just the filename it was saved under, not the path. So you would do

  Workbooks.open(destinationWorkbook)

But then refer to it as

  Workbooks("Book1.xlsm")

But I wonder if you are trying to copy to a new workbook that isn't on your hard drive? In which case you would write

     Workbooks.add
     WorkBooks("book1")

There wouldn't be a file extension because you haven't saved it yet.
You can avoid all these problems by using an object variable

 Dim wb as workbook
Set wb = workbooks.open(destinationworkbook)
or
Set wb = workbooks.add

and then just wb to refer to the workbook


问:
regex expression contains a word and does not contain another
I am trying to write a regex expression that would be give the line that does not contain google but contains com

For Example:

```<code>www.google.com
www.msn.com
www.msn
</code>```

it should match www.msn.com because it contains com and doesn't contain google.

Is this possible?

答:
You can use a negative lookahead regex for your requirement:

```<code>^(?!.*google).*\.com
</code>```

RegEx Demo

RegEx Breakup:

^: Start

(?!.*google): Negative lookahead to assert we don't have google ahead

.*\.com: Match .com after 0 or more characters

Body:
I am trying to write a regex expression that would be give the line that does not contain google but contains com

For Example:

www.google.com
www.msn.com
www.msn

it should match www.msn.com because it contains com and doesn't contain google.

Is this possible?

Body:
You can use a negative lookahead regex for your requirement:

^(?!.*google).*\.com

RegEx Demo

RegEx Breakup:

^: Start

(?!.*google): Negative lookahead to assert we don't have google ahead

.*\.com: Match .com after 0 or more characters


问:
UILongPressGestureRecognizer breaks tableView scrolling
I created a custom Label class that contains a UILongPressGestureRecognizer, and I am invoking it in tableview cells in a TableViewController. The long press gesture recognizer works (two clickable zones in an attributed sting), but the tableView containing the labels no longer scrolls (pans) if the scroll gesture begins in one of the UILongPressGestureRecognizer zones of my CustomLabel. I have tried cancelsTouchesInView = false as well as the various responses below, to no avail. Any suggestions would be greatly appreciated. I've spent a week on this problem. My code is below.

Here is the CustomLabel class:

```<code>class CustomLabel: UILabel {

    let layoutManager = NSLayoutManager()
    let textContainer = NSTextContainer(size: CGSize.zero)
    var textStorage = NSTextStorage() {
        didSet {
            textStorage.addLayoutManager(layoutManager)
        }
    }

    var onCharacterTapped: ((_ label: UILabel, _ characterIndex: Int, _ state: Bool) -> Void)?

    let tapGesture = UILongPressGestureRecognizer()

    override var attributedText: NSAttributedString? {
        didSet {
            if let attributedText = attributedText {

                if attributedText.string != textStorage.string {

                textStorage = NSTextStorage(attributedString: attributedText)

                DispatchQueue.main.async {

                    let characterDelay = TimeInterval(0.01 + Float(arc4random()) /  Float(UInt32.max)) / 100

                    for (index, char) in attributedText.string.characters.enumerated() {

                        DispatchQueue.main.asyncAfter(deadline: .now() + characterDelay * Double(index)) {
                            print("character ch is: \(char) at index: \(index)")
                            super.attributedText = attributedText.attributedSubstring(from: NSRange(location: 0, length: index+1))
                        }
                    }
                }
                }

            } else {
                textStorage = NSTextStorage()
            }
        }
    }

    override var lineBreakMode: NSLineBreakMode {
        didSet {
            textContainer.lineBreakMode = lineBreakMode
        }
    }

    override var numberOfLines: Int {
        didSet {
            textContainer.maximumNumberOfLines = numberOfLines
        }
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setUp()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setUp()
    }

    func setUp() {
        isUserInteractionEnabled = true
        layoutManager.addTextContainer(textContainer)
        textContainer.lineFragmentPadding = 0
        textContainer.lineBreakMode = lineBreakMode
        textContainer.maximumNumberOfLines = numberOfLines
        tapGesture.addTarget(self, action: #selector(CustomLabel.labelTapped(_:)))
        tapGesture.minimumPressDuration = 0
        tapGesture.cancelsTouchesInView = false
        //tapGesture.delegate = self.superview
        addGestureRecognizer(tapGesture)
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        textContainer.size = bounds.size
    }

    func labelTapped(_ gesture: UILongPressGestureRecognizer) {

        let locationOfTouch = gesture.location(in: gesture.view)
        let textBoundingBox = layoutManager.usedRect(for: textContainer)
        let textContainerOffset = CGPoint(x: (bounds.width - textBoundingBox.width) / 2 - textBoundingBox.minX, y: (bounds.height - textBoundingBox.height) / 2 - textBoundingBox.minY)
        let locationOfTouchInTextContainer = CGPoint(x: locationOfTouch.x - textContainerOffset.x, y: locationOfTouch.y - textContainerOffset.y)
        let indexOfCharacter = layoutManager.characterIndex(for: locationOfTouchInTextContainer, in: textContainer, fractionOfDistanceBetweenInsertionPoints: nil)

        if gesture.state == .began {

            onCharacterTapped?(self, indexOfCharacter, true)

        } else if gesture.state == .ended {

            onCharacterTapped?(self, indexOfCharacter, false)

        }

    }

}
</code>```

Here is the cellClass:

```<code>class friendTextCell: UITableViewCell {

    @IBOutlet weak var labelText: CustomLabel!

    override func awakeFromNib() {
        super.awakeFromNib()
        self.layoutIfNeeded()
    }

}
</code>```

And here is selections from the TableViewControllerClass where CustomCells are created:

```<code>class UsersViewController: UITableViewController, UIGestureRecognizerDelegate {

private func gestureRecognizer(gestureRecognizer: UIPanGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UILongPressGestureRecognizer) -> Bool {return true}

    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRequireFailureOf otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return gestureRecognizer === longPressRecognizer &&
            (otherGestureRecognizer.view?.isDescendant(of:tableView) ?? false)
    }

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "friendText", for: indexPath) as! friendTextCell

        print("keyArrrrray is: \(keyArray)")

        if indexPath.section == 0 && indexPath.row < keyArray.count {
            self.removeInstructions()
            cell.labelText.font = cell.labelText.font.withSize(17)
            let text = "> "+namesArray[indexPath.row] + ": " + linkArray[indexPath.row]
            let name = namesArray[indexPath.row]
            let link = linkArray[indexPath.row]
            let imageLink = imageURLArray[indexPath.row]
            let nameChCount = name.characters.count
            let linkChCount = link.characters.count

            let attributedString = NSMutableAttributedString(string: name + ": " + link, attributes: nil)

            let totalChCount = attributedString.string.characters.count

            let linkRange = NSMakeRange(0, nameChCount) // for the word "link" in the string above

            let linkAttributes: [String : AnyObject] = [
                NSForegroundColorAttributeName : UIColor.white, NSUnderlineStyleAttributeName : NSUnderlineStyle.styleSingle.rawValue as AnyObject]
            attributedString.setAttributes(linkAttributes, range:linkRange)

            cell.labelText.attributedText = attributedString

            cell.labelText.onCharacterTapped = { label, characterIndex, state in

                let highlight: [String : AnyObject] = [NSForegroundColorAttributeName : UIColor.black, NSBackgroundColorAttributeName : UIColor.white]

                if state == true {
                    if characterIndex < nameChCount {
                        print("name press began at character \(characterIndex)")
                        attributedString.addAttributes(highlight, range:NSMakeRange(0, nameChCount))
                        cell.labelText.attributedText = attributedString
                    } else if characterIndex > nameChCount {
                        print("link press began at character \(characterIndex)")
                        let startPos = nameChCount + 2
                        let endPos = totalChCount-nameChCount-2
                        attributedString.addAttributes(highlight, range:NSMakeRange(startPos, endPos))
                        cell.labelText.attributedText = attributedString
                    }

                } else if state == false {

                    if characterIndex < name.characters.count {

                        if let userVC:UserViewTableViewController = self.storyboard?.instantiateViewController(withIdentifier: "UserVC") as? UserViewTableViewController {
                            userVC.userName = name
                            userVC.shareLink = link
                            userVC.imageLink = imageLink
                            self.navigationController?.pushViewController(userVC, animated: true)
                        }

                }

                if characterIndex > name.characters.count && characterIndex <= link.characters.count + name.characters.count {

                    //extract link from array
                    let link = self.linkArray[indexPath.row]
                    print("on click link is: \(link)")

                    //Present SafariViewController with link
                    let svc = SFSafariViewController(url: NSURL(string: link)! as URL)
                    self.present(svc, animated: true, completion: nil)

                }
                }

            }

        } else if keyArray.isEmpty && indexPath.section == 0 {

            cell.labelText.text = "..."

        }

        if indexPath.section == 1 && keyArray.count <= 1 {
            let message = "> Press the + button to add more friends."
            cell.labelText.animate(newText: message, characterDelay: TimeInterval(0.01 + Float(arc4random()) /  Float(UInt32.max)) / 200)
        } else if indexPath.section == 1 {
            cell.labelText.text = ""
        }

        return cell

    }
</code>```

答:
tableView containing the labels no longer scrolls (pans) if the scroll gesture begins in one of the UILongPressGestureRecognizer

This problem occurs when you set the UILongPressGestureRecognizer's minimum press duration to 0 and it starts to grab the scroll view's embedded gesture recognizer. You can resolve it by using bigger delay, if you need to use long press gesture recognizer with delay, how it's supposed to be.
First will respond your table view's didSelectRow at and after delay your selector.
It worked for me, although i removed tapGesture.cancelsTouchesInView = false and added attribute @objc before declaring your selector method for recognizer (requires if you write in swift 4).

If you want to use UILongPressGestureRecognizer with no delay, just use UITapGestureRecognizer. In this case table view will scroll, but you can't receive didSelectRow method if you tap on the label.
Table and Collection views gestures delegates are set to underlying scroll view so you cant use UIGestureRecognizerDelegate methods on your UIViewController for that purpose.
If you want to receive some kind of callback in you View Controller when that recognizer fires, you can throw call back by implementing delegate methods.

Create CustomLabel's delegate that implements labelTapped function for example. In your selector call that delegate function. Make your cell conform to that delegate and repeat that in your cell to throw function to your UIViewController. Also you can use closure delegate pattern.

Hope that helps.

Update

So the solution is to make UILongPressGestureRecognizer 's minimumPressDuration to 0 as you initially did and assign the delegate to it's cell (superview in my case).
In cell you need to override this method:

```<code>gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    return gestureRecognizer == yourGesture || otherGestureRecognizer == yourGesture
}
</code>```

By the way you don't need to make your cell conform to UIGestureRecognizerDelegate as it already does

Body:
I created a custom Label class that contains a UILongPressGestureRecognizer, and I am invoking it in tableview cells in a TableViewController. The long press gesture recognizer works (two clickable zones in an attributed sting), but the tableView containing the labels no longer scrolls (pans) if the scroll gesture begins in one of the UILongPressGestureRecognizer zones of my CustomLabel. I have tried cancelsTouchesInView = false as well as the various responses below, to no avail. Any suggestions would be greatly appreciated. I've spent a week on this problem. My code is below.

Here is the CustomLabel class:

class CustomLabel: UILabel {

    let layoutManager = NSLayoutManager()
    let textContainer = NSTextContainer(size: CGSize.zero)
    var textStorage = NSTextStorage() {
        didSet {
            textStorage.addLayoutManager(layoutManager)
        }
    }

    var onCharacterTapped: ((_ label: UILabel, _ characterIndex: Int, _ state: Bool) -> Void)?

    let tapGesture = UILongPressGestureRecognizer()

    override var attributedText: NSAttributedString? {
        didSet {
            if let attributedText = attributedText {

                if attributedText.string != textStorage.string {

                textStorage = NSTextStorage(attributedString: attributedText)

                DispatchQueue.main.async {

                    let characterDelay = TimeInterval(0.01 + Float(arc4random()) /  Float(UInt32.max)) / 100

                    for (index, char) in attributedText.string.characters.enumerated() {

                        DispatchQueue.main.asyncAfter(deadline: .now() + characterDelay * Double(index)) {
                            print("character ch is: \(char) at index: \(index)")
                            super.attributedText = attributedText.attributedSubstring(from: NSRange(location: 0, length: index+1))
                        }
                    }
                }
                }

            } else {
                textStorage = NSTextStorage()
            }
        }
    }

    override var lineBreakMode: NSLineBreakMode {
        didSet {
            textContainer.lineBreakMode = lineBreakMode
        }
    }

    override var numberOfLines: Int {
        didSet {
            textContainer.maximumNumberOfLines = numberOfLines
        }
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setUp()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setUp()
    }

    func setUp() {
        isUserInteractionEnabled = true
        layoutManager.addTextContainer(textContainer)
        textContainer.lineFragmentPadding = 0
        textContainer.lineBreakMode = lineBreakMode
        textContainer.maximumNumberOfLines = numberOfLines
        tapGesture.addTarget(self, action: #selector(CustomLabel.labelTapped(_:)))
        tapGesture.minimumPressDuration = 0
        tapGesture.cancelsTouchesInView = false
        //tapGesture.delegate = self.superview
        addGestureRecognizer(tapGesture)
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        textContainer.size = bounds.size
    }

    func labelTapped(_ gesture: UILongPressGestureRecognizer) {

        let locationOfTouch = gesture.location(in: gesture.view)
        let textBoundingBox = layoutManager.usedRect(for: textContainer)
        let textContainerOffset = CGPoint(x: (bounds.width - textBoundingBox.width) / 2 - textBoundingBox.minX, y: (bounds.height - textBoundingBox.height) / 2 - textBoundingBox.minY)
        let locationOfTouchInTextContainer = CGPoint(x: locationOfTouch.x - textContainerOffset.x, y: locationOfTouch.y - textContainerOffset.y)
        let indexOfCharacter = layoutManager.characterIndex(for: locationOfTouchInTextContainer, in: textContainer, fractionOfDistanceBetweenInsertionPoints: nil)

        if gesture.state == .began {

            onCharacterTapped?(self, indexOfCharacter, true)

        } else if gesture.state == .ended {

            onCharacterTapped?(self, indexOfCharacter, false)

        }

    }

}

Here is the cellClass:

class friendTextCell: UITableViewCell {

    @IBOutlet weak var labelText: CustomLabel!

    override func awakeFromNib() {
        super.awakeFromNib()
        self.layoutIfNeeded()
    }

}

And here is selections from the TableViewControllerClass where CustomCells are created:

class UsersViewController: UITableViewController, UIGestureRecognizerDelegate {

private func gestureRecognizer(gestureRecognizer: UIPanGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UILongPressGestureRecognizer) -> Bool {return true}

    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRequireFailureOf otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return gestureRecognizer === longPressRecognizer &&
            (otherGestureRecognizer.view?.isDescendant(of:tableView) ?? false)
    }

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "friendText", for: indexPath) as! friendTextCell

        print("keyArrrrray is: \(keyArray)")

        if indexPath.section == 0 && indexPath.row < keyArray.count {
            self.removeInstructions()
            cell.labelText.font = cell.labelText.font.withSize(17)
            let text = "> "+namesArray[indexPath.row] + ": " + linkArray[indexPath.row]
            let name = namesArray[indexPath.row]
            let link = linkArray[indexPath.row]
            let imageLink = imageURLArray[indexPath.row]
            let nameChCount = name.characters.count
            let linkChCount = link.characters.count

            let attributedString = NSMutableAttributedString(string: name + ": " + link, attributes: nil)

            let totalChCount = attributedString.string.characters.count

            let linkRange = NSMakeRange(0, nameChCount) // for the word "link" in the string above

            let linkAttributes: [String : AnyObject] = [
                NSForegroundColorAttributeName : UIColor.white, NSUnderlineStyleAttributeName : NSUnderlineStyle.styleSingle.rawValue as AnyObject]
            attributedString.setAttributes(linkAttributes, range:linkRange)

            cell.labelText.attributedText = attributedString

            cell.labelText.onCharacterTapped = { label, characterIndex, state in

                let highlight: [String : AnyObject] = [NSForegroundColorAttributeName : UIColor.black, NSBackgroundColorAttributeName : UIColor.white]

                if state == true {
                    if characterIndex < nameChCount {
                        print("name press began at character \(characterIndex)")
                        attributedString.addAttributes(highlight, range:NSMakeRange(0, nameChCount))
                        cell.labelText.attributedText = attributedString
                    } else if characterIndex > nameChCount {
                        print("link press began at character \(characterIndex)")
                        let startPos = nameChCount + 2
                        let endPos = totalChCount-nameChCount-2
                        attributedString.addAttributes(highlight, range:NSMakeRange(startPos, endPos))
                        cell.labelText.attributedText = attributedString
                    }

                } else if state == false {

                    if characterIndex < name.characters.count {

                        if let userVC:UserViewTableViewController = self.storyboard?.instantiateViewController(withIdentifier: "UserVC") as? UserViewTableViewController {
                            userVC.userName = name
                            userVC.shareLink = link
                            userVC.imageLink = imageLink
                            self.navigationController?.pushViewController(userVC, animated: true)
                        }

                }

                if characterIndex > name.characters.count && characterIndex <= link.characters.count + name.characters.count {

                    //extract link from array
                    let link = self.linkArray[indexPath.row]
                    print("on click link is: \(link)")

                    //Present SafariViewController with link
                    let svc = SFSafariViewController(url: NSURL(string: link)! as URL)
                    self.present(svc, animated: true, completion: nil)

                }
                }

            }

        } else if keyArray.isEmpty && indexPath.section == 0 {

            cell.labelText.text = "..."

        }

        if indexPath.section == 1 && keyArray.count <= 1 {
            let message = "> Press the + button to add more friends."
            cell.labelText.animate(newText: message, characterDelay: TimeInterval(0.01 + Float(arc4random()) /  Float(UInt32.max)) / 200)
        } else if indexPath.section == 1 {
            cell.labelText.text = ""
        }

        return cell

    }

Body:
tableView containing the labels no longer scrolls (pans) if the scroll gesture begins in one of the UILongPressGestureRecognizer

This problem occurs when you set the UILongPressGestureRecognizer's minimum press duration to 0 and it starts to grab the scroll view's embedded gesture recognizer. You can resolve it by using bigger delay, if you need to use long press gesture recognizer with delay, how it's supposed to be.
First will respond your table view's didSelectRow at and after delay your selector.
It worked for me, although i removed tapGesture.cancelsTouchesInView = false and added attribute @objc before declaring your selector method for recognizer (requires if you write in swift 4).

If you want to use UILongPressGestureRecognizer with no delay, just use UITapGestureRecognizer. In this case table view will scroll, but you can't receive didSelectRow method if you tap on the label.
Table and Collection views gestures delegates are set to underlying scroll view so you cant use UIGestureRecognizerDelegate methods on your UIViewController for that purpose.
If you want to receive some kind of callback in you View Controller when that recognizer fires, you can throw call back by implementing delegate methods.

Create CustomLabel's delegate that implements labelTapped function for example. In your selector call that delegate function. Make your cell conform to that delegate and repeat that in your cell to throw function to your UIViewController. Also you can use closure delegate pattern.

Hope that helps.

Update

So the solution is to make UILongPressGestureRecognizer 's minimumPressDuration to 0 as you initially did and assign the delegate to it's cell (superview in my case).
In cell you need to override this method:

gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    return gestureRecognizer == yourGesture || otherGestureRecognizer == yourGesture
}

By the way you don't need to make your cell conform to UIGestureRecognizerDelegate as it already does


问:
Trigger jquery function from select dropdown
This should be really easy, but I have been going around in circles with it for the past three hours... I know that I should change the ID of SELECT to match that of the jquery function, but there is another step (obviously) that I am missing.

I am using the jqueryui datepicker, and I simply want it to pop up when a particular value is chosen with a 'select' dropdown, rather than when an 'input' field is clicked. Here is the code, thanks in advance for your help:

```<code>    <SELECT id="">
        <option value="1">TODAY</option>
        <option value="2">TOMORROW</option>
        <option selected value="3">THIS WEEK</option>
        <option value="4">NEXT WEEK</option>
        <option value="5">THIS MONTH</option>
        <option value="6">NEXT MONTH</option>
        <option value="7">CALENDAR SHOULD POP UP WHEN THIS OPTION IS SELECTED</option>
    </SELECT>

<input type="text" id="datepicker" value="INSTEAD OF THIS">

  <script>
  $( function() {
    $( "#datepicker" ).datepicker({
      minDate: 0, maxDate: "+2Y"
    });
  } );
  </script>
</code>```

答:
Yes, you can do things like this. A switch() will help identify what to do when specific options are selected in the drop down, and they can then tell the .datepicker() what to do.

$(function() {
  $("#datepicker").datepicker({
    minDate: 0,
    maxDate: "+2Y"
  }).hide();
  $("#select-date").change(function(e) {
    if ($(this).val() == "7") {
      $("#datepicker").show().datepicker("show");
    } else {
      $("#datepicker").datepicker("hide").hide();
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<SELECT id="select-date">
  <option value="1">TODAY</option>
  <option value="2">TOMORROW</option>
  <option selected value="3">THIS WEEK</option>
  <option value="4">NEXT WEEK</option>
  <option value="5">THIS MONTH</option>
  <option value="6">NEXT MONTH</option>
  <option value="7">CALENDAR</option>
</SELECT>
<input type="text" id="datepicker"></code>```

Now you can also do this with a ComboBox or Split Button if you were interested. To fit with the site more, you may consider:

$(function() {
  var $datepick = $("#datepicker"),
    $opt7 = $("#select-date option[value='7']");
  $datepick.datepicker({
    minDate: 0,
    maxDate: "+2Y",
    onSelect: function(sDate, dObj) {
      $opt7.html(sDate);
      $datepick.hide();
    }
  }).hide();
  $opt7.click(function(e) {
    $datepick.show().position({
      my: "left top",
      at: "right top",
      of: $("#select-date")
    });
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<SELECT id="select-date">
      <option value="1">TODAY</option>
      <option value="2">TOMORROW</option>
      <option selected value="3">THIS WEEK</option>
      <option value="4">NEXT WEEK</option>
      <option value="5">THIS MONTH</option>
      <option value="6">NEXT MONTH</option>
      <option value="7">CHOOSE DATE</option>
    </SELECT>
<div id="datepicker"></div></code>```

Body:
This should be really easy, but I have been going around in circles with it for the past three hours... I know that I should change the ID of SELECT to match that of the jquery function, but there is another step (obviously) that I am missing.

I am using the jqueryui datepicker, and I simply want it to pop up when a particular value is chosen with a 'select' dropdown, rather than when an 'input' field is clicked. Here is the code, thanks in advance for your help:

    <SELECT id="">
        <option value="1">TODAY</option>
        <option value="2">TOMORROW</option>
        <option selected value="3">THIS WEEK</option>
        <option value="4">NEXT WEEK</option>
        <option value="5">THIS MONTH</option>
        <option value="6">NEXT MONTH</option>
        <option value="7">CALENDAR SHOULD POP UP WHEN THIS OPTION IS SELECTED</option>
    </SELECT>

<input type="text" id="datepicker" value="INSTEAD OF THIS">

Body:
Yes, you can do things like this. A switch() will help identify what to do when specific options are selected in the drop down, and they can then tell the .datepicker() what to do.

$(function() {
  $("#datepicker").datepicker({
    minDate: 0,
    maxDate: "+2Y"
  }).hide();
  $("#select-date").change(function(e) {
    if ($(this).val() == "7") {
      $("#datepicker").show().datepicker("show");
    } else {
      $("#datepicker").datepicker("hide").hide();
    }
  });
});

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<SELECT id="select-date">
  <option value="1">TODAY</option>
  <option value="2">TOMORROW</option>
  <option selected value="3">THIS WEEK</option>
  <option value="4">NEXT WEEK</option>
  <option value="5">THIS MONTH</option>
  <option value="6">NEXT MONTH</option>
  <option value="7">CALENDAR</option>
</SELECT>
<input type="text" id="datepicker">

Now you can also do this with a ComboBox or Split Button if you were interested. To fit with the site more, you may consider:

$(function() {
  var $datepick = $("#datepicker"),
    $opt7 = $("#select-date option[value='7']");
  $datepick.datepicker({
    minDate: 0,
    maxDate: "+2Y",
    onSelect: function(sDate, dObj) {
      $opt7.html(sDate);
      $datepick.hide();
    }
  }).hide();
  $opt7.click(function(e) {
    $datepick.show().position({
      my: "left top",
      at: "right top",
      of: $("#select-date")
    });
  });
});

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<SELECT id="select-date">
      <option value="1">TODAY</option>
      <option value="2">TOMORROW</option>
      <option selected value="3">THIS WEEK</option>
      <option value="4">NEXT WEEK</option>
      <option value="5">THIS MONTH</option>
      <option value="6">NEXT MONTH</option>
      <option value="7">CHOOSE DATE</option>
    </SELECT>
<div id="datepicker"></div>


问:
Spring Controller double validation for @ModelAttribute object
I have implemented controller with method:

```<code>public Page<EventDto> search(@ModelAttribute @Valid EventsCriteria criteria){...}
</code>```

It works. EventsCriteria did not have special separate validator for itself, because it has inner annotation checkers like @NotNull @NotEmpty. Right now situation is changed and it's not enough to have only this validators. so I've added and registered correspond service to verify some sates.

I want service to verify additional composite cases and single validation like before. But my single inner annotation checkers like @NotNull @NotEmpty do not work any more.

Am I configured something incorrectly or it can't work in in same time(specified service and inner checkers)?

My validator example (as it was asked in comments)

There are nothing special, if you know spring, so I missed this part like unimportant to concentrate your attention on my question.

```<code>@Component
public class EventsCriteriaValidator implements Validator {

    public static final String INVALID_RAGE_PARAMETERS_SPECIFIED = "Invalid rage parameters: please specify " +
            "'from' and 'to' or page 'size";

    @Override
    public boolean supports(Class<?> clazz) {
        return clazz.isAssignableFrom(EventsCriteria.class);
    }

    @Override
    public void validate(Object target, Errors errors) {
        EventsCriteria toValidate = (EventsCriteria) target;
        validateComplexRestriction(toValidate, errors);
    }

    private void validateComplexRestriction(EventsCriteria toValidate, Errors errors) {
        if (toValidate.isRangeEmpty() && toValidate.getSize() == 0) {
            errors.rejectValue(SIZE_FIELD, null, INVALID_RAGE_PARAMETERS_SPECIFIED);
        }
    }

}
</code>```

答:
Just make your Validator extend LocalValidatorFactoryBean and then call super.validate(target, errors) in your validate method like this:

```<code>@Override
public void validate(Object target, Errors errors) {
   super.validate(target, errors);

   EventsCriteria toValidate = (EventsCriteria) target;
   validateComplexRestriction(toValidate, errors);
}
</code>```

Body:
I have implemented controller with method:

public Page<EventDto> search(@ModelAttribute @Valid EventsCriteria criteria){...}

It works. EventsCriteria did not have special separate validator for itself, because it has inner annotation checkers like @NotNull @NotEmpty. Right now situation is changed and it's not enough to have only this validators. so I've added and registered correspond service to verify some sates.

I want service to verify additional composite cases and single validation like before. But my single inner annotation checkers like @NotNull @NotEmpty do not work any more.

Am I configured something incorrectly or it can't work in in same time(specified service and inner checkers)?

My validator example (as it was asked in comments)

There are nothing special, if you know spring, so I missed this part like unimportant to concentrate your attention on my question.

@Component
public class EventsCriteriaValidator implements Validator {

    public static final String INVALID_RAGE_PARAMETERS_SPECIFIED = "Invalid rage parameters: please specify " +
            "'from' and 'to' or page 'size";

    @Override
    public boolean supports(Class<?> clazz) {
        return clazz.isAssignableFrom(EventsCriteria.class);
    }

    @Override
    public void validate(Object target, Errors errors) {
        EventsCriteria toValidate = (EventsCriteria) target;
        validateComplexRestriction(toValidate, errors);
    }

    private void validateComplexRestriction(EventsCriteria toValidate, Errors errors) {
        if (toValidate.isRangeEmpty() && toValidate.getSize() == 0) {
            errors.rejectValue(SIZE_FIELD, null, INVALID_RAGE_PARAMETERS_SPECIFIED);
        }
    }

}

Body:
Just make your Validator extend LocalValidatorFactoryBean and then call super.validate(target, errors) in your validate method like this:

@Override
public void validate(Object target, Errors errors) {
   super.validate(target, errors);

   EventsCriteria toValidate = (EventsCriteria) target;
   validateComplexRestriction(toValidate, errors);
}