问:
Validation Attribute localization
I'm working on a ASP .Net Core 5 project, where I created a custom Validation Attribute and in case when the validation result is not valid I want to return a localized error message.

Here is the ViewModel with the validation attribute:

```<code>  public class MyViewModel()
  {
    [Required(ErrorMessage = "RequiredMsg")]
    [CheckTextIsValid(new char[] { 'a', 'b', 'c' }, ErrorMessage = "NotAllowedChars")]
    public string Name { get; set; }

    [Required(ErrorMessage = "RequiredMsg")]
    [CheckTextIsValid(new char[] { 'a', 'b', 'c' }, ErrorMessage = "NotAllowedChars")]
    public string SureName { get; set; }

    [Required(ErrorMessage = "RequiredMsg")]
    [CheckTextIsValid(new char[] { 'a', 'b', 'c' }, ErrorMessage = "NotAllowedChars")]
    public string Address { get; set; }

    [Required(ErrorMessage = "RequiredMsg")]
    public string Phone { get; set; }

    [Required(ErrorMessage = "RequiredMsg")]
    [CheckTextIsValid(new char[] { 'a', 'b', 'c' }, ErrorMessage = "NotAllowedChars")]
    public string Country { get; set; }
  }
</code>```

The "RequiredMsg" is localized and it works, so when there's error I can see the value of "RequiredMsg" = "This feild is required". But it's not working for "NotAllowedChars".

Here is CheckTextIsValid validation code:

```<code>public class CheckTextIsValid :ValidationAttribute
    {
        private char[] NotAllowedChars { get; set; }

        public CheckTextIsValidForSdi(char[] notAllowedChars)
        {
            NotAllowedChars = notAllowedChars;
        }
        public override bool IsValid(object value)
        {
            ..... Logic..
            if(//IsValid)
            {
                return ValidationResult.Success;
            }else{
               return new ValidationResult( string.Format(ErrorMessage, notAllowedChars)); // Here the ErrorMessage is "NotAllowedChars"
            }

        }
    }
</code>```

How can I read the value of "NotAllowedChars" from the resources?

I know that there's a lot of questions about this:
(

ASP.NET Core custom validation attribute localization,

ErrorMessageTranslationService, This is work perfectly with IHtmlLocalizer. ButI need to IHtmlLocalizer<T> because I'm gonna use CheckTextIsValid() in different View Models and pass different error messages.

), but still I couldn't fix this problem.

答:
I write a simply demo to show custom validation

Model

```<code>public class MyViewModel
    {
        [Required(ErrorMessage = "RequiredMsg")]
        [CheckTextIsValid(new char[] { 'a', 'b', 'c' }, ErrorMessage = "Name can't contain a,b,c")]
        public string? Name { get; set; }

        [Required(ErrorMessage = "RequiredMsg")]
        [CheckTextIsValid(new char[] { 'a', 'b', 'c' }, ErrorMessage = "Password can't contain a,b,c")]
        public string? Password { get; set; }
    }
</code>```

validation

```<code>public class CheckTextIsValid : ValidationAttribute
    {
        private char[] NotAllowedChars { get; set; }

        public CheckTextIsValid(char[] notAllowedChars)
        {
            NotAllowedChars = notAllowedChars;

        }
        protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
        {
            var v = (string)value;
            var result = v.IndexOfAny(NotAllowedChars);
            if (result == -1)
            {
                return ValidationResult.Success;
            }

            return new ValidationResult(ErrorMessage);

        }
    }
</code>```

Then you can see When I input NewYork and a, The ErrorMessage will display behind a.

Notice: This demo just custom server-side validation, if you want custom client-side validation you can refer to this link.

Title: Validation Attribute localization

Body:
I'm working on a ASP .Net Core 5 project, where I created a custom Validation Attribute and in case when the validation result is not valid I want to return a localized error message.

Here is the ViewModel with the validation attribute:

  public class MyViewModel()
  {
    [Required(ErrorMessage = "RequiredMsg")]
    [CheckTextIsValid(new char[] { 'a', 'b', 'c' }, ErrorMessage = "NotAllowedChars")]
    public string Name { get; set; }

    [Required(ErrorMessage = "RequiredMsg")]
    [CheckTextIsValid(new char[] { 'a', 'b', 'c' }, ErrorMessage = "NotAllowedChars")]
    public string SureName { get; set; }

    [Required(ErrorMessage = "RequiredMsg")]
    [CheckTextIsValid(new char[] { 'a', 'b', 'c' }, ErrorMessage = "NotAllowedChars")]
    public string Address { get; set; }

    [Required(ErrorMessage = "RequiredMsg")]
    public string Phone { get; set; }

    [Required(ErrorMessage = "RequiredMsg")]
    [CheckTextIsValid(new char[] { 'a', 'b', 'c' }, ErrorMessage = "NotAllowedChars")]
    public string Country { get; set; }
  }

The "RequiredMsg" is localized and it works, so when there's error I can see the value of "RequiredMsg" = "This feild is required". But it's not working for "NotAllowedChars".

Here is CheckTextIsValid validation code:

public class CheckTextIsValid :ValidationAttribute
    {
        private char[] NotAllowedChars { get; set; }

        public CheckTextIsValidForSdi(char[] notAllowedChars)
        {
            NotAllowedChars = notAllowedChars;
        }
        public override bool IsValid(object value)
        {
            ..... Logic..
            if(//IsValid)
            {
                return ValidationResult.Success;
            }else{
               return new ValidationResult( string.Format(ErrorMessage, notAllowedChars)); // Here the ErrorMessage is "NotAllowedChars"
            }

        }
    }

How can I read the value of "NotAllowedChars" from the resources?

I know that there's a lot of questions about this:
(

ASP.NET Core custom validation attribute localization,

ErrorMessageTranslationService, This is work perfectly with IHtmlLocalizer. ButI need to IHtmlLocalizer<T> because I'm gonna use CheckTextIsValid() in different View Models and pass different error messages.

), but still I couldn't fix this problem.

Body:
I write a simply demo to show custom validation

Model

public class MyViewModel
    {
        [Required(ErrorMessage = "RequiredMsg")]
        [CheckTextIsValid(new char[] { 'a', 'b', 'c' }, ErrorMessage = "Name can't contain a,b,c")]
        public string? Name { get; set; }

        [Required(ErrorMessage = "RequiredMsg")]
        [CheckTextIsValid(new char[] { 'a', 'b', 'c' }, ErrorMessage = "Password can't contain a,b,c")]
        public string? Password { get; set; }
    }

validation

public class CheckTextIsValid : ValidationAttribute
    {
        private char[] NotAllowedChars { get; set; }

        public CheckTextIsValid(char[] notAllowedChars)
        {
            NotAllowedChars = notAllowedChars;

        }
        protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
        {
            var v = (string)value;
            var result = v.IndexOfAny(NotAllowedChars);
            if (result == -1)
            {
                return ValidationResult.Success;
            }

            return new ValidationResult(ErrorMessage);

        }
    }

Then you can see When I input NewYork and a, The ErrorMessage will display behind a.

Notice: This demo just custom server-side validation, if you want custom client-side validation you can refer to this link.


来源: stackexchange

问:
ARN as a parameter in Cloud Formation Stack
I wanted to use the ARN as parameter input to cloudformation stack resources EventRuleRegion1 - Target as well as EventBridgeIAMrole  , but it is not working. when i call with Ref function

Original ARN

```<code>arn:aws:events:ap-southeast-2:123456789123:event-bus/central-eventbus-sydney
</code>```

When i give the arn directly in code its working fine.

Code

```<code>AWSTemplateFormatVersion: 2010-09-09

Parameters:
  EventBridgeName:
    Description: Enter the Event Bridge Name
    Type: String
    Default: ec2-lifecycle-events

  EventBusName:
    Description: Enter the Central Event Bus Name
    Type: String
    Default: central-eventbus-sydney

  EventBusArn:
    Description: Enter the ARN of Central Event Bus
    Type: String
    Default: arn:aws:events:ap-southeast-2:123456789123:event-bus/central-eventbus-sydney

  Monitoringaccount:
    Description: Enter the Monitoring AWS account number
    Type: String
    Default: 123456789123

Resources:
    EventRuleRegion1:
        Type: AWS::Events::Rule
        Properties:
            Description: Event rule to send events to monitoring account event bus
            EventBusName: default
            EventPattern:
                source:
                    - aws.ec2
                detail-type:
                    - "EC2 Instance State-change Notification"
                detail:
                  state:
                    - "running"
                    - "stopped"
                    - "terminated"

            Name: !Ref EventBridgeName
            State: ENABLED
            Targets:
                - Arn: >-
                    - !Join [ "", [ !Sub "arn:aws:events:${AWS::Region}:123456789123:event-bus/",!Ref EventBusName ] ]
                  Id: !Ref EventBusName
                  RoleArn: !GetAtt
                    - EventBridgeIAMrole
                    - Arn

    EventBridgeIAMrole:
        Type: 'AWS::IAM::Role'
        Properties:
            AssumeRolePolicyDocument:
                Version: 2012-10-17
                Statement:
                    - Effect: Allow
                      Principal:
                        Service: !Sub events.amazonaws.com
                      Action: 'sts:AssumeRole'
            Path: /
            Policies:
                - PolicyName: PutEventsDestinationBus
                  PolicyDocument:
                    Version: 2012-10-17
                    Statement:
                        - Effect: Allow
                          Action:
                            - 'events:PutEvents'
                          Resource:
                            - >-
                              - !Join [ "", [ !Sub "arn:aws:events:${AWS::Region}:123456789123:event-bus/",!Ref EventBusName ] ]
</code>```

Error

```<code>Parameter - !Join [ "", [ !Sub "arn:aws:events:${AWS::Region}:123456789123:event-bus/",!Ref EventBusName ] ] is not valid. Reason: Provided Arn is not in correct format. (Service: AmazonCloudWatchEvents; Status Code: 400; Error Code: ValidationException; Request ID: 0d52a1d6-095e-44f7-9455-b7481dc4fb8d; Proxy: null)
</code>```

答:
The use of  >- will result in literal strings, not evaluation of your CFN functions (join, ref). It should be:

```<code>            Targets:
                - Arn: !Join [ "", [ !Sub "arn:aws:events:${AWS::Region}:123456789123:event-bus/",!Ref EventBusName ] ]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I wanted to use the ARN as parameter input to cloudformation stack resources EventRuleRegion1 - Target as well as EventBridgeIAMrole  , but it is not working. when i call with Ref function

Original ARN

arn:aws:events:ap-southeast-2:123456789123:event-bus/central-eventbus-sydney

When i give the arn directly in code its working fine.

Code

AWSTemplateFormatVersion: 2010-09-09

Parameters:
  EventBridgeName:
    Description: Enter the Event Bridge Name
    Type: String
    Default: ec2-lifecycle-events

  EventBusName:
    Description: Enter the Central Event Bus Name
    Type: String
    Default: central-eventbus-sydney

  EventBusArn:
    Description: Enter the ARN of Central Event Bus
    Type: String
    Default: arn:aws:events:ap-southeast-2:123456789123:event-bus/central-eventbus-sydney

  Monitoringaccount:
    Description: Enter the Monitoring AWS account number
    Type: String
    Default: 123456789123

Resources:
    EventRuleRegion1:
        Type: AWS::Events::Rule
        Properties:
            Description: Event rule to send events to monitoring account event bus
            EventBusName: default
            EventPattern:
                source:
                    - aws.ec2
                detail-type:
                    - "EC2 Instance State-change Notification"
                detail:
                  state:
                    - "running"
                    - "stopped"
                    - "terminated"

            Name: !Ref EventBridgeName
            State: ENABLED
            Targets:
                - Arn: >-
                    - !Join [ "", [ !Sub "arn:aws:events:${AWS::Region}:123456789123:event-bus/",!Ref EventBusName ] ]
                  Id: !Ref EventBusName
                  RoleArn: !GetAtt
                    - EventBridgeIAMrole
                    - Arn

    EventBridgeIAMrole:
        Type: 'AWS::IAM::Role'
        Properties:
            AssumeRolePolicyDocument:
                Version: 2012-10-17
                Statement:
                    - Effect: Allow
                      Principal:
                        Service: !Sub events.amazonaws.com
                      Action: 'sts:AssumeRole'
            Path: /
            Policies:
                - PolicyName: PutEventsDestinationBus
                  PolicyDocument:
                    Version: 2012-10-17
                    Statement:
                        - Effect: Allow
                          Action:
                            - 'events:PutEvents'
                          Resource:
                            - >-
                              - !Join [ "", [ !Sub "arn:aws:events:${AWS::Region}:123456789123:event-bus/",!Ref EventBusName ] ]

Error

Parameter - !Join [ "", [ !Sub "arn:aws:events:${AWS::Region}:123456789123:event-bus/",!Ref EventBusName ] ] is not valid. Reason: Provided Arn is not in correct format. (Service: AmazonCloudWatchEvents; Status Code: 400; Error Code: ValidationException; Request ID: 0d52a1d6-095e-44f7-9455-b7481dc4fb8d; Proxy: null)

Body:
The use of  >- will result in literal strings, not evaluation of your CFN functions (join, ref). It should be:

            Targets:
                - Arn: !Join [ "", [ !Sub "arn:aws:events:${AWS::Region}:123456789123:event-bus/",!Ref EventBusName ] ]


问:
ES7 React/Redux/GraphQL/React-Native snippets not working
I'm unable to use ES7 React/Redux/GraphQL/React-Native snippets for some reason even though I have installed the extension required.

答:
you have to downgrade to v3.1.1 for it to work, I faced a similar issue and solved it in this way I think the updated version doesn't work fsr

right-click on the extension and select install another version then on the top a list of the versions will come up then select v3.1.1


问:
Declaring functions inside a loop in php
Suppose, I've a function like this -

function something() {

}
```
<p>Now, I need to loop this function by changing the function name like this -</p>
<pre class="lang-php prettyprint-override"><code>function something1() {

}

function something2() {

}

function something3() {

}

function something4() {

}
</code>```

Is it possible to declare functions by loop ?? There are some other code staffs which is already looping inside of the for loop. But I can't change function names dynamically. Most importantly, I can't declare functions separately. I must do it inside a loop.

Can you help me to figure out that how can I do it??

Thanks.

答:
I'm not sure what your asking precisely, because declaring is different from looping, but...

In case you want to call a function by a variable name, you can achieve this by using the concept of variable functions.
See https://www.php.net/manual/en/functions.variable-functions.php for more information.

```<code><?php

function something1()
{
    echo 'First';
}

function something2()
{
    echo 'Second';
}

function something3()
{
    echo 'Third';
}

function something4()
{
    echo 'Fourth';
}

for ($i = 1; $i < 5; $i++) {
    $functionName = "something$i";
    echo $functionName() . " function is called.\n";
}
</code>```

Body:
Suppose, I've a function like this -

function something() {

}

Now, I need to loop this function by changing the function name like this -

function something1() {

}

function something2() {

}

function something3() {

}

function something4() {

}

Is it possible to declare functions by loop ?? There are some other code staffs which is already looping inside of the for loop. But I can't change function names dynamically. Most importantly, I can't declare functions separately. I must do it inside a loop.

Can you help me to figure out that how can I do it??

Thanks.

Body:
I'm not sure what your asking precisely, because declaring is different from looping, but...

In case you want to call a function by a variable name, you can achieve this by using the concept of variable functions.
See https://www.php.net/manual/en/functions.variable-functions.php for more information.

<?php

function something1()
{
    echo 'First';
}

function something2()
{
    echo 'Second';
}

function something3()
{
    echo 'Third';
}

function something4()
{
    echo 'Fourth';
}

for ($i = 1; $i < 5; $i++) {
    $functionName = "something$i";
    echo $functionName() . " function is called.\n";
}


问:
Colliderect function not working in Pygame
So I am making a pong game in pygame while implementing oop. My problem is the colliderect function is giving me the error " ball_hitter object has no attribute 'colliderect'". I've used the colliderect function before but it's not working for me this time.

Code:

```<code>import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((500,500))
pygame.display.set_caption("Pong With Classes!")
#Variables
red = (255,0,0)
blue = (0,0,255)
black = (0,0,0)
clock = pygame.time.Clock()
#End of Variables
class ball_hitter:
    def __init__(self,x,y,length,width,color):
        self.x = x
        self.y = y
        self.length = length
        self.width = width
        self.color = color
        self.left = False
        self.right = False
    def draw_ball_hitter(self):
        screen.fill(black)
        pygame.draw.rect(screen,self.color,(self.x,self.y,self.length,self.width))
#Paddle creation
paddle = ball_hitter(250,400,130,20,red)
#End  of Paddle Creation
class thing_thats_being_hit:
    def __init__(self,x,y,color):
        self.x = x
        self.y = y
        self.radius = 27
        self.color = color
        self.speed_x = -4
        self.speed_y = 4
    def draw_googlyball(self):
        pygame.draw.circle(screen,self.color,(self.x,self.y),self.radius)
    def move(self):
        self.x += self.speed_x
        self.y += self.speed_y
#Ball Creation
ball = thing_thats_being_hit(200,50,blue)
#End of Ball Creation

#Paddle Collision
if paddle.colliderect(ball):
    print("It Worked!")
#End Of Paddle Collision

ball.move()
while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            exit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                paddle.left = True
            if event.key == pygame.K_RIGHT:
                paddle.right = True
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT:
                paddle.left = False
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_RIGHT:
                paddle.right = False
    paddle.draw_ball_hitter()
    ball.draw_googlyball()
    if paddle.left == True:
        paddle.x = paddle.x - 2
    if paddle.right == True:
        paddle.x = paddle.x + 2
    if ball.x <= 0:
        ball.speed_x*=-1
    if ball.x >= 500:
        ball.speed_x *= -1
    if ball.y >= 500:
        pygame.quit()
    ball.move()
    pygame.display.update()
    clock.tick(100)
</code>```

I would appreciate it if someone could give me a fixed code and explain is to me.

答:
See How do I detect collision in pygame?. colliderect is a method of pygame.Rect. Therefore you need to create pygame.Rect objects. Also you have to do the collision test in the application loop instead of before the application loop:

while True:
    # [...]

    paddle_rect = pygame.Rect(paddle.x, paddle.y, paddle.width, paddle. length)
    ball_rect = pygame.Rect(ball.x - ball.radius, ball.y - ball.radius,
                            ball.radius * 2, ball.radius * 2)

    if paddle_rect.colliderect(ball_rect):
        print("It Worked!")
```

Body:
So I am making a pong game in pygame while implementing oop. My problem is the colliderect function is giving me the error " ball_hitter object has no attribute 'colliderect'". I've used the colliderect function before but it's not working for me this time.

Code:

import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((500,500))
pygame.display.set_caption("Pong With Classes!")
#Variables
red = (255,0,0)
blue = (0,0,255)
black = (0,0,0)
clock = pygame.time.Clock()
#End of Variables
class ball_hitter:
    def __init__(self,x,y,length,width,color):
        self.x = x
        self.y = y
        self.length = length
        self.width = width
        self.color = color
        self.left = False
        self.right = False
    def draw_ball_hitter(self):
        screen.fill(black)
        pygame.draw.rect(screen,self.color,(self.x,self.y,self.length,self.width))
#Paddle creation
paddle = ball_hitter(250,400,130,20,red)
#End  of Paddle Creation
class thing_thats_being_hit:
    def __init__(self,x,y,color):
        self.x = x
        self.y = y
        self.radius = 27
        self.color = color
        self.speed_x = -4
        self.speed_y = 4
    def draw_googlyball(self):
        pygame.draw.circle(screen,self.color,(self.x,self.y),self.radius)
    def move(self):
        self.x += self.speed_x
        self.y += self.speed_y
#Ball Creation
ball = thing_thats_being_hit(200,50,blue)
#End of Ball Creation

#Paddle Collision
if paddle.colliderect(ball):
    print("It Worked!")
#End Of Paddle Collision

ball.move()
while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            exit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                paddle.left = True
            if event.key == pygame.K_RIGHT:
                paddle.right = True
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT:
                paddle.left = False
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_RIGHT:
                paddle.right = False
    paddle.draw_ball_hitter()
    ball.draw_googlyball()
    if paddle.left == True:
        paddle.x = paddle.x - 2
    if paddle.right == True:
        paddle.x = paddle.x + 2
    if ball.x <= 0:
        ball.speed_x*=-1
    if ball.x >= 500:
        ball.speed_x *= -1
    if ball.y >= 500:
        pygame.quit()
    ball.move()
    pygame.display.update()
    clock.tick(100)

I would appreciate it if someone could give me a fixed code and explain is to me.


问:
new to python having trouble printing 4 variables
```<code>adding = int(5+3)
subtract = int(10-2)
multiplication = int(2*4)
division = int(16/2)
print (str(adding,"\n",subtract,"\n",multiplication,"\n",division))
</code>```

im getting a typeError: TypeError: str() takes at most 3 arguments (7 given)

答:
To convert an integer to string, you need to use str()  each variables separately.
Also, you can use + as concat operator to avoid extra space.

```<code>print(str(adding)+"\n"+str(subtract)+"\n"+str(multiplication)+"\n"+str(division))
</code>```

Body:
adding = int(5+3)
subtract = int(10-2)
multiplication = int(2*4)
division = int(16/2)
print (str(adding,"\n",subtract,"\n",multiplication,"\n",division))

im getting a typeError: TypeError: str() takes at most 3 arguments (7 given)

Body:
To convert an integer to string, you need to use str()  each variables separately.
Also, you can use + as concat operator to avoid extra space.

print(str(adding)+"\n"+str(subtract)+"\n"+str(multiplication)+"\n"+str(division))


问:
Is it possible to show alert in `clickedButtonAtIndex` method of alertview
In delegate method ofUIalerview I am trying to show another alert after finishing the process on clicking button index. Is it possible to do so?  Also I want to call a method on button click of alert. How can I do that?

I am trying in this way. Is is correct?

```<code>- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(buttonIndex == 1)
    {
        inappPurchaseViewController  = [[InAppPurchaseViewController alloc] init];
        [inappPurchaseViewController Upgrade:nil];
        [inappPurchaseViewController release];

        UIAlertView *purchasedone = [[UIAlertView alloc] initWithTitle:@"Enable Ads" message:@"You can Enable Ads from Settings Option" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [purchasedone show];
        [purchasedone release];
    }
}
</code>```

答:
```<code> UIAlertView *a = [[UIAlertView alloc] initWithTitle:@"a" message:@"b" delegate:self        cancelButtonTitle:@"OK" otherButtonTitles:@"ca",nil];
[a show];
[a release];

 - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {

if(buttonIndex == 1)
{
    UIAlertView *purchasedone = [[UIAlertView alloc] initWithTitle:@"Enable Ads" message:@"You can Enable Ads from Settings Option" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    purchasedone.tag = 55;
    [purchasedone show];
    [purchasedone release];

}

if([alertView tag] == 55 && buttonIndex == 0)
{
    UIAlertView *purchasedone = [[UIAlertView alloc] initWithTitle:@"New Alert" message:@"New Alert Message" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [purchasedone show];
    [purchasedone release];
}
</code>```

}

write UIAlertViewDelegate in .h file.

ContentLicense: CC BY-SA 3.0

Body:
In delegate method ofUIalerview I am trying to show another alert after finishing the process on clicking button index. Is it possible to do so?  Also I want to call a method on button click of alert. How can I do that?

I am trying in this way. Is is correct?

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(buttonIndex == 1)
    {
        inappPurchaseViewController  = [[InAppPurchaseViewController alloc] init];
        [inappPurchaseViewController Upgrade:nil];
        [inappPurchaseViewController release];

        UIAlertView *purchasedone = [[UIAlertView alloc] initWithTitle:@"Enable Ads" message:@"You can Enable Ads from Settings Option" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [purchasedone show];
        [purchasedone release];
    }
}

Body:
 UIAlertView *a = [[UIAlertView alloc] initWithTitle:@"a" message:@"b" delegate:self        cancelButtonTitle:@"OK" otherButtonTitles:@"ca",nil];
[a show];
[a release];

 - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {

if(buttonIndex == 1)
{
    UIAlertView *purchasedone = [[UIAlertView alloc] initWithTitle:@"Enable Ads" message:@"You can Enable Ads from Settings Option" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    purchasedone.tag = 55;
    [purchasedone show];
    [purchasedone release];

}

if([alertView tag] == 55 && buttonIndex == 0)
{
    UIAlertView *purchasedone = [[UIAlertView alloc] initWithTitle:@"New Alert" message:@"New Alert Message" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [purchasedone show];
    [purchasedone release];
}

}

write UIAlertViewDelegate in .h file.


问:
Import a file from a subdirectory?
I have a file called tester.py, located on /project.

/project has a subdirectory called lib, with a file called BoxTime.py:

/project/tester.py
/project/lib/BoxTime.py
```

<p>I want to import <code>BoxTime</code> from <code>tester</code>. I have tried this:</p>

```import lib.BoxTime
```

<p>Which resulted:</p>

<pre class="lang-none prettyprint-override"><code>Traceback (most recent call last):
  File "./tester.py", line 3, in <module>
    import lib.BoxTime
ImportError: No module named lib.BoxTime
</code>```

Any ideas how to import BoxTime from the subdirectory?

EDIT

The __init__.py was the problem, but don't forget to refer to BoxTime as lib.BoxTime, or use:

```<code>import lib.BoxTime as BT
...
BT.bt_function()
</code>```

答:
For this folder hierarchy diagram example:

```<code>/project/tester.py
/project/lib/BoxTime.py
</code>```

1- Create a blank py file __init__.py inside lib folder

2- In the caller py file tester.py add theses code lines

```<code>import os, sys
sys.path.insert(0,'lib')# insert the folder lib in system path
from BoxTime import Function_name # from the py file import the needed function
</code>```

Easy explanation can be found in here.

Notice: This is refered to as creating/importing modules in/from different folder.

Personel experience: I tried to create module from jupyter notebook, it did not not work (maybe I done it improperly using .ipynb), I needed to do it manually outside the juypyter notebook, or using other IDE (e.g. pycharm).

Title: Import a file from a subdirectory?

Body:
I have a file called tester.py, located on /project.

/project has a subdirectory called lib, with a file called BoxTime.py:

/project/tester.py
/project/lib/BoxTime.py

I want to import BoxTime from tester. I have tried this:

import lib.BoxTime

Which resulted:

Traceback (most recent call last):
  File "./tester.py", line 3, in <module>
    import lib.BoxTime
ImportError: No module named lib.BoxTime

Any ideas how to import BoxTime from the subdirectory?

EDIT

The __init__.py was the problem, but don't forget to refer to BoxTime as lib.BoxTime, or use:

import lib.BoxTime as BT
...
BT.bt_function()

Body:
For this folder hierarchy diagram example:

/project/tester.py
/project/lib/BoxTime.py

1- Create a blank py file __init__.py inside lib folder

2- In the caller py file tester.py add theses code lines

import os, sys
sys.path.insert(0,'lib')# insert the folder lib in system path
from BoxTime import Function_name # from the py file import the needed function

Easy explanation can be found in here.

Notice: This is refered to as creating/importing modules in/from different folder.

Personel experience: I tried to create module from jupyter notebook, it did not not work (maybe I done it improperly using .ipynb), I needed to do it manually outside the juypyter notebook, or using other IDE (e.g. pycharm).


问:
Hiding and showing columns onthe same table/view in Oracle
Is it possible in Oracle to create a table (or a view) where two different users access the same table (or the same view) and they see different sets of columns?

For instance, two users execute the same query against a table/view named employees:

```<code>select * from employees;
</code>```

One user sees data for columns name and salary (total columns = 2).

The other user sees data only for the name column (total columns = 1).

I know that a common solution is to create two views against a base table, and assign different permissions to each view. However, that doesn't work for us, as our application needs to use the same select (the same FROM) for both users. In other words, we need to treat the table/view as the same object, with the same db.schema.name identifier for all users. Creating two views would create two objects with different names.

Some databases allow granting column permissions to a table (or view's) columns, but Oracle apparently doesn't allow me to GRANT SELECT privs on individual columns.

The other option is VPD. However, the examples of VPDs I've seen don't show how to hide an entire column. They show how to hide rows based on column values (e.g. https://docs.oracle.com/cd/B28359_01/network.111/b28531/vpd.htm#DBSEG98231) or they show how to mask some or all of the values in a column. I haven't seen a VPD example that completely hides a column based on user permissions.

Are there any other options in Oracle to hide a column based on user permissions?

Thanks in advance

答:
You go into right direction. Create specific view for each user

```<code>create view employees_a as select name, salary from employees;
create view employees_b as select name from employees;
</code>```

Then in order to use always the same name, create user specific SYNONYMS:

```<code>create synonym user_a.employees for main_schema.employees_a;
create synonym user_b.employees for main_schema.employees_b;
</code>```

Body:
Is it possible in Oracle to create a table (or a view) where two different users access the same table (or the same view) and they see different sets of columns?

For instance, two users execute the same query against a table/view named employees:

select * from employees;

One user sees data for columns name and salary (total columns = 2).

The other user sees data only for the name column (total columns = 1).

I know that a common solution is to create two views against a base table, and assign different permissions to each view. However, that doesn't work for us, as our application needs to use the same select (the same FROM) for both users. In other words, we need to treat the table/view as the same object, with the same db.schema.name identifier for all users. Creating two views would create two objects with different names.

Some databases allow granting column permissions to a table (or view's) columns, but Oracle apparently doesn't allow me to GRANT SELECT privs on individual columns.

The other option is VPD. However, the examples of VPDs I've seen don't show how to hide an entire column. They show how to hide rows based on column values (e.g. https://docs.oracle.com/cd/B28359_01/network.111/b28531/vpd.htm#DBSEG98231) or they show how to mask some or all of the values in a column. I haven't seen a VPD example that completely hides a column based on user permissions.

Are there any other options in Oracle to hide a column based on user permissions?

Thanks in advance

Body:
You go into right direction. Create specific view for each user

create view employees_a as select name, salary from employees;
create view employees_b as select name from employees;

Then in order to use always the same name, create user specific SYNONYMS:

create synonym user_a.employees for main_schema.employees_a;
create synonym user_b.employees for main_schema.employees_b;


问:
Lunch Order Billing Menu
Alright so, i have got most of the things working except when i want to order something else like Pizza the Add-On items should change to Pepperoni, Sausage, Olives or Salad the Add-On items should change to  Croutons, Bacon bits, Bread stick but its not changing. Here is what i have got so far:

```<code>enter code here public partial class Form1 : Form
{
    decimal Subtotal;
    decimal Tax = 0.0775m;
    decimal OrderTotal;

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        decimal add = 0m;
        if (chk1.Checked)
        {
            add++;
        }
        if (chk2.Checked)
        {
            add++;
        }
        if (chk3.Checked)
        {
            add++;
        }
        if (rdoHamburger.Checked)
        {
            decimal Hamburger = Convert.ToDecimal(rdoHamburger.Checked);
            Hamburger = 6.95m;

            Subtotal = Hamburger + (add * .75m);
            Tax = Subtotal * 0.0775m;
            OrderTotal = Tax + Subtotal;

            textBox1.Text = Subtotal.ToString("c");
            textBox2.Text = Tax.ToString("c");
            textBox3.Text = OrderTotal.ToString("c");

        }
        else if (rdoPizza.Checked)
        {

            decimal Pizza = Convert.ToDecimal(rdoPizza.Checked);
            Pizza = 5.95m;

            Subtotal = Pizza + (add * .50m);

            Tax = Subtotal * 0.00775m;

            OrderTotal = Tax + Subtotal;

            textBox1.Text = Subtotal.ToString("c");
            textBox2.Text = Tax.ToString("c");
            textBox3.Text = OrderTotal.ToString("c");

        }
        else if (rdoSalad.Checked)
        {

            decimal salad = Convert.ToDecimal(rdoSalad.Checked);
            salad = 4.95m;

            Subtotal = salad + (add * .25m);

            Tax = Subtotal * 0.0775m;
            OrderTotal = Tax + Subtotal;
            textBox1.Text = Subtotal.ToString("c");
            textBox2.Text = Tax.ToString("c");
            textBox3.Text = OrderTotal.ToString("c");
        }
    }

    private void groupBox1_Enter(object sender, EventArgs e)
    {
        if (rdoHamburger.Checked)
        {
            gbxAddOnItems.Text = "Add-on items ($.75 each)";
            chk1.Text = "Lettuce, tomato and ketchup";
            chk2.Text = "Ketchup , mustard and mayo";
            chk3.Text = "French fries";

            chk1.Checked = false;
            chk2.Checked = false;
            chk3.Checked = false;

            textBox1.Clear();
            textBox2.Clear();
            textBox3.Clear();

        }
        else if (rdoPizza.Checked)
        {
            gbxAddOnItems.Text = "Add-on items ($.50 each)";
            chk1.Text = "Pepperoni";
            chk2.Text = "Sausage";
            chk3.Text = "Olives";

            chk1.Checked = false;
            chk2.Checked = false;
            chk3.Checked = false;

            textBox1.Clear();
            textBox2.Clear();
            textBox3.Clear();

        }
        else if (rdoSalad.Checked)
        {
            gbxAddOnItems.Text = "Add-on items ($.25 each)";
            chk1.Text = "Croutons";
            chk2.Text = "Bacon bits";
            chk3.Text = "Bread Sticks";

            chk1.Checked = false;
            chk2.Checked = false;
            chk3.Checked = false;

            textBox1.Clear();
            textBox2.Clear();
            textBox3.Clear();
        }
        textBox1.Clear();
        textBox2.Clear();
        textBox3.Clear();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        string message = "Thank You for Using Our Service!\n Would You Like use our service again?";
        DialogResult button =
            MessageBox.Show(message, "Dear Customer",
            MessageBoxButtons.YesNo,
            MessageBoxIcon.Information);

        if (button == DialogResult.No)
        {
            this.Close();
        }
        if (button == DialogResult.Yes)
        {
            MessageBox.Show("Thank You!! \n We Hope you will come Soon!", "Greeting      Message");
            this.Close();
        }

    }
}
</code>```

...

I would be grateful if anyone could help have 2 days left.

答:
please use CheckedChanged event of RadioButtons,

```<code>private void rdoHamburger_CheckedChanged(object sender, EventArgs e)
{
    chk1.Text = "Lettuce, tomato and ketchup";
    chk2.Text = "Ketchup , mustard and mayo";
    chk3.Text = "French fries";
}

private void rdoPizza_CheckedChanged(object sender, EventArgs e)
{
    chk1.Text = "Pepperoni";
    chk2.Text = "Sausage";
    chk3.Text = "Olives";
}

private void rdoSalad_CheckedChanged(object sender, EventArgs e)
{
    chk1.Text = "Croutons";
    chk2.Text = "Bacon bits";
    chk3.Text = "Bread Sticks";
}
</code>```

Title: Lunch Order Billing Menu

Body:
Alright so, i have got most of the things working except when i want to order something else like Pizza the Add-On items should change to Pepperoni, Sausage, Olives or Salad the Add-On items should change to  Croutons, Bacon bits, Bread stick but its not changing. Here is what i have got so far:

enter code here public partial class Form1 : Form
{
    decimal Subtotal;
    decimal Tax = 0.0775m;
    decimal OrderTotal;

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        decimal add = 0m;
        if (chk1.Checked)
        {
            add++;
        }
        if (chk2.Checked)
        {
            add++;
        }
        if (chk3.Checked)
        {
            add++;
        }
        if (rdoHamburger.Checked)
        {
            decimal Hamburger = Convert.ToDecimal(rdoHamburger.Checked);
            Hamburger = 6.95m;

            Subtotal = Hamburger + (add * .75m);
            Tax = Subtotal * 0.0775m;
            OrderTotal = Tax + Subtotal;

            textBox1.Text = Subtotal.ToString("c");
            textBox2.Text = Tax.ToString("c");
            textBox3.Text = OrderTotal.ToString("c");

        }
        else if (rdoPizza.Checked)
        {

            decimal Pizza = Convert.ToDecimal(rdoPizza.Checked);
            Pizza = 5.95m;

            Subtotal = Pizza + (add * .50m);

            Tax = Subtotal * 0.00775m;

            OrderTotal = Tax + Subtotal;

            textBox1.Text = Subtotal.ToString("c");
            textBox2.Text = Tax.ToString("c");
            textBox3.Text = OrderTotal.ToString("c");

        }
        else if (rdoSalad.Checked)
        {

            decimal salad = Convert.ToDecimal(rdoSalad.Checked);
            salad = 4.95m;

            Subtotal = salad + (add * .25m);

            Tax = Subtotal * 0.0775m;
            OrderTotal = Tax + Subtotal;
            textBox1.Text = Subtotal.ToString("c");
            textBox2.Text = Tax.ToString("c");
            textBox3.Text = OrderTotal.ToString("c");
        }
    }

    private void groupBox1_Enter(object sender, EventArgs e)
    {
        if (rdoHamburger.Checked)
        {
            gbxAddOnItems.Text = "Add-on items ($.75 each)";
            chk1.Text = "Lettuce, tomato and ketchup";
            chk2.Text = "Ketchup , mustard and mayo";
            chk3.Text = "French fries";

            chk1.Checked = false;
            chk2.Checked = false;
            chk3.Checked = false;

            textBox1.Clear();
            textBox2.Clear();
            textBox3.Clear();

        }
        else if (rdoPizza.Checked)
        {
            gbxAddOnItems.Text = "Add-on items ($.50 each)";
            chk1.Text = "Pepperoni";
            chk2.Text = "Sausage";
            chk3.Text = "Olives";

            chk1.Checked = false;
            chk2.Checked = false;
            chk3.Checked = false;

            textBox1.Clear();
            textBox2.Clear();
            textBox3.Clear();

        }
        else if (rdoSalad.Checked)
        {
            gbxAddOnItems.Text = "Add-on items ($.25 each)";
            chk1.Text = "Croutons";
            chk2.Text = "Bacon bits";
            chk3.Text = "Bread Sticks";

            chk1.Checked = false;
            chk2.Checked = false;
            chk3.Checked = false;

            textBox1.Clear();
            textBox2.Clear();
            textBox3.Clear();
        }
        textBox1.Clear();
        textBox2.Clear();
        textBox3.Clear();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        string message = "Thank You for Using Our Service!\n Would You Like use our service again?";
        DialogResult button =
            MessageBox.Show(message, "Dear Customer",
            MessageBoxButtons.YesNo,
            MessageBoxIcon.Information);

        if (button == DialogResult.No)
        {
            this.Close();
        }
        if (button == DialogResult.Yes)
        {
            MessageBox.Show("Thank You!! \n We Hope you will come Soon!", "Greeting      Message");
            this.Close();
        }

    }
}

...

I would be grateful if anyone could help have 2 days left.

Body:
please use CheckedChanged event of RadioButtons,

private void rdoHamburger_CheckedChanged(object sender, EventArgs e)
{
    chk1.Text = "Lettuce, tomato and ketchup";
    chk2.Text = "Ketchup , mustard and mayo";
    chk3.Text = "French fries";
}

private void rdoPizza_CheckedChanged(object sender, EventArgs e)
{
    chk1.Text = "Pepperoni";
    chk2.Text = "Sausage";
    chk3.Text = "Olives";
}

private void rdoSalad_CheckedChanged(object sender, EventArgs e)
{
    chk1.Text = "Croutons";
    chk2.Text = "Bacon bits";
    chk3.Text = "Bread Sticks";
}


问:
Android studio can't see the design?
I have been doing it in Android studio for a few days but I have never had such a problem :(

Background  blank only text showing androidx.constraintlayout....ConstraintLayout

XML file

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Gradle file

```<code>dependencies {

implementation 'androidx.appcompat:appcompat:1.4.1'
implementation 'com.google.android.material:material:1.5.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
</code>```

enter image description here

```<code>dependencies {
    classpath "com.android.tools.build:gradle:7.0.4"

    // NOTE: Do not place your application dependencies here; they
    belong
    // in the individual module build.gradle files
}
</code>```

答:
Update your Constraintlayout dependency in your app level build.gradle and check:

```<code>implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
</code>```

Title: Android studio can't see the design?

Body:
I have been doing it in Android studio for a few days but I have never had such a problem :(

Background  blank only text showing androidx.constraintlayout....ConstraintLayout

XML file

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
</androidx.constraintlayout.widget.ConstraintLayout>

Gradle file

dependencies {

implementation 'androidx.appcompat:appcompat:1.4.1'
implementation 'com.google.android.material:material:1.5.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}

enter image description here

dependencies {
    classpath "com.android.tools.build:gradle:7.0.4"

    // NOTE: Do not place your application dependencies here; they
    belong
    // in the individual module build.gradle files
}

Body:
Update your Constraintlayout dependency in your app level build.gradle and check:

implementation 'androidx.constraintlayout:constraintlayout:2.1.3'


问:
How do I pass the value of Select from Child to Parent Component?
The user can choose the category in which another select will appear depending on what was selected. I create the 2nd component in another .js. I can already view the data but how can I pass the value of my 2nd component to the parent component?

I wanted to pass the value of the select from the size1,js to the demo.js

Link: https://codesandbox.io/s/category-selection-oiu7d

demo.js

```<code>import * as React from "react";
import Box from "@mui/material/Box";
import InputLabel from "@mui/material/InputLabel";
import MenuItem from "@mui/material/MenuItem";
import FormControl from "@mui/material/FormControl";
import Select from "@mui/material/Select";
import Size1 from "./size1";

export default function BasicSelect() {
  const [age, setAge] = React.useState("");

  const handleChange = (event) => {
    setAge(event.target.value);
  };

  return (
    <Box sx={{ minWidth: 120 }}>
      selected: {age}
      <br /> <br />
      <FormControl fullWidth>
        <InputLabel id="demo-simple-select-label">Category</InputLabel>
        <Select
          labelId="demo-simple-select-label"
          id="demo-simple-select"
          value={age}
          label="Age"
          onChange={handleChange}
        >
          <MenuItem value="S-XL">S-XL</MenuItem>
          <MenuItem value="Size2">Size2</MenuItem>
        </Select>
      </FormControl>
      {age === "S-XL" && (
        <>
          <Size1 />{" "}
        </>
      )}
    </Box>
  );
}
</code>```

size1.js

```<code>import * as React from "react";
import Box from "@mui/material/Box";
import InputLabel from "@mui/material/InputLabel";
import MenuItem from "@mui/material/MenuItem";
import FormControl from "@mui/material/FormControl";
import Select from "@mui/material/Select";

export const Size1 = ["XS", "S", "M", "L", "XL"];

export default function BasicSelect() {
  const [size1, setSize1] = React.useState("");

  const handleChange = (event) => {
    setSize1(event.target.value);
  };

  return (
    <Box sx={{ minWidth: 120 }}>
      chosen size: {size1}
      <br /> <br />
      <FormControl fullWidth>
        <InputLabel id="demo-simple-select-label">Choose Size</InputLabel>
        <Select
          labelId="demo-simple-select-label"
          id="demo-simple-select"
          value={size1}
          label="size1"
          onChange={handleChange}
        >
          <MenuItem value="XS">XS</MenuItem>
          <MenuItem value="S">S</MenuItem>
          <MenuItem value="M">M</MenuItem>
          <MenuItem value="L">L</MenuItem>
          <MenuItem value="XL">XL</MenuItem>
        </Select>
      </FormControl>
    </Box>
  );
}
</code>```

答:
I edited your code, please look https://codesandbox.io/s/category-selection-forked-rb8dl

Just remove onSelectionUpdate and it will work ;)

Body:
The user can choose the category in which another select will appear depending on what was selected. I create the 2nd component in another .js. I can already view the data but how can I pass the value of my 2nd component to the parent component?

I wanted to pass the value of the select from the size1,js to the demo.js

Link: https://codesandbox.io/s/category-selection-oiu7d

demo.js

import * as React from "react";
import Box from "@mui/material/Box";
import InputLabel from "@mui/material/InputLabel";
import MenuItem from "@mui/material/MenuItem";
import FormControl from "@mui/material/FormControl";
import Select from "@mui/material/Select";
import Size1 from "./size1";

export default function BasicSelect() {
  const [age, setAge] = React.useState("");

  const handleChange = (event) => {
    setAge(event.target.value);
  };

  return (
    <Box sx={{ minWidth: 120 }}>
      selected: {age}

      <FormControl fullWidth>
        <InputLabel id="demo-simple-select-label">Category</InputLabel>
        <Select
          labelId="demo-simple-select-label"
          id="demo-simple-select"
          value={age}
          label="Age"
          onChange={handleChange}
        >
          <MenuItem value="S-XL">S-XL</MenuItem>
          <MenuItem value="Size2">Size2</MenuItem>
        </Select>
      </FormControl>
      {age === "S-XL" && (
        <>
          <Size1 />{" "}
        </>
      )}
    </Box>
  );
}

size1.js

import * as React from "react";
import Box from "@mui/material/Box";
import InputLabel from "@mui/material/InputLabel";
import MenuItem from "@mui/material/MenuItem";
import FormControl from "@mui/material/FormControl";
import Select from "@mui/material/Select";

export const Size1 = ["XS", "S", "M", "L", "XL"];

export default function BasicSelect() {
  const [size1, setSize1] = React.useState("");

  const handleChange = (event) => {
    setSize1(event.target.value);
  };

  return (
    <Box sx={{ minWidth: 120 }}>
      chosen size: {size1}

      <FormControl fullWidth>
        <InputLabel id="demo-simple-select-label">Choose Size</InputLabel>
        <Select
          labelId="demo-simple-select-label"
          id="demo-simple-select"
          value={size1}
          label="size1"
          onChange={handleChange}
        >
          <MenuItem value="XS">XS</MenuItem>
          <MenuItem value="S">S</MenuItem>
          <MenuItem value="M">M</MenuItem>
          <MenuItem value="L">L</MenuItem>
          <MenuItem value="XL">XL</MenuItem>
        </Select>
      </FormControl>
    </Box>
  );
}


问:
How do I create a directory, and any missing parent directories?
How do I create a directory at a given path, and also create any missing parent directories along that path? For example, the Bash command mkdir -p /path/to/nested/directory does this.

答:
```<code>import os
directory = "./out_dir/subdir1/subdir2"
if not os.path.exists(directory):
    os.makedirs(directory)
</code>```

OwnerDisplayName: Parand

LastEditorDisplayName: Parand


问:
How to call a non-static method from a function pointer?
I have a class "Person" like so:

```<code>typedef void (*action)();
typedef std::unordered_map<int, action> keybindMap; // maps keycodes to functions

class Person {
    keybindMap keybinds;
    void doSomething();
}
</code>```

I use this to call the functions at the right times:

```<code>iter = keybinds.find(event.key.keysym.sym); // event.key.keysym.sym is the key code
if (iter != keybinds.end())
{
    (*iter->second)(); // call whatever function that key is bound to.
}
</code>```

To bind a key, I used keybinds.insert_or_assign(SDLK_a, doSomething). However, this doesn't work (because doSomething is non-static). How do I change the binding code and/or the (*iter->second)() part so that I can call something equivalent to person.doSomething?

答:
A non-static method requires an object to call it on. An ordinary function pointer doesn't have room to hold a reference to an object.

If you change your map to hold std::function instead, you can then use std::bind() or a lambda to associate an object with a method pointer, eg:

```<code>using action = std::function<void()>;
using keybindMap = std::unordered_map<int, action>;

class Person {
    keybindMap keybinds;
    void doSomething();
};

...

Person p, otherP; //must outlive the map...
p.keybinds[...] = [&otherP](){ otherP.doSomething(); }

...

iter = keybinds.find(event.key.keysym.sym);
if (iter != keybinds.end()) {
    iter->second();
}
</code>```

On the other hand, if all of the target methods are in the same class/object, you can use a plain method pointer instead of std::function, which will reduce some overhead, eg:

```<code>class Person {
    using action = void (Person::*)();
    using keybindMap = std::unordered_map<int, action>;

    keybindMap keybinds;
    void doSomething();
};

...

keybinds[...] = &Person::doSomething;

...

iter = keybinds.find(event.key.keysym.sym);
if (iter != keybinds.end()) {
    (this->*(iter->second))();
}
</code>```

Body:
I have a class "Person" like so:

typedef void (*action)();
typedef std::unordered_map<int, action> keybindMap; // maps keycodes to functions

class Person {
    keybindMap keybinds;
    void doSomething();
}

I use this to call the functions at the right times:

iter = keybinds.find(event.key.keysym.sym); // event.key.keysym.sym is the key code
if (iter != keybinds.end())
{
    (*iter->second)(); // call whatever function that key is bound to.
}

To bind a key, I used keybinds.insert_or_assign(SDLK_a, doSomething). However, this doesn't work (because doSomething is non-static). How do I change the binding code and/or the (*iter->second)() part so that I can call something equivalent to person.doSomething?

Body:
A non-static method requires an object to call it on. An ordinary function pointer doesn't have room to hold a reference to an object.

If you change your map to hold std::function instead, you can then use std::bind() or a lambda to associate an object with a method pointer, eg:

using action = std::function<void()>;
using keybindMap = std::unordered_map<int, action>;

class Person {
    keybindMap keybinds;
    void doSomething();
};

...

Person p, otherP; //must outlive the map...
p.keybinds[...] = [&otherP](){ otherP.doSomething(); }

...

iter = keybinds.find(event.key.keysym.sym);
if (iter != keybinds.end()) {
    iter->second();
}

On the other hand, if all of the target methods are in the same class/object, you can use a plain method pointer instead of std::function, which will reduce some overhead, eg:

class Person {
    using action = void (Person::*)();
    using keybindMap = std::unordered_map<int, action>;

    keybindMap keybinds;
    void doSomething();
};

...

keybinds[...] = &Person::doSomething;

...

iter = keybinds.find(event.key.keysym.sym);
if (iter != keybinds.end()) {
    (this->*(iter->second))();
}


问:
Replace buffer in Frida using JS
With Frida I print the SSL_write

```<code>Interceptor.attach(Module.findExportByName("libssl.so", "SSL_write"), {
    onEnter: function (args) {

        console.log(args[1].readByteArray(args[2].toInt32()));

    }
});
</code>```

I want to replace the buffer to write to SSL , if buffer contain Ascii of AAAAAA replace with BBBBBB

How can I do that ?

答:
Steps:

Allocate an Uint8Array with the same size as the function receives (you can check the size_t argument)

Copy the original buffer to our newly allocated one.

Perform the required operations (directly in the ArrayBuffer or convert it as a string back-and-forth).

Get a pointer to the first element of our newly allocated buffer by calling .unwrap().

const sslWritePtr = Module.getExportByName(null, "ssl_write");

function str2ab(str) {
  let buf = new ArrayBuffer(str.length);
  let bufView = new Uint8Array(buf);
  for (var i=0, strLen=str.length; i < strLen; i++) {
    bufView[i] = str.charCodeAt(i);
  }
  return buf;
}

Interceptor.attach(sslWritePtr, {
        onEnter: function (args) {
          // Get the buffer size by checking the third argument.
          const buffer_size = args[2].toInt32() + 1;
          // Read the contents of the buffer and get an ArrayBuffer.
          let buffer = args[1].readByteArray(buffer_size);
          // Convert it to a string object.
          let buffer_string = String.fromCharCode.apply(null, new Uint8Array(buffer));
          // Replace the contents.
          buffer_string = buffer_string.replace("AAAAAA", "BBBBBB");

          // Convert `buffer_string` back to an ArrayBuffer.
          // .unwrap() returns a pointer to the first element of the Uint8Array
          args[1] = str2ab(str).unwrap(); // Assign the pointer of our new Uint8Array.
        },
});
```

This link might be useful to understand better how to operate in this situation: https://learnfrida.info/intermediate_usage/#operating-with-arraybuffers

Title: Replace buffer in Frida using JS

Body:
With Frida I print the SSL_write

Interceptor.attach(Module.findExportByName("libssl.so", "SSL_write"), {
    onEnter: function (args) {

        console.log(args[1].readByteArray(args[2].toInt32()));

    }
});

I want to replace the buffer to write to SSL , if buffer contain Ascii of AAAAAA replace with BBBBBB

How can I do that ?

Body:
Steps:

Allocate an Uint8Array with the same size as the function receives (you can check the size_t argument)

Copy the original buffer to our newly allocated one.

Perform the required operations (directly in the ArrayBuffer or convert it as a string back-and-forth).

Get a pointer to the first element of our newly allocated buffer by calling .unwrap().

const sslWritePtr = Module.getExportByName(null, "ssl_write");

function str2ab(str) {
  let buf = new ArrayBuffer(str.length);
  let bufView = new Uint8Array(buf);
  for (var i=0, strLen=str.length; i < strLen; i++) {
    bufView[i] = str.charCodeAt(i);
  }
  return buf;
}

Interceptor.attach(sslWritePtr, {
        onEnter: function (args) {
          // Get the buffer size by checking the third argument.
          const buffer_size = args[2].toInt32() + 1;
          // Read the contents of the buffer and get an ArrayBuffer.
          let buffer = args[1].readByteArray(buffer_size);
          // Convert it to a string object.
          let buffer_string = String.fromCharCode.apply(null, new Uint8Array(buffer));
          // Replace the contents.
          buffer_string = buffer_string.replace("AAAAAA", "BBBBBB");

          // Convert `buffer_string` back to an ArrayBuffer.
          // .unwrap() returns a pointer to the first element of the Uint8Array
          args[1] = str2ab(str).unwrap(); // Assign the pointer of our new Uint8Array.
        },
});

This link might be useful to understand better how to operate in this situation: https://learnfrida.info/intermediate_usage/#operating-with-arraybuffers


问:
Reading S3 path as data in Spark SQL
Our source provides data in the form: s3://xxxx/yyyy/zzzz/mydate=2021-02-08/<lots of files>.parquet. I need to read all the parquet files in the s3 folder zzzz and then add a column in the read data called mydate that corresponds to the date from which folder the parquet files belong to. Is this possible in Spark SQL?

Example:

Lets say I have these two paths to read data from:

s3://xxxx/yyyy/zzzz/mydate=2021-02-08/abc.parquet

s3://xxxx/yyyy/zzzz/mydate=2021-02-09/pqr.parquet

Data read from spark:

Whatever columns
.
.
.
...
mydate

This row came from 2021-02-08 folder
.
.
.
...
2021-02-08

This row came from 2021-02-09 folder
.
.
.
...
2021-02-09

答:
You can read all the files under s3://xxxx/yyyy/zzzz/mydate=2021-02-08/<lots of files>.parquet into a DataFrame , then add the required mydate column

Data Preparation

```<code>os.environ['PYSPARK_SUBMIT_ARGS'] = "--packages=com.amazonaws:aws-java-sdk-bundle:1.11.375,org.apache.hadoop:hadoop-aws:3.2.0 pyspark-shell"

sc = SparkContext.getOrCreate()
sql = SQLContext(sc)

hadoop_conf = sc._jsc.hadoopConfiguration()

config = configparser.ConfigParser()

config.read(os.path.expanduser("~/.aws/credentials"))

access_key = config.get("****", "aws_access_key_id")
secret_key = config.get("****", "aws_secret_access_key")
session_key = config.get("****", "aws_session_token")

sc._jsc.hadoopConfiguration().set("fs.s3a.endpoint", "s3.amazonaws.com")
sc._jsc.hadoopConfiguration().set("fs.s3a.connection.ssl.enabled", "true")
sc._jsc.hadoopConfiguration().set("fs.s3a.impl", "org.apache.hadoop.fs.s3a.S3AFileSystem");

hadoop_conf.set("fs.s3.aws.credentials.provider", "org.apache.hadoop.fs.s3.TemporaryAWSCredentialsProvider")
hadoop_conf.set("fs.s3a.access.key", access_key)
hadoop_conf.set("fs.s3a.secret.key", secret_key)
hadoop_conf.set("fs.s3a.session.token", session_key)

s3_path = "s3a://xxxx/yyyy/zzzz/mydate=2021-02-08"

sparkDF = sql.read.parquet(s3_path)
</code>```

Extracting Date

```<code>>>> s3_path = "s3a://xxxx/yyyy/zzzz/mydate=2021-02-08"
>>>
>>>
>>> os.path.basename(os.path.splitext(s3_path)[0])
'mydate=2021-02-08'
>>>
>>>
>>> os.path.basename(os.path.splitext(s3_path)[0]).split("=")[1]
'2021-02-08'
>>>

</code>```

Adding Date Column

```<code>s3_path = "s3a://xxxx/yyyy/zzzz/mydate=2021-02-08"
mydate = os.path.basename(os.path.splitext(s3_path)[0]).split("=")[1]

sparkDF = sparkDF.withColumn('mydate',F.lit(mydate))
</code>```

Adding Date Column - SparkSQL

```<code>s3_path = "s3a://xxxx/yyyy/zzzz/mydate=2021-02-08"
mydate = os.path.basename(os.path.splitext(s3_path)[0]).split("=")[1]

sparkDF.registerTempTable("TB1")

sql.sql(f"""
SELECT
  *
  ,{mydate}
FROM TB1
""").show()
</code>```

Title: Reading S3 path as data in Spark SQL

Body:
You can read all the files under s3://xxxx/yyyy/zzzz/mydate=2021-02-08/<lots of files>.parquet into a DataFrame , then add the required mydate column

Data Preparation

os.environ['PYSPARK_SUBMIT_ARGS'] = "--packages=com.amazonaws:aws-java-sdk-bundle:1.11.375,org.apache.hadoop:hadoop-aws:3.2.0 pyspark-shell"

sc = SparkContext.getOrCreate()
sql = SQLContext(sc)

hadoop_conf = sc._jsc.hadoopConfiguration()

config = configparser.ConfigParser()

config.read(os.path.expanduser("~/.aws/credentials"))

access_key = config.get("****", "aws_access_key_id")
secret_key = config.get("****", "aws_secret_access_key")
session_key = config.get("****", "aws_session_token")

sc._jsc.hadoopConfiguration().set("fs.s3a.endpoint", "s3.amazonaws.com")
sc._jsc.hadoopConfiguration().set("fs.s3a.connection.ssl.enabled", "true")
sc._jsc.hadoopConfiguration().set("fs.s3a.impl", "org.apache.hadoop.fs.s3a.S3AFileSystem");

hadoop_conf.set("fs.s3.aws.credentials.provider", "org.apache.hadoop.fs.s3.TemporaryAWSCredentialsProvider")
hadoop_conf.set("fs.s3a.access.key", access_key)
hadoop_conf.set("fs.s3a.secret.key", secret_key)
hadoop_conf.set("fs.s3a.session.token", session_key)

s3_path = "s3a://xxxx/yyyy/zzzz/mydate=2021-02-08"

sparkDF = sql.read.parquet(s3_path)

Extracting Date

>>> s3_path = "s3a://xxxx/yyyy/zzzz/mydate=2021-02-08"
>>>
>>>
>>> os.path.basename(os.path.splitext(s3_path)[0])
'mydate=2021-02-08'
>>>
>>>
>>> os.path.basename(os.path.splitext(s3_path)[0]).split("=")[1]
'2021-02-08'
>>>

Adding Date Column

s3_path = "s3a://xxxx/yyyy/zzzz/mydate=2021-02-08"
mydate = os.path.basename(os.path.splitext(s3_path)[0]).split("=")[1]

sparkDF = sparkDF.withColumn('mydate',F.lit(mydate))

Adding Date Column - SparkSQL

s3_path = "s3a://xxxx/yyyy/zzzz/mydate=2021-02-08"
mydate = os.path.basename(os.path.splitext(s3_path)[0]).split("=")[1]

sparkDF.registerTempTable("TB1")

sql.sql(f"""
SELECT
  *
  ,{mydate}
FROM TB1
""").show()


问:
How to connect a "client" socket on any network in the world to my "socket server"
I made a socket to see how it works.

Basically my intention for testing was to run commands in client computer cmd

First I made the  server  to receive a connection from my other script client

```<code>import socket

HOST = '192.168.100.xx'  #my computer ipv4
PORT = 50000

server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server.bind((HOST,PORT))
server.listen(5)
print('Server waiting connection...')
conn,addr = server.accept()
print('Connection established!')
print('Connected in addr: {}\n'.format(addr))

while True:
    cmd = str(input('command>'))
    conn.send(str.encode(cmd))
    response = str(conn.recv(1024),"utf-8")
    print(response)
    if cmd == 'quit':
        break

server.close()
</code>```

Then I made the client:

```<code>import socket
import subprocess
import os

HOST = '192.168.100.xx' #ipv4 from my computer (server)
PORT = 50000

client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
client.connect((HOST,PORT))
print('Connecting to the server {}'.format(HOST))
while True:
    command = client.recv(1024).decode()

    print('Server command>'+command)
    cmd = subprocess.Popen(args=command,shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
    output = (cmd.stdout.read() + cmd.stderr.read()).decode("utf-8", errors="ignore")
    client.send(str.encode(str(output)+ str(os.getcwd()) +'$'))
</code>```

Here's how I get my IPv4 address:

Initially when I tested it on a machine on my network this worked fine, but when I sent the client to a friend far away to run it, it didn't work.

I would like to know what I do to be able to use my  socket server  to connect with socket client in any corner of the world.

答:
You are using a local ip which allows people connected only to your router connect.
So you need to use your public ip address. (Click Here to check your IP)

Open a port in your router. for example: 1234.

Dont know how? See this video.
Want to learn about it? See this video.

Once you do that, change the port in your code to the port you opened on the router page.

and then change the ip in the client code to your public ip.

Now your friend should be able to connect to your server.

(also you need to have static ip and not dynamic ip)

Body:
I made a socket to see how it works.

Basically my intention for testing was to run commands in client computer cmd

First I made the  server  to receive a connection from my other script client

import socket

HOST = '192.168.100.xx'  #my computer ipv4
PORT = 50000

server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server.bind((HOST,PORT))
server.listen(5)
print('Server waiting connection...')
conn,addr = server.accept()
print('Connection established!')
print('Connected in addr: {}\n'.format(addr))

while True:
    cmd = str(input('command>'))
    conn.send(str.encode(cmd))
    response = str(conn.recv(1024),"utf-8")
    print(response)
    if cmd == 'quit':
        break

server.close()

Then I made the client:

import socket
import subprocess
import os

HOST = '192.168.100.xx' #ipv4 from my computer (server)
PORT = 50000

client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
client.connect((HOST,PORT))
print('Connecting to the server {}'.format(HOST))
while True:
    command = client.recv(1024).decode()

    print('Server command>'+command)
    cmd = subprocess.Popen(args=command,shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
    output = (cmd.stdout.read() + cmd.stderr.read()).decode("utf-8", errors="ignore")
    client.send(str.encode(str(output)+ str(os.getcwd()) +'$'))

Here's how I get my IPv4 address:

Initially when I tested it on a machine on my network this worked fine, but when I sent the client to a friend far away to run it, it didn't work.

I would like to know what I do to be able to use my  socket server  to connect with socket client in any corner of the world.


问:
Show description or comments for variables in FastAPI autodocs (Swagger UI)
I'm making a function and class for it with POST method.

Since I use FastAPI, it automatically generates API docs (using OpenAPI specification and Swagger UI), where I can see the function's description or example data there.

My class and function are like below:

from pydantic import BaseModel, Field
from typing import Optional, List

@app.post("/user/item")
def func1(args1: User, args2: Item):
    ...

class User(BaseModel):
    name: str
    state: List[str]

    class Config:
        schema_extra = {
            "example": {
                "name": "Mike",
                "state": ["Texas", "Arizona"]
            }
        }

    class Item(BaseModel):
        _id: int = Field(..., example=3, description="item id")

```
<p>Through <code>schema_extra</code> and <code>example</code> attribute in <code>Field</code>, I can see the example value in <code>Request body</code> of function description.</p>
<p>It shows like</p>
```{
   "args1": {
        "name": "Mike",
        "state": ["Texas", "Arizona"]     # state user visits. <-- I'd like to add this here or in other place.
    },
    "args2: {
        "_id": 3   <-- Here I can't description 'item id'
    }
}
```

However, I'd like to add description or comments to example value, like # state user visits above.

I've tried to add description attribute of pydantic Field, but I think it shows only for parameters of get method.

Is there any way to do this? Any help will be appreciated.

答:
You are trying to pass "comments" inside the actual JSON payload that will be sent to the server. Thus, such an approach wouldn't work. The way to add description to the fields is as shown below. Users/you can see the descriptions/comments, as well as the examples provided, by expanding the corresponding JSON schema of a Pydantic model (e.g., "User") under "Schemas" (at the bottom of the page) when visting OpenAPI at http://127.0.0.1:8000/docs, for instance. Or, by clicking on "Schema", next to "Example Value", above the example given in the "Request Body".

class User(BaseModel):
    name: str = Field(..., description="Add user name")
    state: List[str]  = Field(..., description="State user visits")

    class Config:
        schema_extra = {
            "example": {
                "name": "Mike",
                "state": ["Texas", "Arizona"]
            }
        }
```
<p>Alternatively, you could use <code>Body</code> field in your endpoint, allowing you to add a description that is shown under the example in the "Request body". As per the documentation:</p>
<blockquote>
<p>But when you use <code>example</code> or <code>examples</code> with any of the other utilities
(<code>Query()</code>, <code>Body()</code>, etc.) those examples are not added to the JSON
Schema that describes that data (not even to OpenAPI's own version of
JSON Schema), they are added directly to the path operation
declaration in OpenAPI (outside the parts of OpenAPI that use JSON
Schema).</p>
</blockquote>
<p>You could add multiple examples (with their associated descriptions), as described in the documentation. Example below:</p>
<pre class="lang-python prettyprint-override"><code>@app.post("/user/item")
async def update_item(
    user: User = Body(
        ...,
        examples={
            "normal": {
                "summary": "A normal example",
                "description": "**name**: Add user name.  **state**: State user vistis. ",
                "value": {
                    "name": "Mike",
                    "state": ["Texas", "Arizona"]
                },
            }
        }
    ),
):
    return {"user": user}
</code>```

Body:
I'm making a function and class for it with POST method.

Since I use FastAPI, it automatically generates API docs (using OpenAPI specification and Swagger UI), where I can see the function's description or example data there.

My class and function are like below:

from pydantic import BaseModel, Field
from typing import Optional, List

@app.post("/user/item")
def func1(args1: User, args2: Item):
    ...

class User(BaseModel):
    name: str
    state: List[str]

    class Config:
        schema_extra = {
            "example": {
                "name": "Mike",
                "state": ["Texas", "Arizona"]
            }
        }

    class Item(BaseModel):
        _id: int = Field(..., example=3, description="item id")

Through schema_extra and example attribute in Field, I can see the example value in Request body of function description.

It shows like

{
   "args1": {
        "name": "Mike",
        "state": ["Texas", "Arizona"]     # state user visits. <-- I'd like to add this here or in other place.
    },
    "args2: {
        "_id": 3   <-- Here I can't description 'item id'
    }
}

However, I'd like to add description or comments to example value, like # state user visits above.

I've tried to add description attribute of pydantic Field, but I think it shows only for parameters of get method.

Is there any way to do this? Any help will be appreciated.

Body:
You are trying to pass "comments" inside the actual JSON payload that will be sent to the server. Thus, such an approach wouldn't work. The way to add description to the fields is as shown below. Users/you can see the descriptions/comments, as well as the examples provided, by expanding the corresponding JSON schema of a Pydantic model (e.g., "User") under "Schemas" (at the bottom of the page) when visting OpenAPI at http://127.0.0.1:8000/docs, for instance. Or, by clicking on "Schema", next to "Example Value", above the example given in the "Request Body".

class User(BaseModel):
    name: str = Field(..., description="Add user name")
    state: List[str]  = Field(..., description="State user visits")

    class Config:
        schema_extra = {
            "example": {
                "name": "Mike",
                "state": ["Texas", "Arizona"]
            }
        }

Alternatively, you could use Body field in your endpoint, allowing you to add a description that is shown under the example in the "Request body". As per the documentation:

But when you use example or examples with any of the other utilities
(Query(), Body(), etc.) those examples are not added to the JSON
Schema that describes that data (not even to OpenAPI's own version of
JSON Schema), they are added directly to the path operation
declaration in OpenAPI (outside the parts of OpenAPI that use JSON
Schema).

You could add multiple examples (with their associated descriptions), as described in the documentation. Example below:

@app.post("/user/item")
async def update_item(
    user: User = Body(
        ...,
        examples={
            "normal": {
                "summary": "A normal example",
                "description": "**name**: Add user name.  **state**: State user vistis. ",
                "value": {
                    "name": "Mike",
                    "state": ["Texas", "Arizona"]
                },
            }
        }
    ),
):
    return {"user": user}


问:
Hibernate: My folder structure is correct but when running app it still cant locate hibernate.config.xml file on resources folder
I am working with Maven, on Netbeans, on Windows

I have my full configured hibernate.cfg.xml file on
"/src/main/resources/hibernate.cfg.xml"

I have triple checked this is a fact.
This is my folder  structure on Netbeans (picture)

When running I get this:

```<code>Exception in thread "main" org.hibernate.internal.util.config.ConfigurationException:
Could not locate cfg.xml resource [/resources/hibernate.cfg.xml]
</code>```

This is my hibernate cfg.xml file:

```<code><!-- This file should be referenced in the configure() method!!! -->

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-configuration PUBLIC

"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
  <session-factory>
    <! -- url -->
    <property name="hibernate.connection.url">jdbc:oracle:thin:@toshiba-pc:1521:SYSTEM</property>

    <! -- username -->
    <property name="hibernate.connection.username">system</property>

    <!-- password -->
    <property name="hibernate.connection.password">27111995</property>

    <!-- database driver -->
    <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>

  </session-factory>
</hibernate-configuration>
</code>```

And on my main class the relevant lines are these:

```<code> public static void main(String[] args) {
     Configuration cfg = new Configuration();
     cfg.configure("/resources/hibernate.cfg.xml");
 ...more code...
</code>```

So basically I have been trying to get around this with no success at all. Any help would be extremely appreciated.

答:
Finally solved it!
My solution was to create a new File object using the System.property("user.dir") method and pass it to the Configuration constructor:</p>
```<code>String roothFolder = System.getProperty("user.dir");
File hibernateConfigFile = new File
(roothFolder + "/src/main/resources/hibernate.cfg.xml");
Configuration cfg = new Configuration();
    cfg.configure(hibernateConfigFile);
</code>```

Body:
I am working with Maven, on Netbeans, on Windows

I have my full configured hibernate.cfg.xml file on
"/src/main/resources/hibernate.cfg.xml"

I have triple checked this is a fact.
This is my folder  structure on Netbeans (picture)

When running I get this:

Exception in thread "main" org.hibernate.internal.util.config.ConfigurationException:
Could not locate cfg.xml resource [/resources/hibernate.cfg.xml]

This is my hibernate cfg.xml file:

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-configuration PUBLIC

"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
  <session-factory>
    <! -- url -->
    <property name="hibernate.connection.url">jdbc:oracle:thin:@toshiba-pc:1521:SYSTEM</property>

    <! -- username -->
    <property name="hibernate.connection.username">system</property>

    <property name="hibernate.connection.password">27111995</property>

    <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>

  </session-factory>
</hibernate-configuration>

And on my main class the relevant lines are these:

 public static void main(String[] args) {
     Configuration cfg = new Configuration();
     cfg.configure("/resources/hibernate.cfg.xml");
 ...more code...

So basically I have been trying to get around this with no success at all. Any help would be extremely appreciated.

Body:
Finally solved it!
My solution was to create a new File object using the System.property("user.dir") method and pass it to the Configuration constructor:

String roothFolder = System.getProperty("user.dir");
File hibernateConfigFile = new File
(roothFolder + "/src/main/resources/hibernate.cfg.xml");
Configuration cfg = new Configuration();
    cfg.configure(hibernateConfigFile);


问:
what is the purpose of dbus interface xml file?
I am reading D-Bus API Design Guidelines:

Interface files for public API should be installed to $(datadir)/dbus-1/interfaces so that other services can load them.

OK... in order to understand how these interface files work, I open the file /usr/share/dbus-1/interfaces/org.gnome.Shell.Screenshot.xml (I'm using Ubuntu 20.04)

```<code><node>
  <interface name="org.gnome.Shell.Screenshot">
  ...
    <method name="PickColor">
      <arg type="a{sv}" direction="out" name="result"/>
    </method>
</code>```

Well, I see the interface name, I see the method name, but that is not enough. If I want to call this method using dbus-send

```<code>$ dbus-send --print-reply --dest=<service.name> </path/to/object> org.gnome.Shell.Screenshot.PickColor
</code>```

I need <service.name> and <path/to/object>, which this xml-file does not provide.

The queston is: what is the purpose of this file if it does not provide full information about the service interface? Is it used by dbus-daemon or by any other programs? Are such files really needed for something? Should I make a conclusion that an xml-file, which does not provide a path to object in , is incomplete? Should such file also mention a service known name (org.gnome.Shell.Screenshot in this case)?

答:
The org.freedesktop.DBus.Introspectable interface has one method:

```<code>      org.freedesktop.DBus.Introspectable.Introspect (out STRING xml_data)

</code>```

Object instances may implement Introspect which returns an XML description of the object. The introspection format is documented at:
https://dbus.freedesktop.org/doc/dbus-specification.html#introspection-format

Using busctl on the command line I can use list to get all the services, tree to get all the objects, and then intropspect to find the API. Using these three commands I can discover the D-Bus services on a system

```<code>$ busctl list
$ busctl tree <service>
$ busctl introspect <service> <object>
</code>```

The service you mentioned in your question is on the Session/User bus so it would be:

$ busctl --user list | grep Screenshot
NAME                                          PID PROCESS         USER       CONNECTION    UNIT              SESSION DESCRIPTION
---------------------------------------------------------------------------------------------------------------------------------
org.gnome.Screenshot                            - -               -          (activatable) -                 -       -
org.gnome.Shell.Screenshot                   1259 gnome-shell     LinuxMachine1 :1.37         user@1000.service -       -

$ busctl --user tree org.gnome.Shell.Screenshot
├─/StatusNotifierWatcher
└─/org
  ├─/org/freedesktop
  │ ├─/org/freedesktop/Notifications
  │ └─/org/freedesktop/portal
  │   └─/org/freedesktop/portal/desktop
  ├─/org/gnome
  │ ├─/org/gnome/Mutter
  │ │ ├─/org/gnome/Mutter/DisplayConfig
  │ │ └─/org/gnome/Mutter/IdleMonitor
  │ │   └─/org/gnome/Mutter/IdleMonitor/Core
  │ ├─/org/gnome/ScreenSaver
  │ ├─/org/gnome/SessionManager
  │ │ └─/org/gnome/SessionManager/EndSessionDialog
  │ ├─/org/gnome/Shell
  │ │ ├─/org/gnome/Shell/AudioDeviceSelection
  │ │ ├─/org/gnome/Shell/Introspect
  │ │ ├─/org/gnome/Shell/Screencast
  │ │ ├─/org/gnome/Shell/Screenshot
  │ │ └─/org/gnome/Shell/Wacom
  │ └─/org/gnome/keyring
  │   └─/org/gnome/keyring/Prompter
  └─/org/gtk
    ├─/org/gtk/MountOperationHandler
    └─/org/gtk/Notifications

$ busctl --user introspect org.gnome.Shell.Screenshot /org/gnome/Shell/Screenshot
NAME                                TYPE      SIGNATURE RESULT/VALUE FLAGS
org.freedesktop.DBus.Introspectable interface -         -            -
.Introspect                         method    -         s            -
org.freedesktop.DBus.Peer           interface -         -            -
.GetMachineId                       method    -         s            -
.Ping                               method    -         -            -
org.freedesktop.DBus.Properties     interface -         -            -
.Get                                method    ss        v            -
.GetAll                             method    s         a{sv}        -
.Set                                method    ssv       -            -
.PropertiesChanged                  signal    sa{sv}as  -            -
org.gnome.Shell.Screenshot          interface -         -            -
.FlashArea                          method    iiii      -            -
.PickColor                          method    -         a{sv}        -
.Screenshot                         method    bbs       bs           -
.ScreenshotArea                     method    iiiibs    bs           -
.ScreenshotWindow                   method    bbbs      bs           -
.SelectArea                         method    -         iiii         -
```
<p>And for completeness, running the same command as you did:</p>
```$ busctl --user call org.gnome.Shell.Screenshot /org/gnome/Shell/Screenshot org.gnome.Shell.Screenshot PickColor
a{sv} 1 "color" (ddd) 1 1 1
```

Body:
I am reading D-Bus API Design Guidelines:

Interface files for public API should be installed to $(datadir)/dbus-1/interfaces so that other services can load them.

OK... in order to understand how these interface files work, I open the file /usr/share/dbus-1/interfaces/org.gnome.Shell.Screenshot.xml (I'm using Ubuntu 20.04)

<node>
  <interface name="org.gnome.Shell.Screenshot">
  ...
    <method name="PickColor">
      <arg type="a{sv}" direction="out" name="result"/>
    </method>

Well, I see the interface name, I see the method name, but that is not enough. If I want to call this method using dbus-send

$ dbus-send --print-reply --dest=<service.name> </path/to/object> org.gnome.Shell.Screenshot.PickColor

I need <service.name> and <path/to/object>, which this xml-file does not provide.

The queston is: what is the purpose of this file if it does not provide full information about the service interface? Is it used by dbus-daemon or by any other programs? Are such files really needed for something? Should I make a conclusion that an xml-file, which does not provide a path to object in , is incomplete? Should such file also mention a service known name (org.gnome.Shell.Screenshot in this case)?

Body:
The org.freedesktop.DBus.Introspectable interface has one method:

      org.freedesktop.DBus.Introspectable.Introspect (out STRING xml_data)

Object instances may implement Introspect which returns an XML description of the object. The introspection format is documented at:
https://dbus.freedesktop.org/doc/dbus-specification.html#introspection-format

Using busctl on the command line I can use list to get all the services, tree to get all the objects, and then intropspect to find the API. Using these three commands I can discover the D-Bus services on a system

$ busctl list
$ busctl tree <service>
$ busctl introspect <service> <object>

The service you mentioned in your question is on the Session/User bus so it would be:

$ busctl --user list | grep Screenshot
NAME                                          PID PROCESS         USER       CONNECTION    UNIT              SESSION DESCRIPTION
---------------------------------------------------------------------------------------------------------------------------------
org.gnome.Screenshot                            - -               -          (activatable) -                 -       -
org.gnome.Shell.Screenshot                   1259 gnome-shell     LinuxMachine1 :1.37         user@1000.service -       -

$ busctl --user tree org.gnome.Shell.Screenshot
├─/StatusNotifierWatcher
└─/org
  ├─/org/freedesktop
  │ ├─/org/freedesktop/Notifications
  │ └─/org/freedesktop/portal
  │   └─/org/freedesktop/portal/desktop
  ├─/org/gnome
  │ ├─/org/gnome/Mutter
  │ │ ├─/org/gnome/Mutter/DisplayConfig
  │ │ └─/org/gnome/Mutter/IdleMonitor
  │ │   └─/org/gnome/Mutter/IdleMonitor/Core
  │ ├─/org/gnome/ScreenSaver
  │ ├─/org/gnome/SessionManager
  │ │ └─/org/gnome/SessionManager/EndSessionDialog
  │ ├─/org/gnome/Shell
  │ │ ├─/org/gnome/Shell/AudioDeviceSelection
  │ │ ├─/org/gnome/Shell/Introspect
  │ │ ├─/org/gnome/Shell/Screencast
  │ │ ├─/org/gnome/Shell/Screenshot
  │ │ └─/org/gnome/Shell/Wacom
  │ └─/org/gnome/keyring
  │   └─/org/gnome/keyring/Prompter
  └─/org/gtk
    ├─/org/gtk/MountOperationHandler
    └─/org/gtk/Notifications

$ busctl --user introspect org.gnome.Shell.Screenshot /org/gnome/Shell/Screenshot
NAME                                TYPE      SIGNATURE RESULT/VALUE FLAGS
org.freedesktop.DBus.Introspectable interface -         -            -
.Introspect                         method    -         s            -
org.freedesktop.DBus.Peer           interface -         -            -
.GetMachineId                       method    -         s            -
.Ping                               method    -         -            -
org.freedesktop.DBus.Properties     interface -         -            -
.Get                                method    ss        v            -
.GetAll                             method    s         a{sv}        -
.Set                                method    ssv       -            -
.PropertiesChanged                  signal    sa{sv}as  -            -
org.gnome.Shell.Screenshot          interface -         -            -
.FlashArea                          method    iiii      -            -
.PickColor                          method    -         a{sv}        -
.Screenshot                         method    bbs       bs           -
.ScreenshotArea                     method    iiiibs    bs           -
.ScreenshotWindow                   method    bbbs      bs           -
.SelectArea                         method    -         iiii         -

And for completeness, running the same command as you did:

$ busctl --user call org.gnome.Shell.Screenshot /org/gnome/Shell/Screenshot org.gnome.Shell.Screenshot PickColor
a{sv} 1 "color" (ddd) 1 1 1


问:
Building an OCX with VS.NET?
What happened to OCX's? Are they no longer possible to create with the latest tools?

I need to create an ActiveX control that I can place in Word, PowerPoint and Excel documents. If I use VS.NET, I can only create a UserControl DLL with COM Interop, but I don't think I can add that using the "More Controls" toolbox of PowerPoint's Developer Tab.

What would you do?

答: Depending on what you need to do, an Add-in may be more appropriate than an OCX, and you can certainly create those with .NET. You should also look at the Visual Studio Tools for Office, not as a direct replacement for an OCX, but only to understand the new capabilities. It may show you new approaches to the problems you're now solving with an OCX.</p>

OwnerDisplayName: Jason

ContentLicense: CC BY-SA 2.5

Title: Building an OCX with VS.NET?

LastEditorDisplayName: warren

OwnerDisplayName: John Saunders


问:
setting NODE_EXTRA_CA_CERTS with dotenv does not work as an export
I feel puzzled by the following behavior. In the very beginning of my main index.js, I am using

require('dotenv').config();
console.log(process.env);  // everything seems in order
```
<p>I know that the rest of my code successfully access all the relevant <code>process.env.${VARS}</code>. However, I get SSL exceptions; exceptions that I can easily solve by</p>
<pre class="lang-sh prettyprint-override"><code>export NODE_EXTRA_CA_CERTS=/some/absolute/path/to/ca.pem
npm start
</code>```

Is there something special about NODE_EXTRA_CA_CERTS that would explained why this specific variable set with require('dotenv').config() does not work while the others work like a charm?

Does it need to be set before running npm? If it does, why is it the case and are there any workaround so I could keep thing simple?

environement:

dotenv 16.0.0

node v16.13.2

答:
neardupe How to properly configure node.js to use Self Signed root certificates? .

Your problem is not in npm. npm start runs your application, typically (but not necessarily) by running node (or whatever spelling on your platform) to run your js code. When you use node to run js, NODE_EXTRA_CA_CERTS is read and saved in the C-code part of node at startup, before beginning to execute js, and subsequent changes in js variables like process.env do not affect it.

The clean way to do this in js is to pass the desired CAlist -- which can consist of the standard list (from tls.rootCertificates) plus any additions (or replacements or deletions) you choose -- in the (relevant) TLS socket creation, or any https request that implicitly creates a TLS socket; or alternatively to use --use-openssl-ca and select an OpenSSL-format store provided by your system (modified if necessary by system means like update-ca-certificates on Debian/Ubuntu) or one you create.

Or when using npm as you do, it should be possible to configure your package.json to set the envvar before running the application in node.

If you can't do either/any of those, especially where you control the toplevel (and startup) but call libraries you can't [safely] change, see the Q I linked above. For https connections that use the default https.globalAgent you can (documentedly) set that per the A. For all connections, you can monkeypatch tls.createSecureContext to use the undocumented context.addCACert as in the Q, which OP confirmed in the A does actually work if using a correct cert.

Body:
I feel puzzled by the following behavior. In the very beginning of my main index.js, I am using

require('dotenv').config();
console.log(process.env);  // everything seems in order

I know that the rest of my code successfully access all the relevant process.env.${VARS}. However, I get SSL exceptions; exceptions that I can easily solve by

export NODE_EXTRA_CA_CERTS=/some/absolute/path/to/ca.pem
npm start

Is there something special about NODE_EXTRA_CA_CERTS that would explained why this specific variable set with require('dotenv').config() does not work while the others work like a charm?

Does it need to be set before running npm? If it does, why is it the case and are there any workaround so I could keep thing simple?

environement:

dotenv 16.0.0

node v16.13.2


问:
yowsup - Send a message to a group
I know this question has been asked before, but it's been about 4-5 years since the latest responses and I think those solutions or even the library itself are not working anymore.

How to send a message to a Whatsapp group using yowsup library?

Assume I have properly installed the library from here in a Raspberry Pi 3b+. I can send a text message to a single phone number using yowsup-cli demos -c config -s xxxxxxx "message", but cant send it to a group using the GJID (failed to fetch keys for xxxx@g.us error).
Can you confirm that this is still possible or do you know a better alternative?

答: Since some days, you cant send messages to groups. An issue on Github is opened. We have to wait.</p>

Title: yowsup - Send a message to a group


问:
Kotlin Gradle plugin
Hello for every one I have some problems in android sudio

[!] Your project requires a newer version of the Kotlin Gradle plugin.
Find the latest version on https://kotlinlang.org/docs/gradle.html#plugin-and-versions, then update D:\flutter-programing\kidsgame\android\build.gradle:
ext.kotlin_version = ''
Exception: Gradle task assembleDebug failed with exit code 1

How can I make it?

enter image description here

答: You can do this change  as shown in below image

Title: Kotlin Gradle plugin