问:
Scala method with type parameter
this is my situation:

```<code>trait BPO
trait BBO
class PointBO extends BBO
class PointPO extends BPO
class CircleBO extends BBO
class CirclePO extends BPO

trait Mapper[-P <: BPO,+B <: BBO] {
  def mapAsBBO(bpo: P): B
}

class PointMapper extends Mapper[PointPO,PointBO]{
  override def mapAsBBO(bpo: PointPO): PointBO = {
    println("Construct point")
    new PointBO
  }
}

class CircleMapper extends Mapper[CirclePO,CircleBO] {
  override def mapAsBBO(bpo: CirclePO): CircleBO = {
    println("Construct circle")
    new CircleBO
  }
}

class Registry{
  def method[P,B](po:P,bo:B)(implicit mapper: Mapper[P,B]) = mapper.mapAsBBO(po)
}

val r = new Registry
val s = r.method[PointPO,PointBO](new PointPO,new PointBO)
</code>```

I would like to pass to the method method, just both classes involved in the mapping and let Scala type inference to implement for me the right mapper, is it possible?

I'm receiving this error:

Error:(31, 40) could not find implicit value for parameter mapper: A$A191.this.Mapper[A$A191.this.PointPO,A$A191.this.PointBO]
lazy val s = r.method[PointPO,PointBO](new PointPO,new PointBO)
                                      ^

Another way should be fine for me, would be called the method method passing it just the mapper class:

```<code>val s = r.method[PointMapper](new PointPO,new PointBO)
</code>```

Is this any way to accomplish one of this street and if one of them is better that the other, plus a little explanation.

EDIT:

In origin I would like to make trait Mapper with both parameters covariant:

```<code>trait Mapper[+P <: BPO,+B <: BBO] {
  def mapAsBBO(bpo: P): B
}
</code>```

like that would be fine the assignment below:

```<code>val d:Mapper[BPO,BBO] = new CircleMapper()
</code>```

but the compiler complain me about P parameter that must be controvariant

There is an alternative solution to do that?

Regards.

答:
Well first of all, in your code the implicit mapper is missing ( as mentioned in the exception ).

So I added these below.
Aside from that if you add the implicit values for your mappers, you have a type boundary issue, as the method needs the same type boundaries as your Mapper, so I also adapted this:

```<code>trait BPO
trait BBO
class PointBO extends BBO
class PointPO extends BPO
class CircleBO extends BBO
class CirclePO extends BPO

trait Mapper[P <: BPO,B <: BBO] {
  def mapAsBBO(bpo: P): B
}

class PointMapper extends Mapper[PointPO,PointBO]{
  override def mapAsBBO(bpo: PointPO): PointBO = {
    println("Construct point")
    new PointBO
  }
}

class CircleMapper extends Mapper[CirclePO,CircleBO] {
  override def mapAsBBO(bpo: CirclePO): CircleBO = {
    println("Construct circle")
    new CircleBO
  }
}

class Registry{
  def method[P <: BPO,B <: BBO](po:P,bo:B)(implicit mapper: Mapper[P,B]) = mapper.mapAsBBO(po)
}

implicit val pMapper = new PointMapper()
implicit val cMapper = new CircleMapper()

val r = new Registry
r.method(new PointPO,new PointBO)
</code>```

EDIT

Removed explicit type parameters from r.method because they are inferred by the compiler. Also removed co- and contra-variance from the Mapper type parameters, since for this functionality it is not needed and no further context is given as to why it is being used, so it would only lead to confusion.

EDIT2

In case you have no reason to instantiate the mapper classes you could also define them as implicit objects:

```<code>trait BPO
trait BBO
class PointBO extends BBO
class PointPO extends BPO
class CircleBO extends BBO
class CirclePO extends BPO

trait Mapper[P <: BPO,B <: BBO] {
  def mapAsBBO(bpo: P): B
}

implicit object PointMapper extends Mapper[PointPO,PointBO]{
  override def mapAsBBO(bpo: PointPO): PointBO = {
    println("Construct point")
    new PointBO
  }
}

implicit object CircleMapper extends Mapper[CirclePO,CircleBO] {
  override def mapAsBBO(bpo: CirclePO): CircleBO = {
    println("Construct circle")
    new CircleBO
  }
}

class Registry{
  def method[P <: BPO,B <: BBO](po:P,bo:B)(implicit mapper: Mapper[P,B]) = mapper.mapAsBBO(po)
}

val r = new Registry
r.method(new PointPO,new PointBO)
</code>```

Title: Scala method with type parameter

Body:
this is my situation:

trait BPO
trait BBO
class PointBO extends BBO
class PointPO extends BPO
class CircleBO extends BBO
class CirclePO extends BPO

trait Mapper[-P <: BPO,+B <: BBO] {
  def mapAsBBO(bpo: P): B
}

class PointMapper extends Mapper[PointPO,PointBO]{
  override def mapAsBBO(bpo: PointPO): PointBO = {
    println("Construct point")
    new PointBO
  }
}

class CircleMapper extends Mapper[CirclePO,CircleBO] {
  override def mapAsBBO(bpo: CirclePO): CircleBO = {
    println("Construct circle")
    new CircleBO
  }
}

class Registry{
  def method[P,B](po:P,bo:B)(implicit mapper: Mapper[P,B]) = mapper.mapAsBBO(po)
}

val r = new Registry
val s = r.method[PointPO,PointBO](new PointPO,new PointBO)

I would like to pass to the method method, just both classes involved in the mapping and let Scala type inference to implement for me the right mapper, is it possible?

I'm receiving this error:

Error:(31, 40) could not find implicit value for parameter mapper: A$A191.this.Mapper[A$A191.this.PointPO,A$A191.this.PointBO]
lazy val s = r.method[PointPO,PointBO](new PointPO,new PointBO)
                                      ^

Another way should be fine for me, would be called the method method passing it just the mapper class:

val s = r.method[PointMapper](new PointPO,new PointBO)

Is this any way to accomplish one of this street and if one of them is better that the other, plus a little explanation.

EDIT:

In origin I would like to make trait Mapper with both parameters covariant:

trait Mapper[+P <: BPO,+B <: BBO] {
  def mapAsBBO(bpo: P): B
}

like that would be fine the assignment below:

val d:Mapper[BPO,BBO] = new CircleMapper()

but the compiler complain me about P parameter that must be controvariant

There is an alternative solution to do that?

Regards.

Body:
Well first of all, in your code the implicit mapper is missing ( as mentioned in the exception ).

So I added these below.
Aside from that if you add the implicit values for your mappers, you have a type boundary issue, as the method needs the same type boundaries as your Mapper, so I also adapted this:

trait BPO
trait BBO
class PointBO extends BBO
class PointPO extends BPO
class CircleBO extends BBO
class CirclePO extends BPO

trait Mapper[P <: BPO,B <: BBO] {
  def mapAsBBO(bpo: P): B
}

class PointMapper extends Mapper[PointPO,PointBO]{
  override def mapAsBBO(bpo: PointPO): PointBO = {
    println("Construct point")
    new PointBO
  }
}

class CircleMapper extends Mapper[CirclePO,CircleBO] {
  override def mapAsBBO(bpo: CirclePO): CircleBO = {
    println("Construct circle")
    new CircleBO
  }
}

class Registry{
  def method[P <: BPO,B <: BBO](po:P,bo:B)(implicit mapper: Mapper[P,B]) = mapper.mapAsBBO(po)
}

implicit val pMapper = new PointMapper()
implicit val cMapper = new CircleMapper()

val r = new Registry
r.method(new PointPO,new PointBO)

EDIT

Removed explicit type parameters from r.method because they are inferred by the compiler. Also removed co- and contra-variance from the Mapper type parameters, since for this functionality it is not needed and no further context is given as to why it is being used, so it would only lead to confusion.

EDIT2

In case you have no reason to instantiate the mapper classes you could also define them as implicit objects:

trait BPO
trait BBO
class PointBO extends BBO
class PointPO extends BPO
class CircleBO extends BBO
class CirclePO extends BPO

trait Mapper[P <: BPO,B <: BBO] {
  def mapAsBBO(bpo: P): B
}

implicit object PointMapper extends Mapper[PointPO,PointBO]{
  override def mapAsBBO(bpo: PointPO): PointBO = {
    println("Construct point")
    new PointBO
  }
}

implicit object CircleMapper extends Mapper[CirclePO,CircleBO] {
  override def mapAsBBO(bpo: CirclePO): CircleBO = {
    println("Construct circle")
    new CircleBO
  }
}

class Registry{
  def method[P <: BPO,B <: BBO](po:P,bo:B)(implicit mapper: Mapper[P,B]) = mapper.mapAsBBO(po)
}

val r = new Registry
r.method(new PointPO,new PointBO)


来源: stackexchange

问:
Unexpected result with polyfit in python
Permit me first to introduce the background of the question:

I came into a quiz, which gave me a data set and a Logistic equation:

Then it asked whether that model can be linearized, and if it is, use the linear model to evaluate the value of a and k.

I tried to linearize it like this:
And coded in python:

```<code>t = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
y = np.array([43.65, 109.86, 187.21, 312.67, 496.58, 707.65, 960.25, 1238.75, 1560, 1824.29, 2199, 2438.89, 2737.71])
yAss = np.log(3000/y - 1)
cof = np.polyfit(t, yAss, deg = 1)
a = math.e**(cof[0]);
k = -cof[1];
yAfter = 3000 / (1 + a*math.e**(-k*t))

sizeScalar = 10
fig = plt.figure(figsize = (sizeScalar*1.1, sizeScalar))
plt.plot(t, y, 'o', markersize = sizeScalar*0.75)
plt.plot(t, yAfter, 'r-')
plt.grid(True)
plt.show()
</code>```

And got that, which is obviously incorrect:
Then by coincident, I changed some part of the code:

```<code>t = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
y = np.array([43.65, 109.86, 187.21, 312.67, 496.58, 707.65, 960.25, 1238.75, 1560, 1824.29, 2199, 2438.89, 2737.71])
yAss = np.log(3000/y - 1)
cof = np.polyfit(t, yAss, deg = 1)
a = math.e**(-cof[1]); #<<<===============here. Before: a = math.e**(cof[0])
k = cof[0]; #<<<==========================and here, Before: k = -cof[1]
temp = 3000 / (1 + a*math.e**(-k*t))
yAfter = []
for itera in temp: #<<<=======================add this
    yAfter.append(3000 - itera)

sizeScalar = 10
fig = plt.figure(figsize = (sizeScalar*1.1, sizeScalar))
plt.plot(t, y, 'o', markersize = sizeScalar*0.75)
plt.plot(t, yAfter, 'r-')
plt.grid(True)
plt.show()
</code>```

And received a sequence that seems to be right?
But how could it be? I think cof[0] IS beta, and cof1 IS -k, if it is, my previous code should just have some wrong concept. But change the order and sign of the coefficient, I got a result that fits well?! Is it purely coincident?
And what might be the right answer of the quiz?

答:
np.polyfit returns the highest degree first: https://docs.scipy.org/doc/numpy/reference/generated/numpy.polyfit.html#numpy.polyfit

Use:

```<code>k = -cof[0]
a = exp(cof[1])
</code>```

Also, you can use NumPy's exponential:

```<code>yAfter = 3000/(1+a*np.exp(-k*t)))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Permit me first to introduce the background of the question:

I came into a quiz, which gave me a data set and a Logistic equation:

Then it asked whether that model can be linearized, and if it is, use the linear model to evaluate the value of a and k.

I tried to linearize it like this:
And coded in python:

t = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
y = np.array([43.65, 109.86, 187.21, 312.67, 496.58, 707.65, 960.25, 1238.75, 1560, 1824.29, 2199, 2438.89, 2737.71])
yAss = np.log(3000/y - 1)
cof = np.polyfit(t, yAss, deg = 1)
a = math.e**(cof[0]);
k = -cof[1];
yAfter = 3000 / (1 + a*math.e**(-k*t))

sizeScalar = 10
fig = plt.figure(figsize = (sizeScalar*1.1, sizeScalar))
plt.plot(t, y, 'o', markersize = sizeScalar*0.75)
plt.plot(t, yAfter, 'r-')
plt.grid(True)
plt.show()

And got that, which is obviously incorrect:
Then by coincident, I changed some part of the code:

t = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
y = np.array([43.65, 109.86, 187.21, 312.67, 496.58, 707.65, 960.25, 1238.75, 1560, 1824.29, 2199, 2438.89, 2737.71])
yAss = np.log(3000/y - 1)
cof = np.polyfit(t, yAss, deg = 1)
a = math.e**(-cof[1]); #<<<===============here. Before: a = math.e**(cof[0])
k = cof[0]; #<<<==========================and here, Before: k = -cof[1]
temp = 3000 / (1 + a*math.e**(-k*t))
yAfter = []
for itera in temp: #<<<=======================add this
    yAfter.append(3000 - itera)

sizeScalar = 10
fig = plt.figure(figsize = (sizeScalar*1.1, sizeScalar))
plt.plot(t, y, 'o', markersize = sizeScalar*0.75)
plt.plot(t, yAfter, 'r-')
plt.grid(True)
plt.show()

And received a sequence that seems to be right?
But how could it be? I think cof[0] IS beta, and cof1 IS -k, if it is, my previous code should just have some wrong concept. But change the order and sign of the coefficient, I got a result that fits well?! Is it purely coincident?
And what might be the right answer of the quiz?

Body:
np.polyfit returns the highest degree first: https://docs.scipy.org/doc/numpy/reference/generated/numpy.polyfit.html#numpy.polyfit

Use:

k = -cof[0]
a = exp(cof[1])

Also, you can use NumPy's exponential:

yAfter = 3000/(1+a*np.exp(-k*t)))


问:
AWS CloudFormation/API Gateway gives 'Invalid Resource identifier specified'
I have been trying to use CloudFormation to deploy to API Gateway, however, I constantly run into the same issue with my method resources. The stack deployments keep failing with 'Invalid Resource identifier specified'.

Here is my method resource from my CloudFormation template:

```<code>"UsersPut": {
        "Type": "AWS::ApiGateway::Method",
        "Properties": {
            "ResourceId": "UsersResource",
            "RestApiId": "MyApi",
            "ApiKeyRequired": true,
            "AuthorizationType": "NONE",
            "HttpMethod": "PUT",
            "Integration": {
                "Type": "AWS_PROXY",
                "IntegrationHttpMethod": "POST",
                "Uri": {
                    "Fn::Join": ["", ["arn:aws:apigateway:", {
                        "Ref": "AWS::Region"
                    }, ":lambda:path/2015-03-31/functions/", {
                        "Fn::GetAtt": ["MyLambdaFunc", "Arn"]
                    }, "/invocations"]]
                }
            },
            "MethodResponses": [{
                "StatusCode": 200
            }]
        }
    }
</code>```

Is anyone able to help me figure out why this keeps failing the stack deployment?

UPDATE: I forgot to mention that I had also tried using references to add the resource ID, that also gave me the same error:

```<code>"UsersPut": {
        "Type": "AWS::ApiGateway::Method",
        "Properties": {
            "ResourceId": {
                "Ref": "UsersResource"
            },
            "RestApiId": "MyApi",
            "ApiKeyRequired": true,
            "AuthorizationType": "NONE",
            "HttpMethod": "PUT",
            "Integration": {
                "Type": "AWS_PROXY",
                "IntegrationHttpMethod": "POST",
                "Uri": {
                    "Fn::Join": ["", ["arn:aws:apigateway:", {
                        "Ref": "AWS::Region"
                    }, ":lambda:path/2015-03-31/functions/", {
                        "Fn::GetAtt": ["MyLambdaFunc", "Arn"]
                    }, "/invocations"]]
                }
            },
            "MethodResponses": [{
                "StatusCode": 200
            }]
        }
    }
</code>```

Here is the full CloudFormation template:

```<code>{
"AWSTemplateFormatVersion": "2010-09-09",
"Resources": {
    "LambdaDynamoDBRole": {
        "Type": "AWS::IAM::Role",
        "Properties": {
            "AssumeRolePolicyDocument": {
                "Version": "2012-10-17",
                "Statement": [{
                    "Effect": "Allow",
                    "Principal": {
                        "Service": [
                            "lambda.amazonaws.com"
                        ]
                    },
                    "Action": [
                        "sts:AssumeRole"
                    ]
                }]
            },
            "Path": "/",
            "Policies": [{
                "PolicyName": "DynamoReadWritePolicy",
                "PolicyDocument": {
                    "Version": "2012-10-17",
                    "Statement": [{
                        "Sid": "1",
                        "Action": [
                            "dynamodb:DeleteItem",
                            "dynamodb:GetItem",
                            "dynamodb:PutItem",
                            "dynamodb:Query",
                            "dynamodb:Scan",
                            "dynamodb:UpdateItem"
                        ],
                        "Effect": "Allow",
                        "Resource": "*"
                    }, {
                        "Sid": "2",
                        "Resource": "*",
                        "Action": [
                            "logs:CreateLogGroup",
                            "logs:CreateLogStream",
                            "logs:PutLogEvents"
                        ],
                        "Effect": "Allow"
                    }]
                }
            }]
        }
    },
    "MyFirstLambdaFn": {
        "Type": "AWS::Lambda::Function",
        "Properties": {
            "Code": {
                "S3Bucket": "myfirstlambdafn",
                "S3Key": "lambda_handler.py.zip"
            },
            "Description": "",
            "FunctionName": "MyFirstLambdaFn",
            "Handler": "lambda_function.lambda_handler",
            "MemorySize": 512,
            "Role": {
                "Fn::GetAtt": [
                    "LambdaDynamoDBRole",
                    "Arn"
                ]
            },
            "Runtime": "python2.7",
            "Timeout": 3
        },
        "DependsOn": "LambdaDynamoDBRole"
    },
    "MySecondLambdaFn": {
        "Type": "AWS::Lambda::Function",
        "Properties": {
            "Code": {
                "S3Bucket": "mysecondlambdafn",
                "S3Key": "lambda_handler.py.zip"
            },
            "Description": "",
            "FunctionName": "MySecondLambdaFn",
            "Handler": "lambda_function.lambda_handler",
            "MemorySize": 512,
            "Role": {
                "Fn::GetAtt": [
                    "LambdaDynamoDBRole",
                    "Arn"
                ]
            },
            "Runtime": "python2.7",
            "Timeout": 3
        },
        "DependsOn": "LambdaDynamoDBRole"
    },
    "MyApi": {
        "Type": "AWS::ApiGateway::RestApi",
        "Properties": {
            "Name": "Project Test API",
            "Description": "Project Test API",
            "FailOnWarnings": true
        }
    },
    "FirstUserPropertyModel": {
        "Type": "AWS::ApiGateway::Model",
        "Properties": {
            "ContentType": "application/json",
            "Name": "FirstUserPropertyModel",
            "RestApiId": {
                "Ref": "MyApi"
            },
            "Schema": {
                "$schema": "http://json-schema.org/draft-04/schema#",
                "title": "FirstUserPropertyModel",
                "type": "object",
                "properties": {
                    "Email": {
                        "type": "string"
                    }
                }
            }
        }
    },
    "SecondUserPropertyModel": {
        "Type": "AWS::ApiGateway::Model",
        "Properties": {
            "ContentType": "application/json",
            "Name": "SecondUserPropertyModel",
            "RestApiId": {
                "Ref": "MyApi"
            },
            "Schema": {
                "$schema": "http://json-schema.org/draft-04/schema#",
                "title": "SecondUserPropertyModel",
                "type": "object",
                "properties": {
                    "Name": {
                        "type": "string"
                    }
                }
            }
        }
    },
    "ErrorCfn": {
        "Type": "AWS::ApiGateway::Model",
        "Properties": {
            "ContentType": "application/json",
            "Name": "ErrorCfn",
            "RestApiId": {
                "Ref": "MyApi"
            },
            "Schema": {
                "$schema": "http://json-schema.org/draft-04/schema#",
                "title": "Error Schema",
                "type": "object",
                "properties": {
                    "message": {
                        "type": "string"
                    }
                }
            }
        }
    },
    "UsersResource": {
        "Type": "AWS::ApiGateway::Resource",
        "Properties": {
            "RestApiId": {
                "Ref": "MyApi"
            },
            "ParentId": {
                "Fn::GetAtt": ["MyApi", "RootResourceId"]
            },
            "PathPart": "users"
        }
    },
    "UsersPost": {
        "Type": "AWS::ApiGateway::Method",
        "Properties": {
            "ResourceId": {
                "Ref": "UsersResource"
            },
            "RestApiId": "MyApi",
            "ApiKeyRequired": true,
            "AuthorizationType": "NONE",
            "HttpMethod": "POST",
            "Integration": {
                "Type": "AWS_PROXY",
                "IntegrationHttpMethod": "POST",
                "Uri": {
                    "Fn::Join": ["", ["arn:aws:apigateway:", {
                        "Ref": "AWS::Region"
                    }, ":lambda:path/2015-03-31/functions/", {
                        "Fn::GetAtt": ["MyFirstLambdaFn", "Arn"]
                    }, "/invocations"]]
                }
            },
            "MethodResponses": [{
                "ResponseModels": {
                    "application/json": {
                        "Ref": "FirstUserPropertyModel"
                    }
                },
                "StatusCode": 200
            }, {
                "ResponseModels": {
                    "application/json": {
                        "Ref": "ErrorCfn"
                    }
                },
                "StatusCode": 404
            }, {
                "ResponseModels": {
                    "application/json": {
                        "Ref": "ErrorCfn"
                    }
                },
                "StatusCode": 500
            }]
        }
    },
    "UsersPut": {
        "Type": "AWS::ApiGateway::Method",
        "Properties": {
            "ResourceId": {
                "Ref": "UsersResource"
            },
            "RestApiId": "MyApi",
            "ApiKeyRequired": true,
            "AuthorizationType": "NONE",
            "HttpMethod": "PUT",
            "Integration": {
                "Type": "AWS_PROXY",
                "IntegrationHttpMethod": "POST",
                "Uri": {
                    "Fn::Join": ["", ["arn:aws:apigateway:", {
                        "Ref": "AWS::Region"
                    }, ":lambda:path/2015-03-31/functions/", {
                        "Fn::GetAtt": ["MySecondLambdaFn", "Arn"]
                    }, "/invocations"]]
                }
            },
            "MethodResponses": [{
                "ResponseModels": {
                    "application/json": {
                        "Ref": "SecondUserPropertyModel"
                    }
                },
                "StatusCode": 200
            }, {
                "ResponseModels": {
                    "application/json": {
                        "Ref": "ErrorCfn"
                    }
                },
                "StatusCode": 404
            }, {
                "ResponseModels": {
                    "application/json": {
                        "Ref": "ErrorCfn"
                    }
                },
                "StatusCode": 500
            }]
        }
    },
    "RestApiDeployment": {
        "Type": "AWS::ApiGateway::Deployment",
        "Properties": {
            "RestApiId": {
                "Ref": "MyApi"
            },
            "StageName": "Prod"
        },
        "DependsOn": ["UsersPost", "UsersPut"]
    }
},
"Description": "Project description"
</code>```

}

答:
ResourceId must be a reference to a cloudformation resource, not a simple string.

e.g.

```<code>  ResourceId:
    Ref: UsersResource
</code>```

Body:
I have been trying to use CloudFormation to deploy to API Gateway, however, I constantly run into the same issue with my method resources. The stack deployments keep failing with 'Invalid Resource identifier specified'.

Here is my method resource from my CloudFormation template:

"UsersPut": {
        "Type": "AWS::ApiGateway::Method",
        "Properties": {
            "ResourceId": "UsersResource",
            "RestApiId": "MyApi",
            "ApiKeyRequired": true,
            "AuthorizationType": "NONE",
            "HttpMethod": "PUT",
            "Integration": {
                "Type": "AWS_PROXY",
                "IntegrationHttpMethod": "POST",
                "Uri": {
                    "Fn::Join": ["", ["arn:aws:apigateway:", {
                        "Ref": "AWS::Region"
                    }, ":lambda:path/2015-03-31/functions/", {
                        "Fn::GetAtt": ["MyLambdaFunc", "Arn"]
                    }, "/invocations"]]
                }
            },
            "MethodResponses": [{
                "StatusCode": 200
            }]
        }
    }

Is anyone able to help me figure out why this keeps failing the stack deployment?

UPDATE: I forgot to mention that I had also tried using references to add the resource ID, that also gave me the same error:

"UsersPut": {
        "Type": "AWS::ApiGateway::Method",
        "Properties": {
            "ResourceId": {
                "Ref": "UsersResource"
            },
            "RestApiId": "MyApi",
            "ApiKeyRequired": true,
            "AuthorizationType": "NONE",
            "HttpMethod": "PUT",
            "Integration": {
                "Type": "AWS_PROXY",
                "IntegrationHttpMethod": "POST",
                "Uri": {
                    "Fn::Join": ["", ["arn:aws:apigateway:", {
                        "Ref": "AWS::Region"
                    }, ":lambda:path/2015-03-31/functions/", {
                        "Fn::GetAtt": ["MyLambdaFunc", "Arn"]
                    }, "/invocations"]]
                }
            },
            "MethodResponses": [{
                "StatusCode": 200
            }]
        }
    }

Here is the full CloudFormation template:

{
"AWSTemplateFormatVersion": "2010-09-09",
"Resources": {
    "LambdaDynamoDBRole": {
        "Type": "AWS::IAM::Role",
        "Properties": {
            "AssumeRolePolicyDocument": {
                "Version": "2012-10-17",
                "Statement": [{
                    "Effect": "Allow",
                    "Principal": {
                        "Service": [
                            "lambda.amazonaws.com"
                        ]
                    },
                    "Action": [
                        "sts:AssumeRole"
                    ]
                }]
            },
            "Path": "/",
            "Policies": [{
                "PolicyName": "DynamoReadWritePolicy",
                "PolicyDocument": {
                    "Version": "2012-10-17",
                    "Statement": [{
                        "Sid": "1",
                        "Action": [
                            "dynamodb:DeleteItem",
                            "dynamodb:GetItem",
                            "dynamodb:PutItem",
                            "dynamodb:Query",
                            "dynamodb:Scan",
                            "dynamodb:UpdateItem"
                        ],
                        "Effect": "Allow",
                        "Resource": "*"
                    }, {
                        "Sid": "2",
                        "Resource": "*",
                        "Action": [
                            "logs:CreateLogGroup",
                            "logs:CreateLogStream",
                            "logs:PutLogEvents"
                        ],
                        "Effect": "Allow"
                    }]
                }
            }]
        }
    },
    "MyFirstLambdaFn": {
        "Type": "AWS::Lambda::Function",
        "Properties": {
            "Code": {
                "S3Bucket": "myfirstlambdafn",
                "S3Key": "lambda_handler.py.zip"
            },
            "Description": "",
            "FunctionName": "MyFirstLambdaFn",
            "Handler": "lambda_function.lambda_handler",
            "MemorySize": 512,
            "Role": {
                "Fn::GetAtt": [
                    "LambdaDynamoDBRole",
                    "Arn"
                ]
            },
            "Runtime": "python2.7",
            "Timeout": 3
        },
        "DependsOn": "LambdaDynamoDBRole"
    },
    "MySecondLambdaFn": {
        "Type": "AWS::Lambda::Function",
        "Properties": {
            "Code": {
                "S3Bucket": "mysecondlambdafn",
                "S3Key": "lambda_handler.py.zip"
            },
            "Description": "",
            "FunctionName": "MySecondLambdaFn",
            "Handler": "lambda_function.lambda_handler",
            "MemorySize": 512,
            "Role": {
                "Fn::GetAtt": [
                    "LambdaDynamoDBRole",
                    "Arn"
                ]
            },
            "Runtime": "python2.7",
            "Timeout": 3
        },
        "DependsOn": "LambdaDynamoDBRole"
    },
    "MyApi": {
        "Type": "AWS::ApiGateway::RestApi",
        "Properties": {
            "Name": "Project Test API",
            "Description": "Project Test API",
            "FailOnWarnings": true
        }
    },
    "FirstUserPropertyModel": {
        "Type": "AWS::ApiGateway::Model",
        "Properties": {
            "ContentType": "application/json",
            "Name": "FirstUserPropertyModel",
            "RestApiId": {
                "Ref": "MyApi"
            },
            "Schema": {
                "$schema": "http://json-schema.org/draft-04/schema#",
                "title": "FirstUserPropertyModel",
                "type": "object",
                "properties": {
                    "Email": {
                        "type": "string"
                    }
                }
            }
        }
    },
    "SecondUserPropertyModel": {
        "Type": "AWS::ApiGateway::Model",
        "Properties": {
            "ContentType": "application/json",
            "Name": "SecondUserPropertyModel",
            "RestApiId": {
                "Ref": "MyApi"
            },
            "Schema": {
                "$schema": "http://json-schema.org/draft-04/schema#",
                "title": "SecondUserPropertyModel",
                "type": "object",
                "properties": {
                    "Name": {
                        "type": "string"
                    }
                }
            }
        }
    },
    "ErrorCfn": {
        "Type": "AWS::ApiGateway::Model",
        "Properties": {
            "ContentType": "application/json",
            "Name": "ErrorCfn",
            "RestApiId": {
                "Ref": "MyApi"
            },
            "Schema": {
                "$schema": "http://json-schema.org/draft-04/schema#",
                "title": "Error Schema",
                "type": "object",
                "properties": {
                    "message": {
                        "type": "string"
                    }
                }
            }
        }
    },
    "UsersResource": {
        "Type": "AWS::ApiGateway::Resource",
        "Properties": {
            "RestApiId": {
                "Ref": "MyApi"
            },
            "ParentId": {
                "Fn::GetAtt": ["MyApi", "RootResourceId"]
            },
            "PathPart": "users"
        }
    },
    "UsersPost": {
        "Type": "AWS::ApiGateway::Method",
        "Properties": {
            "ResourceId": {
                "Ref": "UsersResource"
            },
            "RestApiId": "MyApi",
            "ApiKeyRequired": true,
            "AuthorizationType": "NONE",
            "HttpMethod": "POST",
            "Integration": {
                "Type": "AWS_PROXY",
                "IntegrationHttpMethod": "POST",
                "Uri": {
                    "Fn::Join": ["", ["arn:aws:apigateway:", {
                        "Ref": "AWS::Region"
                    }, ":lambda:path/2015-03-31/functions/", {
                        "Fn::GetAtt": ["MyFirstLambdaFn", "Arn"]
                    }, "/invocations"]]
                }
            },
            "MethodResponses": [{
                "ResponseModels": {
                    "application/json": {
                        "Ref": "FirstUserPropertyModel"
                    }
                },
                "StatusCode": 200
            }, {
                "ResponseModels": {
                    "application/json": {
                        "Ref": "ErrorCfn"
                    }
                },
                "StatusCode": 404
            }, {
                "ResponseModels": {
                    "application/json": {
                        "Ref": "ErrorCfn"
                    }
                },
                "StatusCode": 500
            }]
        }
    },
    "UsersPut": {
        "Type": "AWS::ApiGateway::Method",
        "Properties": {
            "ResourceId": {
                "Ref": "UsersResource"
            },
            "RestApiId": "MyApi",
            "ApiKeyRequired": true,
            "AuthorizationType": "NONE",
            "HttpMethod": "PUT",
            "Integration": {
                "Type": "AWS_PROXY",
                "IntegrationHttpMethod": "POST",
                "Uri": {
                    "Fn::Join": ["", ["arn:aws:apigateway:", {
                        "Ref": "AWS::Region"
                    }, ":lambda:path/2015-03-31/functions/", {
                        "Fn::GetAtt": ["MySecondLambdaFn", "Arn"]
                    }, "/invocations"]]
                }
            },
            "MethodResponses": [{
                "ResponseModels": {
                    "application/json": {
                        "Ref": "SecondUserPropertyModel"
                    }
                },
                "StatusCode": 200
            }, {
                "ResponseModels": {
                    "application/json": {
                        "Ref": "ErrorCfn"
                    }
                },
                "StatusCode": 404
            }, {
                "ResponseModels": {
                    "application/json": {
                        "Ref": "ErrorCfn"
                    }
                },
                "StatusCode": 500
            }]
        }
    },
    "RestApiDeployment": {
        "Type": "AWS::ApiGateway::Deployment",
        "Properties": {
            "RestApiId": {
                "Ref": "MyApi"
            },
            "StageName": "Prod"
        },
        "DependsOn": ["UsersPost", "UsersPut"]
    }
},
"Description": "Project description"

}

Body:
ResourceId must be a reference to a cloudformation resource, not a simple string.

e.g.

  ResourceId:
    Ref: UsersResource


问:
How to design a method that contains lots of IF's or Switch statements
How can i make the design of this class more dynamic so i can add new extensions and types as required.

```<code>public class Processor
{
    public Processor(string fileName)
    {
        string extension = Path.GetExtension(fileName);
        if(extension == "jpg" || extension == "gif" || extension == "png")
        {
            //Process Image file type
        }
        else if(extension == "xls" || extension == "xlsx")
        {
            //Process spreadsheet type
        }
        else if(extension == "doc" || extension == "docx")
        {
            //Process document file type
        }
        //and so forth ...
    }
}
</code>```

We may need to process .tiff files in future or we may need to process video files, which means a new if branch

```<code>else if(extension == "avi" || extension == "mp4")
{
    //Process video file type
}
</code>```

As you can see this can get very long.

The valid files types and groups are stored in a DB...

Can anyone recommend any patterns or clever ideas to solve this problem?
Cheers

答:
I would recommend coming up with an interface for your various file processors to implement:

```<code>public interface IFileProcessor
{
    void Process(string fileName);
    IEnumerable<string> FileExtensions {get;}
}
</code>```

Then use a factory to get the appropriate processor for a particular file name. Like the other answerers, I'm recommending you use a Dictionary to keep a mapping of the processors and their file names. This example uses reflection to register every file processor that it finds in the loaded assemblies. This fits your extensibility requirement well, because all you need is for some loaded assembly to have a class that implements this interface, and it will automatically be registered with the factory. However, you can come up with whatever system you want for registering these types:

```<code>public class ProcessorFactory
{
    static IDictionary<string, IFileProcessor> ProcessorsByExtension =
        new Dictionary<string, IFileProcessor>();

    static ProcessorFactory()
    {
        var processorTypes =
            from a in AppDomain.CurrentDomain.GetAssemblies()
            from t in a.GetTypes()
            where typeof(IFileProcessor).IsAssignableFrom(t)
            select t;
        foreach(var t in processorTypes)
        {
            // Preferably use your DI framework to generate this.
            var processor = (IFileProcessor)Activator.CreateInstance(t);
            foreach(var ext in processor.FileExtensions)
            {
                if(ProcessorsByExtension.ContainsKey(ext))
                {
                    throw new InvalidOperationException(
                        "Multiple processors are registered to extension " + ext);
                }
                ProcessorsByExtension[ext] = processor;
            }
        }
    }

    public IFileProcessor GetProcessorForFile(string fileName)
    {
        string extension = Path.GetExtension(fileName);
        return ProcessorsByExtension[extension];
    }
}
</code>```

A typical implementation of the file processor interface might look like this:

```<code>public class ImageFileProcessor : IFileProcessor
{
    public IEnumerable<string> FileExtensions
    {
        get {return new[]{"jpg", "gif", "png"};}
    }
    public void Process(string fileName)
    {
        // Process Image file type
    }
}
</code>```

This approach keeps your code modular and extensible, while providing excellent performance even if you have an enormous list of file processors.

ContentLicense: CC BY-SA 2.5

Body:
How can i make the design of this class more dynamic so i can add new extensions and types as required.

public class Processor
{
    public Processor(string fileName)
    {
        string extension = Path.GetExtension(fileName);
        if(extension == "jpg" || extension == "gif" || extension == "png")
        {
            //Process Image file type
        }
        else if(extension == "xls" || extension == "xlsx")
        {
            //Process spreadsheet type
        }
        else if(extension == "doc" || extension == "docx")
        {
            //Process document file type
        }
        //and so forth ...
    }
}

We may need to process .tiff files in future or we may need to process video files, which means a new if branch

else if(extension == "avi" || extension == "mp4")
{
    //Process video file type
}

As you can see this can get very long.

The valid files types and groups are stored in a DB...

Can anyone recommend any patterns or clever ideas to solve this problem?
Cheers

Body:
I would recommend coming up with an interface for your various file processors to implement:

public interface IFileProcessor
{
    void Process(string fileName);
    IEnumerable<string> FileExtensions {get;}
}

Then use a factory to get the appropriate processor for a particular file name. Like the other answerers, I'm recommending you use a Dictionary to keep a mapping of the processors and their file names. This example uses reflection to register every file processor that it finds in the loaded assemblies. This fits your extensibility requirement well, because all you need is for some loaded assembly to have a class that implements this interface, and it will automatically be registered with the factory. However, you can come up with whatever system you want for registering these types:

public class ProcessorFactory
{
    static IDictionary<string, IFileProcessor> ProcessorsByExtension =
        new Dictionary<string, IFileProcessor>();

    static ProcessorFactory()
    {
        var processorTypes =
            from a in AppDomain.CurrentDomain.GetAssemblies()
            from t in a.GetTypes()
            where typeof(IFileProcessor).IsAssignableFrom(t)
            select t;
        foreach(var t in processorTypes)
        {
            // Preferably use your DI framework to generate this.
            var processor = (IFileProcessor)Activator.CreateInstance(t);
            foreach(var ext in processor.FileExtensions)
            {
                if(ProcessorsByExtension.ContainsKey(ext))
                {
                    throw new InvalidOperationException(
                        "Multiple processors are registered to extension " + ext);
                }
                ProcessorsByExtension[ext] = processor;
            }
        }
    }

    public IFileProcessor GetProcessorForFile(string fileName)
    {
        string extension = Path.GetExtension(fileName);
        return ProcessorsByExtension[extension];
    }
}

A typical implementation of the file processor interface might look like this:

public class ImageFileProcessor : IFileProcessor
{
    public IEnumerable<string> FileExtensions
    {
        get {return new[]{"jpg", "gif", "png"};}
    }
    public void Process(string fileName)
    {
        // Process Image file type
    }
}

This approach keeps your code modular and extensible, while providing excellent performance even if you have an enormous list of file processors.


问:
Visual studio project dependency to other project doesn't copy exe
I have a C# solution (visual studio 2017) with two projects lets say A and B, both compiled to exe. Project A depends on project B's exe, I though a dependency to project B would solve this. However, the exe doesn't get copied automatically when build.

Does the dependencies not work for exe's ? Is the only solution to make an post build step ?

答:
I think you want a post-build event.

It sounds like you already have the Project Dependency set up, which is good, because it's important that Project B gets built before Project A. And adding a Project Dependency for Project B, to Project A, is the way to do that.

Here's the documentation for adding/removing Project Dependencies: https://msdn.microsoft.com/en-us/library/et61xzb3.aspx

In Project A you can add a post build event that will copy the Project B exe.

Right Click Project A, and choose "Properties".

Change to the "Build Events" tab.

Add the command: copy "FromPath" "ToPath"

The documentation for the copy command is here: https://technet.microsoft.com/en-gb/library/bb490886.aspx?f=255&MSPPError=-2147217396

If you click "Edit Post-build", you'll get a mini-editor which has a button labelled "Macros".

If you click that "Macros" button then it'll allow you to insert replacement strings in the format $(foo).

These macros allow you to get things like the project or solution folder, so you can easily build paths that point to the right places.

Here's some documentation on the build events: https://learn.microsoft.com/en-us/visualstudio/ide/how-to-specify-build-events-csharp

Here's some (crappy) documentation on the Build Events properties page: https://learn.microsoft.com/en-us/visualstudio/ide/reference/build-events-page-project-designer-csharp

Here's some (useful) documentation on the macros: https://msdn.microsoft.com/en-us/library/c02as0cs.aspx


问:
AXIS2/C and ONVIF
I'm trying to create the stub of the wsdl http://www.onvif.org/onvif/ver10/device/wsdl/devicemgmt.wsdl using AXIS2/C (c++), using the following command:

./WSDL2CPP.sh -uri http://www.onvif.org/onvif/ver10/device/wsdl/devicemgmt.wsdl

and I get the following answer:

```<code>Exception in thread "main" org.apache.axis2.wsdl.codegen.CodeGenerationException: Error parsing WSDL
    at org.apache.axis2.wsdl.codegen.CodeGenerationEngine.<init>(CodeGenerationEngine.java:153)
    at org.apache.axis2.wsdl.WSDL2Code.main(WSDL2Code.java:35)
    at org.apache.axis2.wsdl.WSDL2CPP.main(WSDL2CPP.java:19)
Caused by: org.apache.axis2.AxisFault: **`No service was not found in the WSDL at http://www.onvif.org/onvif/ver10/device/wsdl/devicemgmt.wsdl with targetnamespace http://www.onvif.org/ver10/device/wsdl`**
    at org.apache.axis2.description.WSDL11ToAllAxisServicesBuilder.populateAllServices(WSDL11ToAllAxisServicesBuilder.java:115)
    at org.apache.axis2.wsdl.codegen.CodeGenerationEngine.<init>(CodeGenerationEngine.java:147)
    ... 2 more
</code>```

答:
I used the hack used on python-zeep, but it helps with axis2/c as well:

Add this to devicemgmt.wsdl, just before the close tag "</wsdl:definitions>":

```<code><wsdl:service name="DeviceService">
             <wsdl:port name="DevicePort" binding="tds:DeviceBinding">
               <soap:address location="http://192.168.1.100/onvif/device_service"/>
             </wsdl:port>
</wsdl:service>
</code>```

However, I'm still having problems generating the code with any of the variable bindings ("XSD complexType with mix content not supported in ADB"). I had to disable it as follows:

```<code>./WSDL2C.sh -o ../axis2c-test/gen -d none -uri devicemgmt.wsdl
</code>```

Title: AXIS2/C and ONVIF

Body:
I'm trying to create the stub of the wsdl http://www.onvif.org/onvif/ver10/device/wsdl/devicemgmt.wsdl using AXIS2/C (c++), using the following command:

./WSDL2CPP.sh -uri http://www.onvif.org/onvif/ver10/device/wsdl/devicemgmt.wsdl

and I get the following answer:

Exception in thread "main" org.apache.axis2.wsdl.codegen.CodeGenerationException: Error parsing WSDL
    at org.apache.axis2.wsdl.codegen.CodeGenerationEngine.<init>(CodeGenerationEngine.java:153)
    at org.apache.axis2.wsdl.WSDL2Code.main(WSDL2Code.java:35)
    at org.apache.axis2.wsdl.WSDL2CPP.main(WSDL2CPP.java:19)
Caused by: org.apache.axis2.AxisFault: **`No service was not found in the WSDL at http://www.onvif.org/onvif/ver10/device/wsdl/devicemgmt.wsdl with targetnamespace http://www.onvif.org/ver10/device/wsdl`**
    at org.apache.axis2.description.WSDL11ToAllAxisServicesBuilder.populateAllServices(WSDL11ToAllAxisServicesBuilder.java:115)
    at org.apache.axis2.wsdl.codegen.CodeGenerationEngine.<init>(CodeGenerationEngine.java:147)
    ... 2 more

Body:
I used the hack used on python-zeep, but it helps with axis2/c as well:

Add this to devicemgmt.wsdl, just before the close tag "</wsdl:definitions>":

<wsdl:service name="DeviceService">
             <wsdl:port name="DevicePort" binding="tds:DeviceBinding">
               <soap:address location="http://192.168.1.100/onvif/device_service"/>
             </wsdl:port>
</wsdl:service>

However, I'm still having problems generating the code with any of the variable bindings ("XSD complexType with mix content not supported in ADB"). I had to disable it as follows:

./WSDL2C.sh -o ../axis2c-test/gen -d none -uri devicemgmt.wsdl


问:
How to get json object array from deep nested json array?
This is my json, I wanted to get 'products' arrays object.

```<code>{
       "Categories":[
          {
             "id":6,
             "status":"1",
             "parent_id":"0",
             "name":"Bottom Wear",
             "name_ar":"\u0623\u0633\u0641\u0644 \u0627\u0631\u062a\u062f\u0627\u0621",
             "picture":null,
             "description":"gents bottom wear",
             "slug":"bottom-wear",
             "created_at":"2017-06-05 21:08:28",
             "updated_at":"2017-06-05 21:08:28",
             "deleted_at":null,
             "product":[
                {
                   "id":2,
                   "status":"1",
                   "name":"Pants",
                   "name_ar":"\u0628\u0646\u0637\u0644\u0648\u0646",
                   "dryclean_price":"9",
                   "washing_price":"6",
                   "press":"4",
                   "sw_dryclean_price":"9",
                   "sw_washing_price":"6",
                   "sw_press":"4",
                   "picture":null,
                   "created_at":"2017-04-19 21:32:04",
                   "updated_at":"2017-06-05 21:18:04",
                   "deleted_at":null,
                   "pivot":{
                      "category_id":"6",
                      "product_id":"2"
                   }
                },
                {
                   "id":8,
                   "status":"1",
                   "parent_id":"0",
                   "name":"Undergarments",
                   "name_ar":"\u0623\u062b\u0648\u0627\u0628 \u062a\u062d\u062a\u0627\u0646\u064a\u0629",
                   "picture":null,
                   "description":"Undergarments",
                   "slug":"undergarments",
                   "created_at":"2017-06-05 21:22:09",
                   "updated_at":"2017-06-05 21:22:09",
                   "deleted_at":null,
                   "product":[
                      {
                         "id":23,
                         "status":"1",
                         "name":"Underwear",
                         "name_ar":"\u062b\u064a\u0627\u0628 \u062f\u0627\u062e\u0644\u064a\u0629",
                         "dryclean_price":"5",
                         "washing_price":"3",
                         "press":"2",
                         "sw_dryclean_price":"5",
                         "sw_washing_price":"3",
                         "sw_press":"2",
                         "picture":null,
                         "created_at":"2017-04-19 21:35:31",
                         "updated_at":"2017-06-05 21:23:42",
                         "deleted_at":null,
                         "pivot":{
                            "category_id":"8",
                            "product_id":"23"
                         }
                      },
                      {
                         "id":34,
                         "status":"1",
                         "name":"Socks",
                         "name_ar":"\u062c\u0648\u0627\u0631\u0628",
                         "dryclean_price":"5",
                         "washing_price":"3",
                         "press":"2",
                         "sw_dryclean_price":"5",
                         "sw_washing_price":"3",
                         "sw_press":"2",
                         "picture":null,
                         "created_at":"2017-06-05 21:26:14",
                         "updated_at":"2017-06-05 21:26:14",
                         "deleted_at":null,
                         "pivot":{
                            "category_id":"8",
                            "product_id":"34"
                         }
                      }
                   ]
                }
             ]
          }
       ]
    }
</code>```

I am able to save categories in my db like this.

```<code>  protected final String CategoryTable = "category_table";
    protected final String D_ID = "category_id";
    protected final String D_SERVER_ID = "categoryserver_id";
    protected final String D_JSON = "category_json";

 public boolean insertCategory(Category model) {
        ContentValues cv = new ContentValues();
        database = this.getWritableDatabase();
        cv.put(D_SERVER_ID, model.getId());
        cv.put(D_JSON, new Gson().toJson(model));
        int res = (int) database.insert(CategoryTable, null, cv);
        database.close();
        if (res > 0) {
            return true;
        } else {
            return false;
        }
    }

  public Collection<Category> getAllCategories() {
        database = this.getReadableDatabase();
        Gson gson = new Gson();
        ArrayList<Category> lst = new ArrayList<>();
        Cursor c = database.rawQuery("SELECT * FROM " + CategoryTable, null);
        if (c.moveToFirst()) {
            do {
                Category obj = gson.fromJson(c.getString(c.getColumnIndex(D_JSON)), Category.class);
                if (obj != null)
                    lst.add(obj);
            } while (c.moveToNext());
        }
        return lst;
    }
</code>```

Here is a Category Model class:

```<code>public class Category {

    @SerializedName("id")
    @Expose
    private Integer id;
    @SerializedName("status")
    @Expose
    private String status;
    @SerializedName("parent_id")
    @Expose
    private String parentId;
    @SerializedName("name")
    @Expose
    private String name;
    @SerializedName("name_ar")
    @Expose
    private String nameAr;
    @SerializedName("description")
    @Expose
    private String description;
    @SerializedName("slug")
    @Expose
    private String slug;
    @SerializedName("created_at")
    @Expose
    private String createdAt;
    @SerializedName("updated_at")
    @Expose
    private String updatedAt;
    @SerializedName("deleted_at")
    @Expose
    private Object deletedAt;
    @SerializedName("product")
    @Expose
    private List<Product> product = null;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getParentId() {
        return parentId;
    }

    public void setParentId(String parentId) {
        this.parentId = parentId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getNameAr() {
        return nameAr;
    }

    public void setNameAr(String nameAr) {
        this.nameAr = nameAr;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getSlug() {
        return slug;
    }

    public void setSlug(String slug) {
        this.slug = slug;
    }

    public String getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(String createdAt) {
        this.createdAt = createdAt;
    }

    public String getUpdatedAt() {
        return updatedAt;
    }

    public void setUpdatedAt(String updatedAt) {
        this.updatedAt = updatedAt;
    }

    public Object getDeletedAt() {
        return deletedAt;
    }

    public void setDeletedAt(Object deletedAt) {
        this.deletedAt = deletedAt;
    }

    public List<Product> getProduct() {
        return product;
    }

    public void setProduct(List<Product> product) {
        this.product = product;
    }

}
</code>```

I am using retrofit library to get data. Here is the method I am using to save categories array in my db.

```<code>@Override
    public void onSuccess(Call call, Response response, int reqCode) {
        Loading.cancel();
        ProductsResponse productsResponse = (ProductsResponse) response.body();
        for (int i = 0; i < productsResponse.getCategories().size(); i++) {
            Category obj = productsResponse.getCategories().get(i);
            categories.add(obj);
            categoriesHandler.insertCategory(obj);
            categoriesHandler.insertLabel(obj.getName());
        }
        adapter.notifyDataSetChanged();
        loadSpinnerData();
}
</code>```

But how can I get product jsonArray from categories. Tried a lot but not able to find a method. Your help would be appreciated. Need to get products on the bases of categories. Kindly help. Thanks in advance.

Ashish I am using your method:

```<code> private void categorySelector(String str){
        Gson gson = new GsonBuilder().create();
        JSONArray mainData = (JSONArray) categoriesHandler.getAllCategories();
        ArrayList<Category> responseAsArrayList =
                gson.fromJson(mainData.toString(), new TypeToken<List<Category>>() {
                }.getType());
        for(int i =0;i<responseAsArrayList.size();i++)
        {
            for(int j = 0; j < responseAsArrayList.get(i).getProduct().size();j++)
            {
                Category category =  responseAsArrayList.get(i);
                Product product = category.getProduct().get(j);
                products.add(product);
            }

        }
</code>```

答:
```<code>JSONArray array = object.optJSONArray("Categories");  // first get your Categories array from Json Object.

 // Then iterate your categories array.
for (int i = 0; i <array.length ; i++)
    {
        JSONObject innerObject = array.getJSONObject(i);     // get inner json object from array.
        JSONArray innerArray = object.optJSONArray("product");       // then get product array from inner json object
    }
</code>```

Body:
This is my json, I wanted to get 'products' arrays object.

{
       "Categories":[
          {
             "id":6,
             "status":"1",
             "parent_id":"0",
             "name":"Bottom Wear",
             "name_ar":"\u0623\u0633\u0641\u0644 \u0627\u0631\u062a\u062f\u0627\u0621",
             "picture":null,
             "description":"gents bottom wear",
             "slug":"bottom-wear",
             "created_at":"2017-06-05 21:08:28",
             "updated_at":"2017-06-05 21:08:28",
             "deleted_at":null,
             "product":[
                {
                   "id":2,
                   "status":"1",
                   "name":"Pants",
                   "name_ar":"\u0628\u0646\u0637\u0644\u0648\u0646",
                   "dryclean_price":"9",
                   "washing_price":"6",
                   "press":"4",
                   "sw_dryclean_price":"9",
                   "sw_washing_price":"6",
                   "sw_press":"4",
                   "picture":null,
                   "created_at":"2017-04-19 21:32:04",
                   "updated_at":"2017-06-05 21:18:04",
                   "deleted_at":null,
                   "pivot":{
                      "category_id":"6",
                      "product_id":"2"
                   }
                },
                {
                   "id":8,
                   "status":"1",
                   "parent_id":"0",
                   "name":"Undergarments",
                   "name_ar":"\u0623\u062b\u0648\u0627\u0628 \u062a\u062d\u062a\u0627\u0646\u064a\u0629",
                   "picture":null,
                   "description":"Undergarments",
                   "slug":"undergarments",
                   "created_at":"2017-06-05 21:22:09",
                   "updated_at":"2017-06-05 21:22:09",
                   "deleted_at":null,
                   "product":[
                      {
                         "id":23,
                         "status":"1",
                         "name":"Underwear",
                         "name_ar":"\u062b\u064a\u0627\u0628 \u062f\u0627\u062e\u0644\u064a\u0629",
                         "dryclean_price":"5",
                         "washing_price":"3",
                         "press":"2",
                         "sw_dryclean_price":"5",
                         "sw_washing_price":"3",
                         "sw_press":"2",
                         "picture":null,
                         "created_at":"2017-04-19 21:35:31",
                         "updated_at":"2017-06-05 21:23:42",
                         "deleted_at":null,
                         "pivot":{
                            "category_id":"8",
                            "product_id":"23"
                         }
                      },
                      {
                         "id":34,
                         "status":"1",
                         "name":"Socks",
                         "name_ar":"\u062c\u0648\u0627\u0631\u0628",
                         "dryclean_price":"5",
                         "washing_price":"3",
                         "press":"2",
                         "sw_dryclean_price":"5",
                         "sw_washing_price":"3",
                         "sw_press":"2",
                         "picture":null,
                         "created_at":"2017-06-05 21:26:14",
                         "updated_at":"2017-06-05 21:26:14",
                         "deleted_at":null,
                         "pivot":{
                            "category_id":"8",
                            "product_id":"34"
                         }
                      }
                   ]
                }
             ]
          }
       ]
    }

I am able to save categories in my db like this.

  protected final String CategoryTable = "category_table";
    protected final String D_ID = "category_id";
    protected final String D_SERVER_ID = "categoryserver_id";
    protected final String D_JSON = "category_json";

 public boolean insertCategory(Category model) {
        ContentValues cv = new ContentValues();
        database = this.getWritableDatabase();
        cv.put(D_SERVER_ID, model.getId());
        cv.put(D_JSON, new Gson().toJson(model));
        int res = (int) database.insert(CategoryTable, null, cv);
        database.close();
        if (res > 0) {
            return true;
        } else {
            return false;
        }
    }

  public Collection<Category> getAllCategories() {
        database = this.getReadableDatabase();
        Gson gson = new Gson();
        ArrayList<Category> lst = new ArrayList<>();
        Cursor c = database.rawQuery("SELECT * FROM " + CategoryTable, null);
        if (c.moveToFirst()) {
            do {
                Category obj = gson.fromJson(c.getString(c.getColumnIndex(D_JSON)), Category.class);
                if (obj != null)
                    lst.add(obj);
            } while (c.moveToNext());
        }
        return lst;
    }

Here is a Category Model class:

public class Category {

    @SerializedName("id")
    @Expose
    private Integer id;
    @SerializedName("status")
    @Expose
    private String status;
    @SerializedName("parent_id")
    @Expose
    private String parentId;
    @SerializedName("name")
    @Expose
    private String name;
    @SerializedName("name_ar")
    @Expose
    private String nameAr;
    @SerializedName("description")
    @Expose
    private String description;
    @SerializedName("slug")
    @Expose
    private String slug;
    @SerializedName("created_at")
    @Expose
    private String createdAt;
    @SerializedName("updated_at")
    @Expose
    private String updatedAt;
    @SerializedName("deleted_at")
    @Expose
    private Object deletedAt;
    @SerializedName("product")
    @Expose
    private List<Product> product = null;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getParentId() {
        return parentId;
    }

    public void setParentId(String parentId) {
        this.parentId = parentId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getNameAr() {
        return nameAr;
    }

    public void setNameAr(String nameAr) {
        this.nameAr = nameAr;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getSlug() {
        return slug;
    }

    public void setSlug(String slug) {
        this.slug = slug;
    }

    public String getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(String createdAt) {
        this.createdAt = createdAt;
    }

    public String getUpdatedAt() {
        return updatedAt;
    }

    public void setUpdatedAt(String updatedAt) {
        this.updatedAt = updatedAt;
    }

    public Object getDeletedAt() {
        return deletedAt;
    }

    public void setDeletedAt(Object deletedAt) {
        this.deletedAt = deletedAt;
    }

    public List<Product> getProduct() {
        return product;
    }

    public void setProduct(List<Product> product) {
        this.product = product;
    }

}

I am using retrofit library to get data. Here is the method I am using to save categories array in my db.

@Override
    public void onSuccess(Call call, Response response, int reqCode) {
        Loading.cancel();
        ProductsResponse productsResponse = (ProductsResponse) response.body();
        for (int i = 0; i < productsResponse.getCategories().size(); i++) {
            Category obj = productsResponse.getCategories().get(i);
            categories.add(obj);
            categoriesHandler.insertCategory(obj);
            categoriesHandler.insertLabel(obj.getName());
        }
        adapter.notifyDataSetChanged();
        loadSpinnerData();
}

But how can I get product jsonArray from categories. Tried a lot but not able to find a method. Your help would be appreciated. Need to get products on the bases of categories. Kindly help. Thanks in advance.

Ashish I am using your method:

 private void categorySelector(String str){
        Gson gson = new GsonBuilder().create();
        JSONArray mainData = (JSONArray) categoriesHandler.getAllCategories();
        ArrayList<Category> responseAsArrayList =
                gson.fromJson(mainData.toString(), new TypeToken<List<Category>>() {
                }.getType());
        for(int i =0;i<responseAsArrayList.size();i++)
        {
            for(int j = 0; j < responseAsArrayList.get(i).getProduct().size();j++)
            {
                Category category =  responseAsArrayList.get(i);
                Product product = category.getProduct().get(j);
                products.add(product);
            }

        }


问:
Email Alert when Crashes cross a particular Threshold
Is it possible to setup an email alert when the number of crashes in my app crosses a particular threshold per day?

I would like to receive an email, for example, when my app crashes more than 7 times in the last 24 hs.

I'm tracking the crashes with Crashlytics (from Fabric). I didn't find anything related within Settings -> Notifications nor in any google research.

I sent an email to support@fabric.io, still waiting to their response.

Many thanks

答:
Mike from Fabric here.

I resent my reply from our support channel as well.

There is not a custom notification that can be sent, but let me clarify what is currently available.

New Issue: A new issue email would be sent when an issue first appears in Fabric for the very first time.

Regressed Issue: If an issue has been closed and happens in a version outside the subset of versions where the issue had occurred previously, then you'll be notified.

Crash Stability Digest: A digest email contianing a summary of your issues including any issues that are new or trending higher and thus may be worth investigating as a priority.

Issue Velocity Alert: If an issue is causing a crash in 1% of all user sessions within the past hour, you'll be notifiied.

Stability Alert: If your app's stability drops below a statistically significant amount based on historical data, then you'll be notified.

Perhaps some combination of these could help?


问:
Azure Web Role Recycle Itself after running for weeks?
I am new to Microsoft Azure and working on a MVP for a client. I am able to successfully deploy my ASP.NET MVC web app to a Web Role. The issue I'm facing is that Azure Web Role seems to recycle itself and revert to the deployment package. This leads to rollback of manual changes done (if any) after the deployment (like I allow user to upload profile images and am storing them in file system).

Is this the expected behavior? If not, when can I look from debugging purposes?

Looking for any help possible.

答:
Is this the expected behavior? If not, when can I look from debugging
  purposes?

It is expected behavior. Azure Fabric Controller is responsible for managing the Virtual Machines in which your WebRole runs. It takes care of patching the VM and do other maintenance related work on that VM. It is also responsible for taking out faulty VMs and replace them with brand new VMs. When the replacement happens, Fabric Controller will create the new VM based on the last deployment package.

You should not be making any changes manually after VM hosting WebRole has been created, these are Stateless VMs. Any changes you make to VM will be rolled back if Fabric Controller decides to recycle the VM. Please note that these changes do persist if the VM is simply rebooted.


问:
Unsigned long in Java
Currently, I am using signed values, -2^63 to 2^63-1. Now I need the same range (2 * 2^64), but with positive values only. I found the java documentations mentioning unsigned long, which suits this use.

I tried to declare 2^64 to a Long wrapper object, but it still loses the data, in other words, it only captures till the Long.MAX_VALUE, so I am clearly missing something.
Is BigInteger the signed long that Java supports?

Is there a definition or pointer as to how to declare and use it?

答:
In Java 8, unsigned long support was introduced. Still, these are typical longs, but the sign doesn't affect adding and subtracting. For dividing and comparing, you have dedicated methods in Long. Also, you can do the following:

```<code>long l1 = Long.parseUnsignedLong("12345678901234567890");
String l1Str = Long.toUnsignedString(l1)
</code>```

BigInteger is a bit different. It can keep huge numbers. It stores them as int[] and supports arithmetic.

Title: Unsigned long in Java

Body:
In Java 8, unsigned long support was introduced. Still, these are typical longs, but the sign doesn't affect adding and subtracting. For dividing and comparing, you have dedicated methods in Long. Also, you can do the following:

long l1 = Long.parseUnsignedLong("12345678901234567890");
String l1Str = Long.toUnsignedString(l1)

BigInteger is a bit different. It can keep huge numbers. It stores them as int[] and supports arithmetic.

ContentLicense: CC BY-SA 4.0


问:
How can I align some text vertically in the middle of an HTML image?
I have this:
http://jsfiddle.net/8KWtH/

I would like to move the > so it is in the middle vertically of the two images.

How can i do this?

答:
Use line-height to accomplish this:

```<code><span style="font-size: 34px;line-height: 79px;"> > </span>
</code>```

EDIT:

Because of the nature of the images, you need to use vertical-align to accomplish this:

```<code><div style="float: left;">
<img src="http://www.lokeshdhakar.com/projects/lightbox2/images/image-2.jpg" style="width: 60px; height: 79px;vertical-align: middle;">
<span style="font-size: 34px;"> > </span>
<img src="http://www.lokeshdhakar.com/projects/lightbox2/images/image-2.jpg" style="width: 60px; height: 79px;vertical-align: middle;">
</div>
</code>```

Body:
Use line-height to accomplish this:

<span style="font-size: 34px;line-height: 79px;"> &gt; </span>

EDIT:

Because of the nature of the images, you need to use vertical-align to accomplish this:

<div style="float: left;">
<img src="http://www.lokeshdhakar.com/projects/lightbox2/images/image-2.jpg" style="width: 60px; height: 79px;vertical-align: middle;">
<span style="font-size: 34px;"> &gt; </span>
<img src="http://www.lokeshdhakar.com/projects/lightbox2/images/image-2.jpg" style="width: 60px; height: 79px;vertical-align: middle;">
</div>


问:
AzCopy - Wildcards In Middle Of Pattern?
Scenario:
-Backups located in Azure storage
-Folder containing >100,000 folders
-Inside of each folder is a file in the following format: MM-DD-YYYY_randomnumber.wav.gz

We need to pull all files from two months (unknown number, likely 30,000-40,000).

Looks like AzCopy is the utility we need to accomplish this.

The following command is how I'd imagine it would work, but am unable to get it to do so:

```<code>AzCopy /Source:https://path.to.files/path/to/files /Dest:C:\test /SourceKey:key /Pattern:11-*-2016_*.wav.gz /S
</code>```

The following grabs the parent folder (it's named the same as the files within them, just without the .wav.gz extension), which wouldn't be ideal, but would be workable. However, this would grab files from multiple years:

```<code>AzCopy /Source:https://path.to.files/path/to/files /Dest:C:\test /SourceKey:key /Pattern:11 /S
</code>```

I've read the documentation, and it mentions wildcards can be used in some circumstances but not others, but I'm not entirely sure what it's meaning.

Thanks!

答:
You don't have to use Azcopy, a few lines of powershell using the AzureRM module should be able to download the files.
Altough I have not tested it with a large numer of files.

And with powershell, you can easily edit the "blobnames" variable and pick the correct folders and files you want using wildcards.
The folders in the Azure storage account you chose will also be created on your local drive.

```<code>$blobnames = "somebackups/2016.*/11-*-2016_*.wav.gz"
</code>```

The code below is pretty self explaining.

```<code>$storageAccountName = "storage"
$storageAccountKey = "SuperLongKey"
$containerName = "backup"
$localDirectory = "c:/temp/stackoverflow"
$blobnames = "11-*-2016_*.wav.gz"

$ctx = New-AzureStorageContext -StorageAccountName $storageAccountName -StorageAccountKey $storageAccountKey

$blobsToDownload = Get-AzureStorageBlob -Context $ctx -blob $blobnames -Container $containerName

$blobsToDownload | Get-AzureStorageBlobContent -Destination $localDirectory
</code>```

Body:
Scenario:
-Backups located in Azure storage
-Folder containing >100,000 folders
-Inside of each folder is a file in the following format: MM-DD-YYYY_randomnumber.wav.gz

We need to pull all files from two months (unknown number, likely 30,000-40,000).

Looks like AzCopy is the utility we need to accomplish this.

The following command is how I'd imagine it would work, but am unable to get it to do so:

AzCopy /Source:https://path.to.files/path/to/files /Dest:C:\test /SourceKey:key /Pattern:11-*-2016_*.wav.gz /S

The following grabs the parent folder (it's named the same as the files within them, just without the .wav.gz extension), which wouldn't be ideal, but would be workable. However, this would grab files from multiple years:

AzCopy /Source:https://path.to.files/path/to/files /Dest:C:\test /SourceKey:key /Pattern:11 /S

I've read the documentation, and it mentions wildcards can be used in some circumstances but not others, but I'm not entirely sure what it's meaning.

Thanks!

Body:
You don't have to use Azcopy, a few lines of powershell using the AzureRM module should be able to download the files.
Altough I have not tested it with a large numer of files.

And with powershell, you can easily edit the "blobnames" variable and pick the correct folders and files you want using wildcards.
The folders in the Azure storage account you chose will also be created on your local drive.

$blobnames = "somebackups/2016.*/11-*-2016_*.wav.gz"

The code below is pretty self explaining.

$storageAccountName = "storage"
$storageAccountKey = "SuperLongKey"
$containerName = "backup"
$localDirectory = "c:/temp/stackoverflow"
$blobnames = "11-*-2016_*.wav.gz"

$ctx = New-AzureStorageContext -StorageAccountName $storageAccountName -StorageAccountKey $storageAccountKey

$blobsToDownload = Get-AzureStorageBlob -Context $ctx -blob $blobnames -Container $containerName

$blobsToDownload | Get-AzureStorageBlobContent -Destination $localDirectory


问:
nltk problems with Stanford NLP
New to Python 3.6 with Mac...Was trying to use NLTK with Stanford NLP.

(1) was totally not able to understand environment variables and can't set correctly when using Stanford NLP. I tried the following but run out of idea when arriving at STEP3,

Add the appropriate Stanford NLP .jar file to the  CLASSPATH environment variable.

Stanford Parser and NLTK

Wondering whether some guys can explain patiently how the CLASSPATH works and how to set them with/before NLTK (export codes are disabled in NLTK)

Although setting environment variables is a much elegant way, I have to choose the alternative. I downloaded all jar files and put them on my desktop. (No idea where they should be placed. Most related instructions deals with Windows, which does not work for Mac).

Therefore, tried to specify the locations of Stanford NLP tools, such as follows

screenshot of the codes and how they failed in the interpreter

Hope to solve it! Thanks much!!!!

答:
To set an environment variable globally, run

```<code>export CLASSPATH="path/to/file.jar"
</code>```

from the terminal (iTerm or iTerm2 on mac) or

```<code>export CLASSPATH=`pwd`/file.jar
</code>```

if you're in the folder where file.jar is located.

To set an environment variable in a python script:

```<code>import os
os.environ['CLASSPATH'] = 'path/to/file.jar'
</code>```

Note that in a python script, the values will not be availabile after that script has run.

Title: nltk problems with Stanford NLP

Body:
To set an environment variable globally, run

export CLASSPATH="path/to/file.jar"

from the terminal (iTerm or iTerm2 on mac) or

export CLASSPATH=`pwd`/file.jar

if you're in the folder where file.jar is located.

To set an environment variable in a python script:

import os
os.environ['CLASSPATH'] = 'path/to/file.jar'

Note that in a python script, the values will not be availabile after that script has run.


问:
Fixed background image with ios7
I have a project that I am using the fixed background image. It works great on everything except ios7. On the ipad the background image is zoomed in and blurry. Here is the CSS code I am using -

```<code>.header {
  display: table;
  height: 100%;
  width: 100%;
  position: relative;
  color: #fff;
  background: url(../images/boston2.jpg) no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
  }
</code>```

here is a link to the live page - www.wdeanmedical.com

What am I missing?

答:
I had a very simple solution for this, after struggling with all the methods of fixing this.

i had the problem on my mobile IOS devices.

css (desktop)

```<code>#ci-hero-11 .widget-wrap , #ci-hero-12 .widget-wrap {
background-size: auto;
background-attachment: fixed;
}

.widget-wrap {
background-attachment: scroll;
}
</code>```

Then i overwrite it with media query removing "fixed" as background attachment.

css (mobile)

```<code>/*-------- iPads (portrait and landscape) --------*/
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px) {
#ci-hero-11 .widget-wrap , #ci-hero-12 .widget-wrap {

    background-attachment: initial;

}
}
</code>```

initial -   Sets this property to its default value. I think because IOS doesn't accept 'fixed' it falls back to a default value it accepts, scroll.

This worked for me on every device. Hope it helps someone else as well.

Title: Fixed background image with ios7

Body:
I have a project that I am using the fixed background image. It works great on everything except ios7. On the ipad the background image is zoomed in and blurry. Here is the CSS code I am using -

.header {
  display: table;
  height: 100%;
  width: 100%;
  position: relative;
  color: #fff;
  background: url(../images/boston2.jpg) no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
  }

here is a link to the live page - www.wdeanmedical.com

What am I missing?

Body:
I had a very simple solution for this, after struggling with all the methods of fixing this.

i had the problem on my mobile IOS devices.

css (desktop)

#ci-hero-11 .widget-wrap , #ci-hero-12 .widget-wrap {
background-size: auto;
background-attachment: fixed;
}

.widget-wrap {
background-attachment: scroll;
}

Then i overwrite it with media query removing "fixed" as background attachment.

css (mobile)

/*-------- iPads (portrait and landscape) --------*/
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px) {
#ci-hero-11 .widget-wrap , #ci-hero-12 .widget-wrap {

    background-attachment: initial;

}
}

initial -   Sets this property to its default value. I think because IOS doesn't accept 'fixed' it falls back to a default value it accepts, scroll.

This worked for me on every device. Hope it helps someone else as well.


问:
C# - Menustrip- Check if Parent exists and get the reference to them
First of all Thanks for your Time! I hope you can help me =/

I have a MenuStrip where i want to add items dynamically.

What i want to do :
If a Partent with exactly the same name already exists the Childs should be add to this parent instead creating a new Parent(MenuStripItem) with the same name.

My Code does currently checks if the parent already exists (which works fine) but the problem is i cant get the reference to this parent -> firstItem=var doesnt work -> cant convert ToolStripItem to ToolStripMenuItem... and changing the "firstItem" to ToolStripItem gives me an Error because i cant use  "firstItem.DropDownItems.Add(withChild);" anymore to add a Child later on...

```<code>        private void AddNewMenuStrips(string [,] NewMenuStripInfo)
    {
        ToolStripMenuItem firstItem;
         bool alreadyexists = false;
         string someItem = "Settings"; // the parent im looking for
        var items = menuStrip2.Items.Find(someItem+"ToolStripMenuItem",false); //here it checks if parent already exists. Which Works but i cant get the reference of the parent to  "firstItem"

        foreach (var item in items)
        {
            MessageBox.Show("FOUND"+item.Name);
            firstItem = var; // ERROR cant convert ToolStripItem to ToolStripMenuItem
            alreadyexists=true;
        }

        if (alreadyexists == false) { firstItem = new ToolStripMenuItem(someItem); }
   }
</code>```

THANKS in advance!

答:
ToolStripMenuItem is a class which represents top level menu items and derives (not directly) from ToolStripItem.

Therefore to retrieve the parent menu item you can use a cast:

```<code>foreach (var item in parents)
{
    MessageBox.Show("FOUND" + item.Name);
    firstItem = item as ToolStripMenuItem;
    alreadyexists = true;
    // break;
}
</code>```

Body:
First of all Thanks for your Time! I hope you can help me =/

I have a MenuStrip where i want to add items dynamically.

What i want to do :
If a Partent with exactly the same name already exists the Childs should be add to this parent instead creating a new Parent(MenuStripItem) with the same name.

My Code does currently checks if the parent already exists (which works fine) but the problem is i cant get the reference to this parent -> firstItem=var doesnt work -> cant convert ToolStripItem to ToolStripMenuItem... and changing the "firstItem" to ToolStripItem gives me an Error because i cant use  "firstItem.DropDownItems.Add(withChild);" anymore to add a Child later on...

        private void AddNewMenuStrips(string [,] NewMenuStripInfo)
    {
        ToolStripMenuItem firstItem;
         bool alreadyexists = false;
         string someItem = "Settings"; // the parent im looking for
        var items = menuStrip2.Items.Find(someItem+"ToolStripMenuItem",false); //here it checks if parent already exists. Which Works but i cant get the reference of the parent to  "firstItem"

        foreach (var item in items)
        {
            MessageBox.Show("FOUND"+item.Name);
            firstItem = var; // ERROR cant convert ToolStripItem to ToolStripMenuItem
            alreadyexists=true;
        }

        if (alreadyexists == false) { firstItem = new ToolStripMenuItem(someItem); }
   }

THANKS in advance!

Body:
ToolStripMenuItem is a class which represents top level menu items and derives (not directly) from ToolStripItem.

Therefore to retrieve the parent menu item you can use a cast:

foreach (var item in parents)
{
    MessageBox.Show("FOUND" + item.Name);
    firstItem = item as ToolStripMenuItem;
    alreadyexists = true;
    // break;
}


问:
AEM/CQ - javax.xml.namespace can't resolve OSGI dependency
I'm using AEM 6.2 and I'm currently implementing WebService.
I included all dependency jars in OSGI bundle which I created externally and all dependency issue got resolved except one:

javax.xml.namespace,version=[1.0,2) -- Cannot be resolved

When I checked in the maven using depfinder tool, it showed me as below:

```<code><dependency>
    <groupId>org.apache.sling</groupId>
    <artifactId>org.apache.sling.fragment.ws</artifactId>
    <version>1.0.2</version>
    <scope>provided</scope>
</dependency>
</code>```

However, in my other custom project, the javax.xml.namespace is showing resolved state.

I'm stuck in this situation and any pointers will be really appreciated.

Thanks,
Jineet

答:
If you look closely at the output of the "Package Dependency" tool you will see that the Maven dependency has the version 1.0.2. The exported version of this package on the other hand is 0.0.0.fragment_xml.

I do not know why that is but this means you need to use a little workaround to resolve your bundles against this version.

What you basically have to do is to update your MANIFEST.MF and change the imported version from 1.0.2 to 0.0.0.fragment_xml.

We are using Maven and the maven-bundle-plugin plugin to achieve this:

```<code><plugin>
    <groupId>org.apache.felix</groupId>
    <artifactId>maven-bundle-plugin</artifactId>
    <extensions>true</extensions>
    <configuration>
        <instructions>
            <Import-Package>
                javax.xml.namespace;version="0.0.0.fragment_xml",
                *
            </Import-Package>
        </instructions>
    </configuration>
</plugin>
</code>```

I hope this helps.

Body:
I'm using AEM 6.2 and I'm currently implementing WebService.
I included all dependency jars in OSGI bundle which I created externally and all dependency issue got resolved except one:

javax.xml.namespace,version=[1.0,2) -- Cannot be resolved

When I checked in the maven using depfinder tool, it showed me as below:

<dependency>
    <groupId>org.apache.sling</groupId>
    <artifactId>org.apache.sling.fragment.ws</artifactId>
    <version>1.0.2</version>
    <scope>provided</scope>
</dependency>

However, in my other custom project, the javax.xml.namespace is showing resolved state.

I'm stuck in this situation and any pointers will be really appreciated.

Thanks,
Jineet

Body:
If you look closely at the output of the "Package Dependency" tool you will see that the Maven dependency has the version 1.0.2. The exported version of this package on the other hand is 0.0.0.fragment_xml.

I do not know why that is but this means you need to use a little workaround to resolve your bundles against this version.

What you basically have to do is to update your MANIFEST.MF and change the imported version from 1.0.2 to 0.0.0.fragment_xml.

We are using Maven and the maven-bundle-plugin plugin to achieve this:

<plugin>
    <groupId>org.apache.felix</groupId>
    <artifactId>maven-bundle-plugin</artifactId>
    <extensions>true</extensions>
    <configuration>
        <instructions>
            <Import-Package>
                javax.xml.namespace;version="0.0.0.fragment_xml",
                *
            </Import-Package>
        </instructions>
    </configuration>
</plugin>

I hope this helps.


问:
Need to Format this JSON properly and display in HTML using AJAX
I have a JSON that looks like this, I get it from a PHP file that calls Yahoo Finance API,

It's the first time I see a JSON like this.

I looked everywhere but all I manage to do is console log it... I'd like to display it into a table, or a ul, with AJAX
I'd like to access everything and display just what I need or everything.

I tried a bunch of different code snippets from everywhere but couldn't make it work, in three days !...

I'm using scheb/yahoo-finance-api on packagist for that, if it helps.

Thanks for your help.

{
    query: {
        count: 1,
        created: "2017-06-07T12:34:44Z",
        lang: "en-US",
        results: {
            quote: {
                symbol: "APLL",
                Symbol: "APLL",
                LastTradePriceOnly: "0.119",
                LastTradeDate: "6/6/2017",
                LastTradeTime: "11:13am",
                Change: "+0.023",
                Open: "0.119",
                DaysHigh: "0.119",
                DaysLow: "0.110",
                Volume: "300"
            }
        }
    }
}

$(function(){
$("#get-data").click(function() {
    //do ajax here and load data
    var showData = $('#show-data');
    var $data = $.getJSON("data.php", function(data) {

        // $data = $data.responseText;
        function buildTree(data, container) {
            $data.forEach(function(node) {

                var el = document.createElement(node.tag);

                if (Array.isArray(node.content)) {
                    buildTree(node.content, el);
                }
                else if (typeof(node.content) == 'object') {
                    buildTree([node.content], el);
                }
                else {
                    el.innerHTML = node.content;
                }

                container.appendChild(el);
            });

        }

        console.log($data);
        buildTree($data, document.body);
    });
});
```

});

That's the one I have for now, I deleted all the others, I took it form here and modified it with no success tho..
Thank you for answering :)

答:
This is in literal notation so I assume you've already parsed it into an object. Let's call that object myObject

```<code>var myObject={
query : {
    count : 1 ,
    created : "2017-06-07T12:34:44Z" ,
    lang : "en-US" ,
    results : {
        quote : {
            symbol : "APLL" , Symbol : "APLL" , LastTradePriceOnly : "0.119" , LastTradeDate : "6/6/2017" , LastTradeTime : "11:13am" , Change : "+0.023" , Open : "0.119" , DaysHigh : "0.119" , DaysLow : "0.110" , Volume : "300" } } } }
</code>```

You can access properties as follows:

```<code>var myCount = myObject.query.count
console.log(myCount)   // logs 1
</code>```

Body:
I have a JSON that looks like this, I get it from a PHP file that calls Yahoo Finance API,

It's the first time I see a JSON like this.

I looked everywhere but all I manage to do is console log it... I'd like to display it into a table, or a ul, with AJAX
I'd like to access everything and display just what I need or everything.

I tried a bunch of different code snippets from everywhere but couldn't make it work, in three days !...

I'm using scheb/yahoo-finance-api on packagist for that, if it helps.

Thanks for your help.

{
    query: {
        count: 1,
        created: "2017-06-07T12:34:44Z",
        lang: "en-US",
        results: {
            quote: {
                symbol: "APLL",
                Symbol: "APLL",
                LastTradePriceOnly: "0.119",
                LastTradeDate: "6/6/2017",
                LastTradeTime: "11:13am",
                Change: "+0.023",
                Open: "0.119",
                DaysHigh: "0.119",
                DaysLow: "0.110",
                Volume: "300"
            }
        }
    }
}

$(function(){
$("#get-data").click(function() {
    //do ajax here and load data
    var showData = $('#show-data');
    var $data = $.getJSON("data.php", function(data) {

        // $data = $data.responseText;
        function buildTree(data, container) {
            $data.forEach(function(node) {

                var el = document.createElement(node.tag);

                if (Array.isArray(node.content)) {
                    buildTree(node.content, el);
                }
                else if (typeof(node.content) == 'object') {
                    buildTree([node.content], el);
                }
                else {
                    el.innerHTML = node.content;
                }

                container.appendChild(el);
            });

        }

        console.log($data);
        buildTree($data, document.body);
    });
});

});

That's the one I have for now, I deleted all the others, I took it form here and modified it with no success tho..
Thank you for answering :)

Body:
This is in literal notation so I assume you've already parsed it into an object. Let's call that object myObject

var myObject={
query : {
    count : 1 ,
    created : "2017-06-07T12:34:44Z" ,
    lang : "en-US" ,
    results : {
        quote : {
            symbol : "APLL" , Symbol : "APLL" , LastTradePriceOnly : "0.119" , LastTradeDate : "6/6/2017" , LastTradeTime : "11:13am" , Change : "+0.023" , Open : "0.119" , DaysHigh : "0.119" , DaysLow : "0.110" , Volume : "300" } } } }

You can access properties as follows:

var myCount = myObject.query.count
console.log(myCount)   // logs 1


问:
caching common lookup data - strategies
Looking at implementing caching for some common lookup data in an asp.net web application.

In the past, I've created a singleton that creates a bunch of hashtables, which have public accessors.  This works pretty well for read-only data that never changes.

I've done a bit of looking into the System.Web.Caching, but it doesn't seem to offer any benefits over the singleton approach.  We're not using SQLServer, so we wouldn't be able to take advantage of the SQLCacheDependency for the rare cases where the data might change.

Anyone have experience with either of these alternatives?  Or have a better suggestion?

答:
I can't speak to the benefits of System.Web.Caching since, like you, I've typically implemented singleton instances of a lookup table data structure.  The singleton class also exposes an InvalidateCache() method to handle the rare cases where data might change.

If you're building a business object library for use in both asp.net and, for example, winforms then you might decide to avoid using System.Web.Caching.

The Business Object framework which I use provides a base class for lookup tables called NameValueListBase<TKey, TValue>.  This generic base class provides strongly typed helper methods.  You could develop a similar base class and expose your own helper methods as opposed to just exposing an instance of System.Collections.Generic.Dictionary.

The Business Object framework to which I refer is called CSLA.Net and is explained in great detail in Expert C# 2008 Business Objects.  There is also a version of the book available for VB.Net.

OwnerDisplayName: chris

Title: caching common lookup data - strategies


问:
Strange Feature? of Ruby Arrays
I came around this strange feature(?) of arrays in Ruby and it would be very helpful if someone could explain to me why they work the way they do.

First lets give an example of how things usually work.

```<code>a = "Hello" #=> "Hello"
b = a #=> "Hello"
b += " Goodbye" #=> "Hello Goodbye"
b #=> "Hello Goodbye"
a #=> "Hello"
</code>```

Ok cool, when you use = it creats a copy of the object (this time a string).

But when you use arrays this happens:

```<code>a = [1,2,3] #=> [1,2,3]
b = a #=> [1,2,3]
b[1] = 5 #=> [1,5,3]
b #=> [1,5,3]
a #=> [1,5,3]
</code>```

Now thats just strange.  Its the only object I've found that doesn't get copied when using = but instead just creates a refrance to the original object.

Can someone also explain (there must be a method) for copying an array without having it point back to the original object?

答:
Try your Array case with a String:

```<code>a = "Hello" #=> "Hello"
b = a #=> "Hello"
b[1] = "x" #=> "x"
b #=> "Hxllo"
a #=> "Hxllo"
</code>```

Strings and Arrays work the same way in this regard.

The key difference in the two cases, as you wrote them, is this:

```<code>b += " Goodbye"
</code>```

This is syntactic shorthand for

```<code>b = b + " Goodbye"
</code>```

which is creating a new string from b + " Goodbye" and then assigning that to b. The way to modify an existing string, rather than creating a new one, is

```<code>b << " Goodbye"
</code>```

And if you plug that into your sequence, you'll see that it modifies both a and b, since both variables refer to the same string object.

As for deep copying, there's a decent piece about it here:

http://ruby.about.com/od/advancedruby/a/deepcopy.htm

Title: Strange Feature? of Ruby Arrays

Body:
I came around this strange feature(?) of arrays in Ruby and it would be very helpful if someone could explain to me why they work the way they do.

First lets give an example of how things usually work.

a = "Hello" #=> "Hello"
b = a #=> "Hello"
b += " Goodbye" #=> "Hello Goodbye"
b #=> "Hello Goodbye"
a #=> "Hello"

Ok cool, when you use = it creats a copy of the object (this time a string).

But when you use arrays this happens:

a = [1,2,3] #=> [1,2,3]
b = a #=> [1,2,3]
b[1] = 5 #=> [1,5,3]
b #=> [1,5,3]
a #=> [1,5,3]

Now thats just strange.  Its the only object I've found that doesn't get copied when using = but instead just creates a refrance to the original object.

Can someone also explain (there must be a method) for copying an array without having it point back to the original object?

Body:
Try your Array case with a String:

a = "Hello" #=> "Hello"
b = a #=> "Hello"
b[1] = "x" #=> "x"
b #=> "Hxllo"
a #=> "Hxllo"

Strings and Arrays work the same way in this regard.

The key difference in the two cases, as you wrote them, is this:

b += " Goodbye"

This is syntactic shorthand for

b = b + " Goodbye"

which is creating a new string from b + " Goodbye" and then assigning that to b. The way to modify an existing string, rather than creating a new one, is

b << " Goodbye"

And if you plug that into your sequence, you'll see that it modifies both a and b, since both variables refer to the same string object.

As for deep copying, there's a decent piece about it here:

http://ruby.about.com/od/advancedruby/a/deepcopy.htm