问:
Mockito verify 'arguments are different', while they are identical
I am testing spring RestController. I use several prams to call controller. The call is successful and i got expected response. But Mockito is not able to verify mock call of service. Why?:

```<code>...
    private static final String TRACE_ID = "1";
    private static final String MAPPED_ID = "2";
...

    @Test
    void getLogMessages() throws Exception {
        LogMessageDto dto = easyRandom.nextObject(LogMessageDto.class);
        Integer slice = 0;
        Integer limit = 60;
        Integer serviceLimit = 50;
        Date startFrom = new Date();
        Date startTo = new Date();
        MultiValueMap<String, String > params = new LinkedMultiValueMap<>();
        params.put("traceId", Collections.singletonList(TRACE_ID));
        params.put("mappedId", Collections.singletonList(MAPPED_ID));
        params.put("slice", Collections.singletonList(slice.toString()));
        params.put("limit", Collections.singletonList(limit.toString()));
        params.put("startFrom", Collections.singletonList(startFrom.toString()));
        params.put("startTo", Collections.singletonList(startTo.toString()));
        Mockito.when(logMessageService.getLogMessages(anyString(), anyString(), anyInt(), anyInt(), any(Date.class),
                        any(Date.class)))
                .thenReturn(new PageImpl<>(Collections.singletonList(dto)));
        mockMvc.perform(get("/feed-logs-service/messages")
                        .queryParams(params))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.content[0].content", equalTo(asParsedJson(dto.getContent()))))
                .andExpect(jsonPath("$.content[0].fields", equalTo(asParsedJson(dto.getFields()))));
        verify(logMessageService).getLogMessages(eq(TRACE_ID), eq(MAPPED_ID), eq(slice), eq(serviceLimit), eq(startFrom),
                eq(startTo));
        verifyNoMoreInteractions(logMessageService);
    }
</code>```

the test execution results in:

```<code>Argument(s) are different! Wanted:
service.LogMessageService#0 bean.getLogMessages(
    "1",
    "2",
    0,
    50,
    Sun Feb 06 14:52:13 MSK 2022,
    Sun Feb 06 14:52:13 MSK 2022
);
-> at controller.LogMessageControllerTest.getLogMessages(LogMessageControllerTest.java:97)
Actual invocations have different arguments:
service.LogMessageService#0 bean.getLogMessages(
    "1",
    "2",
    0,
    50,
    Sun Feb 06 14:52:13 MSK 2022,
    Sun Feb 06 14:52:13 MSK 2022
);
</code>```

intellij idea shows additional empty line when i click 'Click to see difference' link, is it the reason?, and how to pass trough? Thanks for any suggestions.

EDIT:
controller method:

```<code>    @GetMapping("/messages")
    public Page<LogMessageDto> getLogMessages(@RequestParam String traceId, @RequestParam String mappedId,
            @RequestParam(required = false) Integer slice,
            @RequestParam(required = false, defaultValue = SIZE_LIMIT) Integer limit,
            @RequestParam(required = false) @DateTimeFormat(pattern = "EEE MMM dd HH:mm:ss ZZZ yyyy") Date startFrom,
            @RequestParam(required = false) @DateTimeFormat(pattern = "EEE MMM dd HH:mm:ss ZZZ yyyy") Date startTo) {
        limit = checkLimit(limit);
        return logMessageService.getLogMessages(traceId, mappedId, slice, limit, startFrom, startTo);
    }
</code>```

答:
From the test:

```<code>Date startFrom = new Date();
</code>```

These values are parsed to a String:

```<code>params.put("startFrom", Collections.singletonList(startFrom.toString()));
</code>```

But when verifying it's not the String representation that's validated:

```<code>verify(logMessageService).getLogMessages(..., eq(startFrom), ...);
</code>```

I could tell you the problem with this. But as an exercise to learn how Date works I suggest you compare the startFrom.getTime() from the variable created in the test, and the call to logMessageService.getLogMessages(...)

Edit to add an explanation of the problem

The Date is represented as a 64 bit integer internally, down to millisecond. That's what's used when the equals-method is called. When the toString method is called it's converted to a human readable format, and by default loses the millisecond bit. When it's converted back to a Date in the controller it's with zeros as the milliseconds. Which is verified against the Date with milliseconds.

Body:
I am testing spring RestController. I use several prams to call controller. The call is successful and i got expected response. But Mockito is not able to verify mock call of service. Why?:

...
    private static final String TRACE_ID = "1";
    private static final String MAPPED_ID = "2";
...

    @Test
    void getLogMessages() throws Exception {
        LogMessageDto dto = easyRandom.nextObject(LogMessageDto.class);
        Integer slice = 0;
        Integer limit = 60;
        Integer serviceLimit = 50;
        Date startFrom = new Date();
        Date startTo = new Date();
        MultiValueMap<String, String > params = new LinkedMultiValueMap<>();
        params.put("traceId", Collections.singletonList(TRACE_ID));
        params.put("mappedId", Collections.singletonList(MAPPED_ID));
        params.put("slice", Collections.singletonList(slice.toString()));
        params.put("limit", Collections.singletonList(limit.toString()));
        params.put("startFrom", Collections.singletonList(startFrom.toString()));
        params.put("startTo", Collections.singletonList(startTo.toString()));
        Mockito.when(logMessageService.getLogMessages(anyString(), anyString(), anyInt(), anyInt(), any(Date.class),
                        any(Date.class)))
                .thenReturn(new PageImpl<>(Collections.singletonList(dto)));
        mockMvc.perform(get("/feed-logs-service/messages")
                        .queryParams(params))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.content[0].content", equalTo(asParsedJson(dto.getContent()))))
                .andExpect(jsonPath("$.content[0].fields", equalTo(asParsedJson(dto.getFields()))));
        verify(logMessageService).getLogMessages(eq(TRACE_ID), eq(MAPPED_ID), eq(slice), eq(serviceLimit), eq(startFrom),
                eq(startTo));
        verifyNoMoreInteractions(logMessageService);
    }

the test execution results in:

Argument(s) are different! Wanted:
service.LogMessageService#0 bean.getLogMessages(
    "1",
    "2",
    0,
    50,
    Sun Feb 06 14:52:13 MSK 2022,
    Sun Feb 06 14:52:13 MSK 2022
);
-> at controller.LogMessageControllerTest.getLogMessages(LogMessageControllerTest.java:97)
Actual invocations have different arguments:
service.LogMessageService#0 bean.getLogMessages(
    "1",
    "2",
    0,
    50,
    Sun Feb 06 14:52:13 MSK 2022,
    Sun Feb 06 14:52:13 MSK 2022
);

intellij idea shows additional empty line when i click 'Click to see difference' link, is it the reason?, and how to pass trough? Thanks for any suggestions.

EDIT:
controller method:

    @GetMapping("/messages")
    public Page<LogMessageDto> getLogMessages(@RequestParam String traceId, @RequestParam String mappedId,
            @RequestParam(required = false) Integer slice,
            @RequestParam(required = false, defaultValue = SIZE_LIMIT) Integer limit,
            @RequestParam(required = false) @DateTimeFormat(pattern = "EEE MMM dd HH:mm:ss ZZZ yyyy") Date startFrom,
            @RequestParam(required = false) @DateTimeFormat(pattern = "EEE MMM dd HH:mm:ss ZZZ yyyy") Date startTo) {
        limit = checkLimit(limit);
        return logMessageService.getLogMessages(traceId, mappedId, slice, limit, startFrom, startTo);
    }

Body:
From the test:

Date startFrom = new Date();

These values are parsed to a String:

params.put("startFrom", Collections.singletonList(startFrom.toString()));

But when verifying it's not the String representation that's validated:

verify(logMessageService).getLogMessages(..., eq(startFrom), ...);

I could tell you the problem with this. But as an exercise to learn how Date works I suggest you compare the startFrom.getTime() from the variable created in the test, and the call to logMessageService.getLogMessages(...)

Edit to add an explanation of the problem

The Date is represented as a 64 bit integer internally, down to millisecond. That's what's used when the equals-method is called. When the toString method is called it's converted to a human readable format, and by default loses the millisecond bit. When it's converted back to a Date in the controller it's with zeros as the milliseconds. Which is verified against the Date with milliseconds.


来源: stackexchange

问:
Vs Code nx console generate command not working : This command has no flags to set
I'm have nx console extension installed in my Vs Code and upon trying to use the generate command (generate component, service, library etc.) its saying "ng generate @schematics/angular:component
This command has no flags to set" . I don't want to write the commands manually since it is time consuming. I have tried uninstalling and reinstalling the extension, closing my VsCode but i still get the same error.

答:
Solved it.. turns out my nx console had just upgraded itself to a newer and less stable version.
To solve this go to your extensions panel on vs code find nx console extension and click on the settings icon at the bottom right.
And select Install another version then choose any lesser version then reload your window

ContentLicense: CC BY-SA 4.0


问:
How to pass argument when extend Robotframework AppiumLibrary to call appium execute_script function
I have create a python file with the following content

```<code>from robot.libraries.BuiltIn import BuiltIn

def scroll_page_to_the_bottom():
    BuiltIn().get_library_instance('AppiumLibrary').execute_script("mobile: scroll", {'direction': 'down'})
</code>```

When I call from robot file with keyword scroll_page_to_the_bottom I got an error TypeError: too many positional arguments

I thought something wrong with my scripts and I try to use other mobile command such as mobile: deviceInfo and it works perfectly
Here is the working execute_script from my code BuiltIn().get_library_instance('AppiumLibrary').execute_script("mobile: deviceInfo")

My question is how to pass command with argument to execute_script?

referring to http://appium.io/docs/en/commands/mobile-command/index.html, I have use the correct format execute_script("mobile: scroll", {'direction': 'down'}) but got an error TypeError: too many positional arguments from robot execution

答:
Your python code is calling the execute_script() method on a AppiumLibrary object, from the robotframework-appiumlibrary package. This method receives only one parameter (script), and you are passing two arguments: 1. the string "mobile: scroll" and 2. the dict {'direction': 'down'}. Hence the TypeError: too many positional arguments exception.

The second example you gave works because you passed the correct number of arguments: the string "mobile: deviceInfo".

The page http://appium.io/docs/en/commands/mobile-command/index.html documents the execute_script() method from the appium-python-client package, and this is a different package. The method you are calling is not there.

Body:
I have create a python file with the following content

from robot.libraries.BuiltIn import BuiltIn

def scroll_page_to_the_bottom():
    BuiltIn().get_library_instance('AppiumLibrary').execute_script("mobile: scroll", {'direction': 'down'})

When I call from robot file with keyword scroll_page_to_the_bottom I got an error TypeError: too many positional arguments

I thought something wrong with my scripts and I try to use other mobile command such as mobile: deviceInfo and it works perfectly
Here is the working execute_script from my code BuiltIn().get_library_instance('AppiumLibrary').execute_script("mobile: deviceInfo")

My question is how to pass command with argument to execute_script?

referring to http://appium.io/docs/en/commands/mobile-command/index.html, I have use the correct format execute_script("mobile: scroll", {'direction': 'down'}) but got an error TypeError: too many positional arguments from robot execution


问:
Bootstrap 5 background color is having opacity
I'm trying to create a OR divider, but in bootstrap 5 its not working correctly which is working properly in bootstrap 4. In my project bootstrap 5 is being used. Background color of text is having some opacity.

HTML:

```<code><div class="or-line-block pt-2">
    <h6 class="text-center m-0"><span class="or-txt px-2">OR</span></h6>
    <hr class="or-line">
</div>
</code>```

CSS:

```<code>.or-txt{
    background-color: white;
}
.or-line{
    margin-top: -10px;
    border-color: rgba(#333, 0.1);
}
</code>```

In Bootstrap 4:

In Bootstrap 5:

What is the issue. Please help

答:
It's because bootstrap has changed the CSS for hr. They've added opacity and some other CSS. Kindly add this to your code

```<code>hr {
    opacity: 1;
}
</code>```

Body:
I'm trying to create a OR divider, but in bootstrap 5 its not working correctly which is working properly in bootstrap 4. In my project bootstrap 5 is being used. Background color of text is having some opacity.

HTML:

OR

CSS:

.or-txt{
    background-color: white;
}
.or-line{
    margin-top: -10px;
    border-color: rgba(#333, 0.1);
}

In Bootstrap 4:

In Bootstrap 5:

What is the issue. Please help

Body:
It's because bootstrap has changed the CSS for hr. They've added opacity and some other CSS. Kindly add this to your code

hr {
    opacity: 1;
}


问:
Flex Create an array of images to insert into a itemRenderer
I am trying to loop through a list of images and then add them to list box with a itemRenderer </p>

```<code>public function createDataProvider():ArrayList
{

    var a:Array = new Array();
    for (var i:int = 0; i < select_query.data.length; i++){
        var x:Image = new Image();
        x.height = 95
        x.width = 126
        x.id = "list_image_" + i
        x.source = (PathToMyImage);

         a[i] = x

    }
    return new ArrayList(a);
}
<s:List id="myListX" width="234" height="550"
        dragEnabled="true" dropEnabled="true" dragMoveEnabled="true"
        dataProvider="{createDataProvider()}">
    <s:layout>
    <s:TileLayout id="myListX_tiles"
                  requestedRowCount="1"
                  horizontalGap="0"
                  verticalGap="0" horizontalAlign="center" verticalAlign="middle" />
    </s:layout>
        <s:itemRenderer>

        </s:itemRenderer>
</s:List>
</code>```

答:
Here you go:  </p>

```<code>public function createDataProvider():ArrayList
{

    var a:Array = new Array();
    for (var i:int = 0; i < select_query.data.length; i++){
         a[i] =  (PathToMyImage);
    }
    return new ArrayList(a);
}

<s:List id="myListX" width="234" height="550"
        dragEnabled="true" dropEnabled="true" dragMoveEnabled="true"
        dataProvider="{createDataProvider()}">
    <s:layout>
    <s:TileLayout id="myListX_tiles"
                  requestedRowCount="1"
                  horizontalGap="0"
                  verticalGap="0" horizontalAlign="center" verticalAlign="middle" />
    </s:layout>
    <s:itemRenderer>
        <fx:Component>
            <s:DataRenderer>
                <s:Image source="{data}" height="95" width="126" />
            </s:DataRenderer>
        </fx:Component>
    </s:itemRenderer>

</s:List>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to loop through a list of images and then add them to list box with a itemRenderer

public function createDataProvider():ArrayList
{

    var a:Array = new Array();
    for (var i:int = 0; i < select_query.data.length; i++){
        var x:Image = new Image();
        x.height = 95
        x.width = 126
        x.id = "list_image_" + i
        x.source = (PathToMyImage);

         a[i] = x

    }
    return new ArrayList(a);
}
<s:List id="myListX" width="234" height="550"
        dragEnabled="true" dropEnabled="true" dragMoveEnabled="true"
        dataProvider="{createDataProvider()}">
    <s:layout>
    <s:TileLayout id="myListX_tiles"
                  requestedRowCount="1"
                  horizontalGap="0"
                  verticalGap="0" horizontalAlign="center" verticalAlign="middle" />
    </s:layout>
        <s:itemRenderer>

        </s:itemRenderer>
</s:List>

Body:
Here you go:

public function createDataProvider():ArrayList
{

    var a:Array = new Array();
    for (var i:int = 0; i < select_query.data.length; i++){
         a[i] =  (PathToMyImage);
    }
    return new ArrayList(a);
}

<s:List id="myListX" width="234" height="550"
        dragEnabled="true" dropEnabled="true" dragMoveEnabled="true"
        dataProvider="{createDataProvider()}">
    <s:layout>
    <s:TileLayout id="myListX_tiles"
                  requestedRowCount="1"
                  horizontalGap="0"
                  verticalGap="0" horizontalAlign="center" verticalAlign="middle" />
    </s:layout>
    <s:itemRenderer>
        <fx:Component>
            <s:DataRenderer>
                <s:Image source="{data}" height="95" width="126" />
            </s:DataRenderer>
        </fx:Component>
    </s:itemRenderer>

</s:List>


问:
Flutter change checkbox tick icon size
Is it possible to change the tick size of checkbox ? i tried wrapping the CheckBox with Transform.scale with scale: 2.0 but it makes the whole CheckBox button bigger.

答: Maybe you will try asset image instead of icon for check box.</p>

Title: Flutter change checkbox tick icon size


问:
How to store a Complex Nested JSON in Redis using Python
As i am new to redis, i need some guidance on how we can store the below complex json in REDIS so that we can access the Elements of the JSON from REDIS -

```<code>"Reservations": [
        {
            "Instances": [
                {
                    "Monitoring": {
                        "State": "disabled"
                    },
                    "PublicDnsName": "",
                    "State": {
                        "Code": 16,
                        "Name": "running"
                    },
                    "EbsOptimized": "false",
                    "LaunchTime": "xxxxxxxxx",
                    "PrivateIpAddress": "x.x.x.x",
                    "ProductCodes": [],
                    "VpcId": "xxxxx",
                    "StateTransitionReason": "",
                    "InstanceId": "i-xxxxxxx",
                    "EnaSupport": "true",
                    "ImageId": "ami-xxxxx",
                    "PrivateDnsName": "ip-xxxxxx.ec2.internal",
                    "KeyName": "xxxxxxv",
                    "SecurityGroups": [
                        {
                            "GroupName": "xxx",
                            "GroupId": "sg-xxxx"
                        },
                        {
                            "GroupName": "xxxxxx",
                            "GroupId": "sg-xxxxx"
                        },
                        {
                            "GroupName": "xxxxx",
                            "GroupId": "sg-xxxxxx"
                        },
                        {
                            "GroupName": "xxxxx",
                            "GroupId": "sg-xxxxxx"
                        }
                    ],
                    "ClientToken": "xxxxx",
                    "SubnetId": "subnet-xxxxx",
                    "InstanceType": "t2.micro",
                    "NetworkInterfaces": [
                        {
                            "Status": "in-use",
                            "MacAddress": "xxxxxxxx",
                            "SourceDestCheck": "true",
                            "VpcId": "vpc-xxxxx",
                            "Description": "",
                            "NetworkInterfaceId": "eni-xxxxx",
                            "PrivateIpAddresses": [
                                {
                                    "PrivateDnsName": "ip-xx-ec2.internal",
                                    "Primary": "true",
                                    "PrivateIpAddress": "xxxxx"
                                }
                            ],
                            "PrivateDnsName": "ip-xxxx-xx.ec2.internal",
                            "Attachment": {
                                "Status": "attached",
                                "DeviceIndex": 0,
                                "DeleteOnTermination": "true",
                                "AttachmentId": "eni-attach-xxxxx",
                                "AttachTime": "2017-0xxxxx"
                            },
                            "Groups": [
                                {
                                    "GroupName": "xx",
                                    "GroupId": "sg-xxxx"
                                },
                                {
                                    "GroupName": "xxxx",
                                    "GroupId": "sg-xxx"
                                },
                                {
                                    "GroupName": "xxxx",
                                    "GroupId": "sg-xxx"
                                },
                                {
                                    "GroupName": "xxxx",
                                    "GroupId": "sg-xxxx"
                                }
                            ],
                            "Ipv6Addresses": [],
                            "OwnerId": "xxx",
                            "SubnetId": "subnet-xxxx",
                            "PrivateIpAddress": "1xxxx"
                        }
                    ],
                    "SourceDestCheck": "true",
                    "Placement": {
                        "Tenancy": "default",
                        "GroupName": "",
                        "AvailabilityZone": "us-xxxxxxx"
                    },
                    "Hypervisor": "xen",
                    "BlockDeviceMappings": [
                        {
                            "DeviceName": "/dev/xxxxxx",
                            "Ebs": {
                                "Status": "attached",
                                "DeleteOnTermination": "true",
                                "VolumeId": "vol-xxxxxx",
                                "AttachTime": "2017-xxxxxxx"
                            }
                        }
                    ],
                    "Architecture": "x86_64",
                    "RootDeviceType": "ebs",
                    "IamInstanceProfile": {
                        "Id": "xxxxxxxx",
                        "Arn": "arn:aws:iam::xxxxxxx"
                    },
                    "RootDeviceName": "/dev/xxxxx",
                    "VirtualizationType": "hvm",
                    "Tags": [
                        {
                            "Value": "xxxxxx",
                            "Key": "aws:cloudformation:stack-name"
                        },
                        {
                            "Value": "xxxxxxx",
                            "Key": "aws:cloudformation:logical-id"
                        },
                        {
                            "Value": "arn:aws:cloudformation:xxxxxx",
                            "Key": "aws:cloudformation:stack-id"
                        }
                    ],
                    "AmiLaunchIndex": 0
                }
            ],
            "ReservationId": "r-xxxxx",
            "RequesterId": "xxxxx",
            "Groups": [],
            "OwnerId": "xxxxxx"
        }
    ]
}
</code>```

I need to store this in such a way that i query the IP/Hostname/InstanceID to get all the elements that are present in the JSON.

I need some guidance on the above.

答:
I used this method to save data in JSON format in Radis and it worked on my project properly,

Note That I have defined an expiration time for data storage

import redis
import json

rs = redis.Redis(host="127.0.0.1", port=6379, decode_responses=True)

def set_json(data, expire_time):
   for key in data.keys():
       if rs.set(key, str(data[key]), expire_time) is False:
           return False
       return True

def get_json(topic):
    value = rs.mget(topic)
    if value is not None:
        return json.loads(json.dumps(value[0]))
    return False

data = {
        "topic":
        {
            "key0":"value",
            "key1":
            [
                {"key3":1}
            ]
        }
    }

set_json(data, 50)

topic = get_json("topic")
print(topic)

```
<p>Output :</p>
<pre class="lang-sh prettyprint-override"><code>>> {'key0': 'value', 'key1': [{'key3': 1}]}
</code>```

Body:
As i am new to redis, i need some guidance on how we can store the below complex json in REDIS so that we can access the Elements of the JSON from REDIS -

"Reservations": [
        {
            "Instances": [
                {
                    "Monitoring": {
                        "State": "disabled"
                    },
                    "PublicDnsName": "",
                    "State": {
                        "Code": 16,
                        "Name": "running"
                    },
                    "EbsOptimized": "false",
                    "LaunchTime": "xxxxxxxxx",
                    "PrivateIpAddress": "x.x.x.x",
                    "ProductCodes": [],
                    "VpcId": "xxxxx",
                    "StateTransitionReason": "",
                    "InstanceId": "i-xxxxxxx",
                    "EnaSupport": "true",
                    "ImageId": "ami-xxxxx",
                    "PrivateDnsName": "ip-xxxxxx.ec2.internal",
                    "KeyName": "xxxxxxv",
                    "SecurityGroups": [
                        {
                            "GroupName": "xxx",
                            "GroupId": "sg-xxxx"
                        },
                        {
                            "GroupName": "xxxxxx",
                            "GroupId": "sg-xxxxx"
                        },
                        {
                            "GroupName": "xxxxx",
                            "GroupId": "sg-xxxxxx"
                        },
                        {
                            "GroupName": "xxxxx",
                            "GroupId": "sg-xxxxxx"
                        }
                    ],
                    "ClientToken": "xxxxx",
                    "SubnetId": "subnet-xxxxx",
                    "InstanceType": "t2.micro",
                    "NetworkInterfaces": [
                        {
                            "Status": "in-use",
                            "MacAddress": "xxxxxxxx",
                            "SourceDestCheck": "true",
                            "VpcId": "vpc-xxxxx",
                            "Description": "",
                            "NetworkInterfaceId": "eni-xxxxx",
                            "PrivateIpAddresses": [
                                {
                                    "PrivateDnsName": "ip-xx-ec2.internal",
                                    "Primary": "true",
                                    "PrivateIpAddress": "xxxxx"
                                }
                            ],
                            "PrivateDnsName": "ip-xxxx-xx.ec2.internal",
                            "Attachment": {
                                "Status": "attached",
                                "DeviceIndex": 0,
                                "DeleteOnTermination": "true",
                                "AttachmentId": "eni-attach-xxxxx",
                                "AttachTime": "2017-0xxxxx"
                            },
                            "Groups": [
                                {
                                    "GroupName": "xx",
                                    "GroupId": "sg-xxxx"
                                },
                                {
                                    "GroupName": "xxxx",
                                    "GroupId": "sg-xxx"
                                },
                                {
                                    "GroupName": "xxxx",
                                    "GroupId": "sg-xxx"
                                },
                                {
                                    "GroupName": "xxxx",
                                    "GroupId": "sg-xxxx"
                                }
                            ],
                            "Ipv6Addresses": [],
                            "OwnerId": "xxx",
                            "SubnetId": "subnet-xxxx",
                            "PrivateIpAddress": "1xxxx"
                        }
                    ],
                    "SourceDestCheck": "true",
                    "Placement": {
                        "Tenancy": "default",
                        "GroupName": "",
                        "AvailabilityZone": "us-xxxxxxx"
                    },
                    "Hypervisor": "xen",
                    "BlockDeviceMappings": [
                        {
                            "DeviceName": "/dev/xxxxxx",
                            "Ebs": {
                                "Status": "attached",
                                "DeleteOnTermination": "true",
                                "VolumeId": "vol-xxxxxx",
                                "AttachTime": "2017-xxxxxxx"
                            }
                        }
                    ],
                    "Architecture": "x86_64",
                    "RootDeviceType": "ebs",
                    "IamInstanceProfile": {
                        "Id": "xxxxxxxx",
                        "Arn": "arn:aws:iam::xxxxxxx"
                    },
                    "RootDeviceName": "/dev/xxxxx",
                    "VirtualizationType": "hvm",
                    "Tags": [
                        {
                            "Value": "xxxxxx",
                            "Key": "aws:cloudformation:stack-name"
                        },
                        {
                            "Value": "xxxxxxx",
                            "Key": "aws:cloudformation:logical-id"
                        },
                        {
                            "Value": "arn:aws:cloudformation:xxxxxx",
                            "Key": "aws:cloudformation:stack-id"
                        }
                    ],
                    "AmiLaunchIndex": 0
                }
            ],
            "ReservationId": "r-xxxxx",
            "RequesterId": "xxxxx",
            "Groups": [],
            "OwnerId": "xxxxxx"
        }
    ]
}

I need to store this in such a way that i query the IP/Hostname/InstanceID to get all the elements that are present in the JSON.

I need some guidance on the above.

Body:
I used this method to save data in JSON format in Radis and it worked on my project properly,

Note That I have defined an expiration time for data storage

import redis
import json

rs = redis.Redis(host="127.0.0.1", port=6379, decode_responses=True)

def set_json(data, expire_time):
   for key in data.keys():
       if rs.set(key, str(data[key]), expire_time) is False:
           return False
       return True

def get_json(topic):
    value = rs.mget(topic)
    if value is not None:
        return json.loads(json.dumps(value[0]))
    return False

data = {
        "topic":
        {
            "key0":"value",
            "key1":
            [
                {"key3":1}
            ]
        }
    }

set_json(data, 50)

topic = get_json("topic")
print(topic)

Output :

>> {'key0': 'value', 'key1': [{'key3': 1}]}


问:
react-router routes not giving the desired output when rendered not showing anything on the webpage
I am a beginner in react and i am using routes for basic routing of components on my homepage
This is the code on my homepage component but still it shows nothing on my webpage when I run the server

```<code>import React,{ Component } from "react";
import RoomJoinPage from "./RoomJoinPage";
import CreateRoomPage from "./CreateRoomPage";
import { BrowserRouter as Router, Switch, Route, Link, Redirect, Routes } from "react-router-dom";

export default class HomePage extends Component {
    constructor(props) {
      super(props);
    }

    render() {
      return (
        <div>
          <Router>
              <Routes>
                <Route exact path='/' element={ <HomePage/> }><h1>This is the home page</h1></Route>
                <Route exact path='/join' element={ <RoomJoinPage/> }></Route>
                <Route exact path='/create' element={ <CreateRoomPage/> } ></Route>
              </Routes>
          </Router>
        </div>
        );
    }
}
</code>```

I have used webpack configurations to create the app as I am using react and Django. When I searched for solution on stack somebody commented on a post as if you are using webpack configurations for manually setting up the project it requires devServer : {historyApiFallback: true,} for react routes to work so what should I do please help me I've been stuck on this part from last two days If the above solution is right then please let me know where to write that following statement to make the react routes work...

答:
I see you are using Browser Router as Router. One thing I would try is to use BrowserRouter without using as Router, just like this <BrowserRouter> </BrowserRouter>.
Another thing that I would try is to use HashRouter instead of BrowserRouter, and use it in the file index.js like this:

```<code> ReactDOM.render(
  <React.StrictMode>
    <HashRouter>
            <App />
    </HashRouter>
  </React.StrictMode>,
  document.getElementById('root')
);
</code>```

And your HomePage file should look like this:

```<code>import React,{ Component } from "react";
import RoomJoinPage from "./RoomJoinPage";
import CreateRoomPage from "./CreateRoomPage";
import { Switch, Route, Link, Redirect, Routes } from "react-router-dom";

export default class HomePage extends Component {
    constructor(props) {
      super(props);
    }

    render() {
      return (
        <div>

              <Routes>
                <Route exact path='/' element={ <HomePage/> }><h1>This is the home page</h1></Route>
                <Route exact path='/join' element={ <RoomJoinPage/> }></Route>
                <Route exact path='/create' element={ <CreateRoomPage/> } ></Route>
              </Routes>

        </div>
        );
    }
}
</code>```

If anything of this works, please share the version of react router dom and react if it's possible. Previously I also had problems of this style with RRD.

Body:
I am a beginner in react and i am using routes for basic routing of components on my homepage
This is the code on my homepage component but still it shows nothing on my webpage when I run the server

import React,{ Component } from "react";
import RoomJoinPage from "./RoomJoinPage";
import CreateRoomPage from "./CreateRoomPage";
import { BrowserRouter as Router, Switch, Route, Link, Redirect, Routes } from "react-router-dom";

export default class HomePage extends Component {
    constructor(props) {
      super(props);
    }

    render() {
      return (

          <Router>
              <Routes>
                <Route exact path='/' element={ <HomePage/> }>
This is the home page
</Route>
                <Route exact path='/join' element={ <RoomJoinPage/> }></Route>
                <Route exact path='/create' element={ <CreateRoomPage/> } ></Route>
              </Routes>
          </Router>

        );
    }
}

I have used webpack configurations to create the app as I am using react and Django. When I searched for solution on stack somebody commented on a post as if you are using webpack configurations for manually setting up the project it requires devServer : {historyApiFallback: true,} for react routes to work so what should I do please help me I've been stuck on this part from last two days If the above solution is right then please let me know where to write that following statement to make the react routes work...

Body:
I see you are using Browser Router as Router. One thing I would try is to use BrowserRouter without using as Router, just like this <BrowserRouter> </BrowserRouter>.
Another thing that I would try is to use HashRouter instead of BrowserRouter, and use it in the file index.js like this:

 ReactDOM.render(
  <React.StrictMode>
    <HashRouter>
            <App />
    </HashRouter>
  </React.StrictMode>,
  document.getElementById('root')
);

And your HomePage file should look like this:

import React,{ Component } from "react";
import RoomJoinPage from "./RoomJoinPage";
import CreateRoomPage from "./CreateRoomPage";
import { Switch, Route, Link, Redirect, Routes } from "react-router-dom";

export default class HomePage extends Component {
    constructor(props) {
      super(props);
    }

    render() {
      return (
        <div>

              <Routes>
                <Route exact path='/' element={ <HomePage/> }><h1>This is the home page</h1></Route>
                <Route exact path='/join' element={ <RoomJoinPage/> }></Route>
                <Route exact path='/create' element={ <CreateRoomPage/> } ></Route>
              </Routes>

        </div>
        );
    }
}

If anything of this works, please share the version of react router dom and react if it's possible. Previously I also had problems of this style with RRD.


问:
Access the NA field in the list
We could easily create a NA name/field in the R list.

However it is very hard to access this NA field.

I want to access the NA field name in the list from the loop.

ll = list(1, 2, 4)
# One name is a NA
names(ll) <- c("a", "b", NA)
# or
# ll = list(a = 1, b = 2, `NA` = 4) here "NA" works
# the only way I could access NA field in the list
ll$`NA`

# not works
ll[[NA]]
ll[NA]

# my objective is to be able to subset NA field in the loop like:
# these NOT work
ll[c("a","a", "b", NA)]
lapply(c("a","a", "b", NA), \(x) ll[[x]])
lapply(c("a","a", "b", NA), \(x) ll$x)
```
<p>This some ugly solution from me:</p>
```Map(\(x) if (is.na(x)) ll$`NA` else ll[[x]], names(ll))
```

Title: Access the NA field in the list

Body:
We could easily create a NA name/field in the R list.

However it is very hard to access this NA field.

I want to access the NA field name in the list from the loop.

ll = list(1, 2, 4)
# One name is a NA
names(ll) <- c("a", "b", NA)
# or
# ll = list(a = 1, b = 2, `NA` = 4) here "NA" works
# the only way I could access NA field in the list
ll$`NA`

# not works
ll[[NA]]
ll[NA]

# my objective is to be able to subset NA field in the loop like:
# these NOT work
ll[c("a","a", "b", NA)]
lapply(c("a","a", "b", NA), \(x) ll[[x]])
lapply(c("a","a", "b", NA), \(x) ll$x)

This some ugly solution from me:

Map(\(x) if (is.na(x)) ll$`NA` else ll[[x]], names(ll))

Body:
You can use match on the list's names

lapply(c("a","a", "b", NA), \(x) ll[[match(x, names(ll))]])
#> [[1]]
#> [1] 1
#>
#> [[2]]
#> [1] 1
#>
#> [[3]]
#> [1] 2
#>
#> [[4]]
#> [1] 4


问:
Can't perform a React state update on an unmounted component Error on Firebase onAuthStateChanged
I am trying to route to '/' after the user successfully logs in.

Currently, in my Login.JS file, I have the handleSubmit function that gets the result from the form:

```<code> async function handleSubmit(e) {
        e.preventDefault()

        try {
            setError("")
            setLoading(true)
            await login(emailRef.current.value, passwordRef.current.value)
            history.push("/")
        } catch(error) {
            console.log(error)
            setError("Failed to Log In")
        }
        setLoading(false)
    }
</code>```

Then, I have a AuthContext that passes the Login context

```<code>import React, { useContext, useEffect, useState } from 'react';
import { onAuthStateChanged, getAuth, signInWithEmailAndPassword} from 'firebase/auth';
import app from '../firebase'

const AuthContext = React.createContext()

export function useAuth() {
    return useContext(AuthContext)
}

export function AuthProvider({ children }) {
    const auth = getAuth()
    const [currentUser, setCurrentUser] = useState()
    const [loading, setLoading] = useState(true)

    function login(email, password) {
        return signInWithEmailAndPassword(auth, email, password)
    }

    useEffect(() => {
        const unsubscribe = onAuthStateChanged(auth, (user) => {
            setCurrentUser(user)
            setLoading(false)
        })
        return unsubscribe;
    }, [auth])

    const value = {
        currentUser,
        login
    }
    return (
        <AuthContext.Provider value={value}>
            {!loading && children}
        </AuthContext.Provider>
    )
}
</code>```

I can see that the user is able to LogIn, however, it doesn't render anything in the '/' page and shows this error message in the console:

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

答:
```<code>useEffect(() => {
    const unsubscribe = onAuthStateChanged(auth, (user) => {
        setCurrentUser(user)
        setLoading(false)
    })
    return unsubscribe;
}, [auth])
</code>```

You can not use a return statement rather than a cleanup function in useEffect hook.

Body:
I am trying to route to '/' after the user successfully logs in.

Currently, in my Login.JS file, I have the handleSubmit function that gets the result from the form:

 async function handleSubmit(e) {
        e.preventDefault()

        try {
            setError("")
            setLoading(true)
            await login(emailRef.current.value, passwordRef.current.value)
            history.push("/")
        } catch(error) {
            console.log(error)
            setError("Failed to Log In")
        }
        setLoading(false)
    }

Then, I have a AuthContext that passes the Login context

import React, { useContext, useEffect, useState } from 'react';
import { onAuthStateChanged, getAuth, signInWithEmailAndPassword} from 'firebase/auth';
import app from '../firebase'

const AuthContext = React.createContext()

export function useAuth() {
    return useContext(AuthContext)
}

export function AuthProvider({ children }) {
    const auth = getAuth()
    const [currentUser, setCurrentUser] = useState()
    const [loading, setLoading] = useState(true)

    function login(email, password) {
        return signInWithEmailAndPassword(auth, email, password)
    }

    useEffect(() => {
        const unsubscribe = onAuthStateChanged(auth, (user) => {
            setCurrentUser(user)
            setLoading(false)
        })
        return unsubscribe;
    }, [auth])

    const value = {
        currentUser,
        login
    }
    return (
        <AuthContext.Provider value={value}>
            {!loading && children}
        </AuthContext.Provider>
    )
}

I can see that the user is able to LogIn, however, it doesn't render anything in the '/' page and shows this error message in the console:

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

Body:
useEffect(() => {
    const unsubscribe = onAuthStateChanged(auth, (user) => {
        setCurrentUser(user)
        setLoading(false)
    })
    return unsubscribe;
}, [auth])

You can not use a return statement rather than a cleanup function in useEffect hook.


问:
background color of angular-fontawesome icons not scalling
Im using angular-fontawesome
and want to change the background color of an font-awesome fa-icon

```<code> <fa-icon
    class="vue-icon"
    [icon]="faVue"
    ></fa-icon>

</code>```

I changed the color using the class attribute

```<code>.vue-icon {
    padding: 10px;
    background: #62dda4;
}

</code>```

If I use the size attribute to make the icon bigger the bg is only half filled

```<code> <fa-icon
    class="vue-icon"
    [icon]="faVue"
    size="6x"
    ></fa-icon>
</code>```

what causes this behavior ?

so far I could not found a background property from the library

答:
Try giving it a block property to contain it.</p>
```<code>.vue-icon {
  display: inline-block; /* add this line*/
  padding: 10px;
  background: #62dda4;
}
</code>```

Body:
Im using angular-fontawesome
and want to change the background color of an font-awesome fa-icon

 <fa-icon
    class="vue-icon"
    [icon]="faVue"
    ></fa-icon>

I changed the color using the class attribute

.vue-icon {
    padding: 10px;
    background: #62dda4;
}

If I use the size attribute to make the icon bigger the bg is only half filled

 <fa-icon
    class="vue-icon"
    [icon]="faVue"
    size="6x"
    ></fa-icon>

what causes this behavior ?

so far I could not found a background property from the library

Body:
Try giving it a block property to contain it.

.vue-icon {
  display: inline-block; /* add this line*/
  padding: 10px;
  background: #62dda4;
}


问:
How to upload an image from vue js to django rest framework?
I am using django-rest-framework as my backend and I want to upload an Image from the frontend(vuejs2)
note: the backend works perfectly and I can upload the photo using django admin</p>

答:
I assume your backend accept multipart/form-data and using axios

<input type="file" @change="onFileChange" />

export default {
  methods: {
    onFileChange(e) {
      const formData = new FormData();
      formData.append("file", e.target.files[0]);
      axios
        .post("/upload", formData)
        .then(() => {
          console.log("SUCCESS");
        })
        .catch(() => {
          console.log("FAILED");
        });
    },
  },
}
```


问:
Perl advice - Taking in a file and changing contents
I have a request for some advice on how to approach this script I want to write in Perl. Basically I have a file that looks like :

```<code>  id: 1
  Relationship: ""
  name: shelby
  pet: 1
  color:4
</code>```

There are certain keywords such as pet and color that have numbers after then. I want to be able to take in a file and look for these keywords (there are 5 or 6 of them) and then change the number to the word that number corresponds to. That is to say for the keyword "Pet"---> 0 =dog, 1 = cat, 2=fish. And for the keyword "color" 0 = red, 1=blue,2=purple,3=brown,4=white. The script should find and change these numbers. The goal should be an output file that looks like:

```<code>      id: 1
      Relationship: ""
      name: shelby
      pet: cat
      color:white
</code>```

I've been struggling with how to do this for a while. I looked up online maybe I could do an array of hashes or something but I'm relatively new to Perl and don't know exactly how to even approach this problem.... Any advice would be much appreciated!

Thanks

答:
This should do it</p>

```<code>use strict;

my $inputFileName = 'E:\test.txt';
my $outputFileName = 'E:\test2.txt';

my %Colors = ( 1 => 'Red' , 2 => 'Green' , 4 => 'Blue' );
my %Pets = ( 1 => 'Dog' , 2 => 'Cat' );

open( IN , "<" , $inputFileName) or die "$inputFileName could not be opened $!";
open( OUT, ">" , $outputFileName) or die "$outputFileName could not be opened $!";

while(<IN>)
{
    my $line = $_;
    if (/^(\s*pet\s*:\s*)(\d+)/ )
    {
        $line = $1. $Pets{$2} . "\n";
    }
    elsif (/\s*^color\s*:\s*(\d+)/ )
    {
       $line = $1. $Colors{$2} . "\n";
    }

    print OUT $line;
}
close(IN);
close(OUT);
</code>```

Body:
I have a request for some advice on how to approach this script I want to write in Perl. Basically I have a file that looks like :

  id: 1
  Relationship: ""
  name: shelby
  pet: 1
  color:4

There are certain keywords such as pet and color that have numbers after then. I want to be able to take in a file and look for these keywords (there are 5 or 6 of them) and then change the number to the word that number corresponds to. That is to say for the keyword "Pet"---> 0 =dog, 1 = cat, 2=fish. And for the keyword "color" 0 = red, 1=blue,2=purple,3=brown,4=white. The script should find and change these numbers. The goal should be an output file that looks like:

      id: 1
      Relationship: ""
      name: shelby
      pet: cat
      color:white

I've been struggling with how to do this for a while. I looked up online maybe I could do an array of hashes or something but I'm relatively new to Perl and don't know exactly how to even approach this problem.... Any advice would be much appreciated!

Thanks

Body:
This should do it

use strict;

my $inputFileName = 'E:\test.txt';
my $outputFileName = 'E:\test2.txt';

my %Colors = ( 1 => 'Red' , 2 => 'Green' , 4 => 'Blue' );
my %Pets = ( 1 => 'Dog' , 2 => 'Cat' );

open( IN , "<" , $inputFileName) or die "$inputFileName could not be opened $!";
open( OUT, ">" , $outputFileName) or die "$outputFileName could not be opened $!";

while(<IN>)
{
    my $line = $_;
    if (/^(\s*pet\s*:\s*)(\d+)/ )
    {
        $line = $1. $Pets{$2} . "\n";
    }
    elsif (/\s*^color\s*:\s*(\d+)/ )
    {
       $line = $1. $Colors{$2} . "\n";
    }

    print OUT $line;
}
close(IN);
close(OUT);


问:
Could not initialize class org.apache.maven.plugin.war.util.WebappStructureSerializer -Maven Configuration Problem Any solution?
When I am creating a Maven project I am getting this error in pom.xml

Could not initialize class
org.apache.maven.plugin.war.util.WebappStructureSerializer

-Maven Configuration Problem

web.xml is missing and <failOnMissingWebXml> is set to true.

答:
Try to add the plugin to your maven project, by adding this in your pom.xml

```<code><plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-war-plugin</artifactId>
    <version>3.3.1</version>
</plugin>
</code>```

After that: Right click -> Maven -> Update Project

Body:
Try to add the plugin to your maven project, by adding this in your pom.xml

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-war-plugin</artifactId>
    <version>3.3.1</version>
</plugin>

After that: Right click -> Maven -> Update Project


问:
How to create a Rock Paper Scissors command in discord.py
I'm very new to discord.py and I want to create a Rock, Paper, Scissors command. I got it working, but I want to do it using user input.

I tried using the await bot.wait_for code, but for some reason it doesn't work. I'm not getting any errors, but it just doesn't work and I can't figure out why. Here's my code:

```<code>from discord.ext.commands import Bot
import random

bot = Bot(".")

@bot.command(help="Play with .rps [your choice]")
async def rps(ctx):
    rpsGame = ['rock', 'paper', 'scissors']
    await ctx.send(f"Rock, paper, or scissors? Choose wisely...")

    def check(msg):
        return msg.author == ctx.author and msg.channel == ctx.channel and msg.content.lower() in rpsGame

    user_choice = await bot.wait_for('message', check=check)

    comp_choice = random.choice(rpsGame)
    if user_choice == 'rock':
        if comp_choice == 'rock':
            await ctx.send(f'Well, that was weird. We tied.\nYour choice: {user_choice}\nMy choice: {comp_choice}')
        elif comp_choice == 'paper':
            await ctx.send(f'Nice try, but I won that time!!\nYour choice: {user_choice}\nMy choice: {comp_choice}')
        elif comp_choice == 'scissors':
            await ctx.send(f"Aw, you beat me. It won't happen again!\nYour choice: {user_choice}\nMy choice: {comp_choice}")

    elif user_choice == 'paper':
        if comp_choice == 'rock':
            await ctx.send(f'The pen beats the sword? More like the paper beats the rock!!\nYour choice: {user_choice}\nMy choice: {comp_choice}')
        elif comp_choice == 'paper':
            await ctx.send(f'Oh, wacky. We just tied. I call a rematch!!\nYour choice: {user_choice}\nMy choice: {comp_choice}')
        elif comp_choice == 'scissors':
            await ctx.send(f"Aw man, you actually managed to beat me.\nYour choice: {user_choice}\nMy choice: {comp_choice}")

    elif user_choice == 'scissors':
        if comp_choice == 'rock':
            await ctx.send(f'HAHA!! I JUST CRUSHED YOU!! I rock!!\nYour choice: {user_choice}\nMy choice: {comp_choice}')
        elif comp_choice == 'paper':
            await ctx.send(f'Bruh. >: |\nYour choice: {user_choice}\nMy choice: {comp_choice}')
        elif comp_choice == 'scissors':
            await ctx.send(f"Oh well, we tied.\nYour choice: {user_choice}\nMy choice: {comp_choice}")
</code>```

What can I do to fix it?

答:
```<code>@bot.command()
async def rps(ctx, choice):
    asyncio.sleep(1)
    choices=["rock", "paper", "scissors"]
    comp_choice = random.choice(choices)
    asyncio.sleep(10)
    await ctx.send(f'GGS!, you chose {choice} and i chose {comp_choice} ')
    if choice not in choices:
        await ctx.send("error: please put rock, paper or scissors")
</code>```

Body:
I'm very new to discord.py and I want to create a Rock, Paper, Scissors command. I got it working, but I want to do it using user input.

I tried using the await bot.wait_for code, but for some reason it doesn't work. I'm not getting any errors, but it just doesn't work and I can't figure out why. Here's my code:

from discord.ext.commands import Bot
import random

bot = Bot(".")

@bot.command(help="Play with .rps [your choice]")
async def rps(ctx):
    rpsGame = ['rock', 'paper', 'scissors']
    await ctx.send(f"Rock, paper, or scissors? Choose wisely...")

    def check(msg):
        return msg.author == ctx.author and msg.channel == ctx.channel and msg.content.lower() in rpsGame

    user_choice = await bot.wait_for('message', check=check)

    comp_choice = random.choice(rpsGame)
    if user_choice == 'rock':
        if comp_choice == 'rock':
            await ctx.send(f'Well, that was weird. We tied.\nYour choice: {user_choice}\nMy choice: {comp_choice}')
        elif comp_choice == 'paper':
            await ctx.send(f'Nice try, but I won that time!!\nYour choice: {user_choice}\nMy choice: {comp_choice}')
        elif comp_choice == 'scissors':
            await ctx.send(f"Aw, you beat me. It won't happen again!\nYour choice: {user_choice}\nMy choice: {comp_choice}")

    elif user_choice == 'paper':
        if comp_choice == 'rock':
            await ctx.send(f'The pen beats the sword? More like the paper beats the rock!!\nYour choice: {user_choice}\nMy choice: {comp_choice}')
        elif comp_choice == 'paper':
            await ctx.send(f'Oh, wacky. We just tied. I call a rematch!!\nYour choice: {user_choice}\nMy choice: {comp_choice}')
        elif comp_choice == 'scissors':
            await ctx.send(f"Aw man, you actually managed to beat me.\nYour choice: {user_choice}\nMy choice: {comp_choice}")

    elif user_choice == 'scissors':
        if comp_choice == 'rock':
            await ctx.send(f'HAHA!! I JUST CRUSHED YOU!! I rock!!\nYour choice: {user_choice}\nMy choice: {comp_choice}')
        elif comp_choice == 'paper':
            await ctx.send(f'Bruh. >: |\nYour choice: {user_choice}\nMy choice: {comp_choice}')
        elif comp_choice == 'scissors':
            await ctx.send(f"Oh well, we tied.\nYour choice: {user_choice}\nMy choice: {comp_choice}")

What can I do to fix it?


问:
Postgres aggregate problem
I'm not sure why this won't work:

```<code>SELECT u.id, u.tag, u.unit_type, Count(p.id) AS num_points
FROM ot2.unit u
INNER JOIN ot2.point p on p.unit_id = u.id
GROUP BY u.id
HAVING Count(p.id) > 800;
</code>```

ERROR: column "u.tag" must appear in the GROUP BY clause or be used in an aggregate function
  SQL state: 42803

I have already provided a column for group by.

答:
Just what the error says. u.tag is not in the group by and you aren't telling how to aggregate the different u.tag values to a single one.

More concrete you have 2 options:

Add u.tag in the group by clause (and u.unit_type as well)

use an aggregate function on those 2 fields (min, max, sum, avg, ....)

Title: Postgres aggregate problem

Body:
I'm not sure why this won't work:

SELECT u.id, u.tag, u.unit_type, Count(p.id) AS num_points
FROM ot2.unit u
INNER JOIN ot2.point p on p.unit_id = u.id
GROUP BY u.id
HAVING Count(p.id) > 800;

ERROR: column "u.tag" must appear in the GROUP BY clause or be used in an aggregate function
  SQL state: 42803

I have already provided a column for group by.


问:
Ionic Print without Sidemenu on Desktop
How do I effectively hide the sidemenu for printing only, when printing from desktop? I've tried adding CSS to ion-menu, which seems to work, except some things are still offset by the size of the menu (like headers). I'm sure there are other implications, such as different display resolutions or screen sizes if print is invoked from the browser.

Another thing I'm open to is having a whole new page just for printing, but I'm just trying to keep everything together so that I don't have to maintain two pages for the same thing.

答:
Here are the rules I use for printable pages with Ionic :

@media print {
  ion-header, ion-backdrop, .tabbar, ion-footer, ion-content::part(background) {
    display: none !important;
  }
  ion-nav {
    contain: none;
    overflow: visible;
  }
  ion-split-pane {
    display: block;
  }
  .scroll-content,
  ion-modal,
  ion-modal .modal-wrapper,
  ion-modal .ion-page,
  ion-modal .ion-page > ion-content,
  .ion-page,
  .ion-page > ion-content,
  ion-split-pane,
  ion-tab,
  ion-tabs,
  ion-router-outlet,
  .app-root,
  ion-content::part(scroll),
  body {
    contain: none;
    position: initial;
    height: auto;
    overflow: visible;
  }
  .fixed-content, .scroll-content {
    margin-top: 0 !important;
  }
}
```

It should hide navigation components, and allow scrollable elements to remain fully visible. You can put it into a top-level CSS stylesheet instead of a component, so it applies to all your pages in print mode.
Note that you may encounter "unmatched selector" warnings with ion-content::part, but it will work anyway.

Title: Ionic Print without Sidemenu on Desktop

Body:
Here are the rules I use for printable pages with Ionic :

@media print {
  ion-header, ion-backdrop, .tabbar, ion-footer, ion-content::part(background) {
    display: none !important;
  }
  ion-nav {
    contain: none;
    overflow: visible;
  }
  ion-split-pane {
    display: block;
  }
  .scroll-content,
  ion-modal,
  ion-modal .modal-wrapper,
  ion-modal .ion-page,
  ion-modal .ion-page > ion-content,
  .ion-page,
  .ion-page > ion-content,
  ion-split-pane,
  ion-tab,
  ion-tabs,
  ion-router-outlet,
  .app-root,
  ion-content::part(scroll),
  body {
    contain: none;
    position: initial;
    height: auto;
    overflow: visible;
  }
  .fixed-content, .scroll-content {
    margin-top: 0 !important;
  }
}

It should hide navigation components, and allow scrollable elements to remain fully visible. You can put it into a top-level CSS stylesheet instead of a component, so it applies to all your pages in print mode.
Note that you may encounter "unmatched selector" warnings with ion-content::part, but it will work anyway.


问:
vuejs router - Require is not defined
I am trying to get started with this: https://github.com/vuejs/vue-router

I have cloned the package, and followed the instructions to build:

```<code>npm install
npm run build
</code>```

But I am receiving a "Require is not defined" error on:

```<code>var Vue = require('vue')
var VueRouter = require('../src')
</code>```

in /example/example.js

I have installed node and browserify... Not sure what to do.

答:
*use import

```<code>import Vue from 'vue'
import VueRouter from 'vue-router'
</code>```

Title: vuejs router - Require is not defined

Body:
I am trying to get started with this: https://github.com/vuejs/vue-router

I have cloned the package, and followed the instructions to build:

npm install
npm run build

But I am receiving a "Require is not defined" error on:

var Vue = require('vue')
var VueRouter = require('../src')

in /example/example.js

I have installed node and browserify... Not sure what to do.

Body:
*use import

import Vue from 'vue'
import VueRouter from 'vue-router'


问:
I try to install react native and Build failed
I try to install react native and Build failed. Why?

Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.

Try the new cross-platform PowerShell https://aka.ms/pscore6

PS C:\Users\stefa\Desktop\REACT\better> npx react-native run-android
info Running jetifier to migrate libraries to AndroidX. You can disae it using "--no-jetifier" flag.
Jetifier found 863 file(s) to forward-jetify. Using 12 workers...
info Starting JS server...
info Installing the app...

Task :app:processDebugMainManifest FAILED
11 actionable tasks: 11 executed

FAILURE: Build failed with an exception.

What went wrong:
Execution failed for task ':app:processDebugMainManifest'.

Unable to make field private final java.lang.String java.io.File.ph accessible: module java.base does not "opens java.io" to unnamed mule @49c3ac54

Try:
Run with --stacktrace option to get the stack trace. Run with --infor --debug option to get more log output. Run with --scan to get fullnsights.

Get more help at https://help.gradle.org

BUILD FAILED in 8s

error Failed to install the app. Make sure you have the Android devepment environment set up: https://reactnative.dev/docs/environment-sup.
Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevrverPort=8081

FAILURE: Build failed with an exception.

What went wrong:
Execution failed for task ':app:processDebugMainManifest'.

Unable to make field private final java.lang.String java.io.File.ph accessible: module java.base does not "opens java.io" to unnamed mule @49c3ac54
get more log output. Run with --scan to get full insights.

Get more help at https://help.gradle.org

BUILD FAILED in 8s

```<code>at makeError (C:\Users\stefa\Desktop\REACT\better\node_modules\execa\index.js:174:9)
at C:\Users\stefa\Desktop\REACT\better\node_modules\execa\index.js:278:16
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async runOnAllDevices (C:\Users\stefa\Desktop\REACT\better\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\runOnAllDevices.js:109:5)
at async Command.handleAction (C:\Users\stefa\Desktop\REACT\better\node_modules\@react-native-community\cli\build\index.js:192:9)
</code>```

info Run CLI with --verbose flag for more details.
PS C:\Users\stefa\Desktop\REACT\better>

答:
This is most probably due to the JDK being lower than JDK11.
Try Installing JDK11 by opening your project in Android Studio and then following these steps:

Open Settings and go to the Build, deployment.. option and click on the arrow to reveral Build option, click on the Build Option.

Click on the drop down list next to Gradle JDK: under Gradle projects.

Select Download JDK from the list and select Azul and JDK Version 11.

Click OK and wait for it to download and confirm the updated Java/JDK is selected and press Apply followed by OK.

Body:
I try to install react native and Build failed. Why?

Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.

Try the new cross-platform PowerShell https://aka.ms/pscore6

PS C:\Users\stefa\Desktop\REACT\better> npx react-native run-android
info Running jetifier to migrate libraries to AndroidX. You can disae it using "--no-jetifier" flag.
Jetifier found 863 file(s) to forward-jetify. Using 12 workers...
info Starting JS server...
info Installing the app...

Task :app:processDebugMainManifest FAILED
11 actionable tasks: 11 executed

FAILURE: Build failed with an exception.

What went wrong:
Execution failed for task ':app:processDebugMainManifest'.

Unable to make field private final java.lang.String java.io.File.ph accessible: module java.base does not "opens java.io" to unnamed mule @49c3ac54

Try:
Run with --stacktrace option to get the stack trace. Run with --infor --debug option to get more log output. Run with --scan to get fullnsights.

Get more help at https://help.gradle.org

BUILD FAILED in 8s

error Failed to install the app. Make sure you have the Android devepment environment set up: https://reactnative.dev/docs/environment-sup.
Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevrverPort=8081

FAILURE: Build failed with an exception.

What went wrong:
Execution failed for task ':app:processDebugMainManifest'.

Unable to make field private final java.lang.String java.io.File.ph accessible: module java.base does not "opens java.io" to unnamed mule @49c3ac54
get more log output. Run with --scan to get full insights.

Get more help at https://help.gradle.org

BUILD FAILED in 8s

at makeError (C:\Users\stefa\Desktop\REACT\better\node_modules\execa\index.js:174:9)
at C:\Users\stefa\Desktop\REACT\better\node_modules\execa\index.js:278:16
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async runOnAllDevices (C:\Users\stefa\Desktop\REACT\better\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\runOnAllDevices.js:109:5)
at async Command.handleAction (C:\Users\stefa\Desktop\REACT\better\node_modules\@react-native-community\cli\build\index.js:192:9)

info Run CLI with --verbose flag for more details.
PS C:\Users\stefa\Desktop\REACT\better>


问:
How Do I Create A Database And User In Docker Using A Script?
I'm following the instructions here on how to connect to MS SQL Server using docker.

After running the container you need to connect to do some setup:

```<code>docker exec -it sql1 "bash"
/opt/mssql-tools/bin/sqlcmd -S localhost -U SA -P 'YourStrong!Passw0rd'
</code>```

Create a database

```<code>CREATE DATABASE TestDB
GO
</code>```

Then create a user

```<code>CREATE LOGIN TEST_USER WITH PASSWORD = 'YourStrong!Passw0rd'
GO
QUIT
</code>```

Maybe you want to do a few other things like sp_addrolemember to be owner or other some such.

Is it possible to script these steps or combine it into single command?

e.g. run the docker command with the sqlcmd as a parameter and the required sql in a file as a parameter to that?

I don't want to compose my own container with these changes in.

答:
For those ending up here who just want a "scriptable" solution, something like this should work (for mssql 2017):

```<code>#!/usr/bin/env bash
set -e

CONTAINER_NAME="replace-with-something-meaningfull"
SA_PASSWORD="YourStrong!Passw0rd"
DB_NAME="TestDB"

until docker exec -i ${CONTAINER_NAME} /opt/mssql-tools/bin/sqlcmd -S localhost -U sa -P ${SA_PASSWORD} -d master -Q "CREATE DATABASE ${DB_NAME}" 2>/dev/null
do
  sleep 2
done

until docker exec -i ${CONTAINER_NAME} /opt/mssql-tools/bin/sqlcmd -S localhost -U sa -P ${SA_PASSWORD} -d master -Q "CREATE LOGIN TEST_USER WITH PASSWORD = 'YourStrong!Passw0rd'" 2>/dev/null
do
  sleep 2
done
</code>```

It is by no means perfect but should do the job.

Body:
I'm following the instructions here on how to connect to MS SQL Server using docker.

After running the container you need to connect to do some setup:

docker exec -it sql1 "bash"
/opt/mssql-tools/bin/sqlcmd -S localhost -U SA -P 'YourStrong!Passw0rd'

Create a database

CREATE DATABASE TestDB
GO

Then create a user

CREATE LOGIN TEST_USER WITH PASSWORD = 'YourStrong!Passw0rd'
GO
QUIT

Maybe you want to do a few other things like sp_addrolemember to be owner or other some such.

Is it possible to script these steps or combine it into single command?

e.g. run the docker command with the sqlcmd as a parameter and the required sql in a file as a parameter to that?

I don't want to compose my own container with these changes in.

Body:
For those ending up here who just want a "scriptable" solution, something like this should work (for mssql 2017):

#!/usr/bin/env bash
set -e

CONTAINER_NAME="replace-with-something-meaningfull"
SA_PASSWORD="YourStrong!Passw0rd"
DB_NAME="TestDB"

until docker exec -i ${CONTAINER_NAME} /opt/mssql-tools/bin/sqlcmd -S localhost -U sa -P ${SA_PASSWORD} -d master -Q "CREATE DATABASE ${DB_NAME}" 2>/dev/null
do
  sleep 2
done

until docker exec -i ${CONTAINER_NAME} /opt/mssql-tools/bin/sqlcmd -S localhost -U sa -P ${SA_PASSWORD} -d master -Q "CREATE LOGIN TEST_USER WITH PASSWORD = 'YourStrong!Passw0rd'" 2>/dev/null
do
  sleep 2
done

It is by no means perfect but should do the job.


问:
Button border color xamarin forms not showed
I want to set border color to button in Xamarin Forms but with this code doesn't work:

```<code><Button Text="Test"
        BorderWidth="5"
        BorderRadius="2"
        BorderColor="Red">
</Button>
</code>```

Using this code the border doesn't appear.

I've also tried this but doen't work.

I've tried it in Android 4.4 (Phisical Device) and in Android 6.0
  (Virtual Device) but doesn't work too.

SOLVED FOLLOWING THIS

答:
By default the border width is zero, so setting its color makes no difference. You need to set both of them:</p>
```<code><Button Text="Jenson" BorderColor="Red" BorderWidth="1" />
</code>```

Body:
I want to set border color to button in Xamarin Forms but with this code doesn't work:

<Button Text="Test"
        BorderWidth="5"
        BorderRadius="2"
        BorderColor="Red">
</Button>

Using this code the border doesn't appear.

I've also tried this but doen't work.

I've tried it in Android 4.4 (Phisical Device) and in Android 6.0
  (Virtual Device) but doesn't work too.

SOLVED FOLLOWING THIS

Body:
By default the border width is zero, so setting its color makes no difference. You need to set both of them:

<Button Text="Jenson" BorderColor="Red" BorderWidth="1" />


问:
Removing pages from search engine results
Hey everyone, I'm a bit new to SEO. I built a one page website that initially utilized several pages (but are now removed), and it looks as if Google has indexed those so that they show up as search results. Is there any way to remove those from the search results? Thanks.</p>

答: Make sure that your server/application is sending correct 404 HTTP header on requests of non existing pages and wait.</p>


问:
Print line above specific string from txt file
I have txt file contains data, i want to loop over file and print only line above "City" word.

Ex of txt file:

```<code>NEW FUSTAT TOURS
City
USA
Addres
napolean
Phone Number
************
Email
***************
PACKAGES
Test TOURS
City
UK
Addres
napolean
Phone Number
************
Email
***************
PACKAGES
</code>```

Result Expected:

```<code>NEW FUSTAT TOURS
Test TOURS
</code>```

I tried:

```<code>with open('dd.txt', 'r', encoding="utf-8") as f:
    input_file = f.readlines()
    for i, line in enumerate(input_file):
        if 'City' in line:
            f1 = (input_file[:i])
            f2 = str(f1)
            f3 = (f2.replace("['", ''))
            f4 = (f3.replace("\\n']", ''))
            print(f4)
</code>```

Result:

```<code>NEW FUSTAT TOURS
NEW FUSTAT TOURS\n', 'City\n', 'USA\n', 'Addres\n', 'napolean\n', 'Phone Number\n', '************\n', 'Email\n', '***************\n', 'PACKAGES\n', 'Test TOURS
</code>```

Any kind of help please?

答:
```<code>with open('dd.txt', 'r', encoding="utf-8") as f:
    line = ''
    for next_line in f:
        if next_line.startswith('City'):
            print(line)
        line = next_line.strip()
</code>```

EDIT:

```<code>with open('dd.txt') as f, open('out.txt', 'w') as f_out:
    line = ''
    for next_line in f:
        if next_line.startswith('City'):
            f_out.write(line)
        line = next_line
</code>```

Body:
I have txt file contains data, i want to loop over file and print only line above "City" word.

Ex of txt file:

NEW FUSTAT TOURS
City
USA
Addres
napolean
Phone Number
************
Email
***************
PACKAGES
Test TOURS
City
UK
Addres
napolean
Phone Number
************
Email
***************
PACKAGES

Result Expected:

NEW FUSTAT TOURS
Test TOURS

I tried:

with open('dd.txt', 'r', encoding="utf-8") as f:
    input_file = f.readlines()
    for i, line in enumerate(input_file):
        if 'City' in line:
            f1 = (input_file[:i])
            f2 = str(f1)
            f3 = (f2.replace("['", ''))
            f4 = (f3.replace("\\n']", ''))
            print(f4)

Result:

NEW FUSTAT TOURS
NEW FUSTAT TOURS\n', 'City\n', 'USA\n', 'Addres\n', 'napolean\n', 'Phone Number\n', '************\n', 'Email\n', '***************\n', 'PACKAGES\n', 'Test TOURS

Any kind of help please?

Body:
with open('dd.txt', 'r', encoding="utf-8") as f:
    line = ''
    for next_line in f:
        if next_line.startswith('City'):
            print(line)
        line = next_line.strip()

EDIT:

with open('dd.txt') as f, open('out.txt', 'w') as f_out:
    line = ''
    for next_line in f:
        if next_line.startswith('City'):
            f_out.write(line)
        line = next_line


答:
It's easy achieved by using regular expressions
So you want to find all lines that have City line right after them. So regex will be

```<code>".+\nCity"
</code>```

And a code to find all matched (supposing text is placed in input.txt) is

```<code>import re

with open("input.txt", 'r') as f:
    text = f.read()

for matched in re.findall(".+\nCity", text):
    print(matched[:-5])
</code>```

P.S.

You are striping \nCity part in matched[:-5] slice

Title: Print line above specific string from txt file

Body:
It's easy achieved by using regular expressions
So you want to find all lines that have City line right after them. So regex will be

".+\nCity"

And a code to find all matched (supposing text is placed in input.txt) is

import re

with open("input.txt", 'r') as f:
    text = f.read()

for matched in re.findall(".+\nCity", text):
    print(matched[:-5])

P.S.

You are striping \nCity part in matched[:-5] slice


问:
Flutter- Conditional Statement-Buttons appear/disappear based on conditions set
in the code below, the codes are correct, but there is problem in connected

when status!='connected!'- Connect Button appear- once connected - button disappears since status=='connected' as set in the code.

However, when status=='connected' actually, Disconnect button should appear. In  my case , it is not appearing.Please see the  code below, I commented out where I feel is the problem.

Like

main.dart

```<code>import 'package:flutter/material.dart';
import 'package:get/get.dart';
import './blecontroller.dart';

void main() {
  runApp(MyApp());}

class MyApp extends StatelessWidget {
@override Widget build(BuildContext context) {
return GetMaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,),
home: MyHomePage());}}

class MyHomePage extends StatelessWidget {
TextStyle myStyle = TextStyle(fontSize: 30);
final BleController c = Get.put(BleController());
MyHomePage();
@override Widget build(BuildContext context){
return Scaffold(
appBar: AppBar(title: Text('Thermometer test')),
body: Column(children: <Widget>[

  SizedBox(height:50),

  Obx(() => Text('${c.status}',
    style:myStyle)),

  SizedBox(height:50),

  Obx(() => Text('Temperature: ${c.temperature}',
    style:myStyle)),

  SizedBox(height:50),

  Obx(() => Container(
    child: c.status != 'connected!'
      ? ElevatedButton(onPressed: c.connect,
          child: Text('connect',
            style:myStyle))
      : null)

      ),

      Obx(() => Container( //Button disconnect does not appear when status='connected'
    child: c.status=='connected!'
      ? ElevatedButton(onPressed: c.disconnect,
          child: Text('Disconnect Now',
            style:myStyle))
      : null)),

      ]));}}

</code>```

blecontroller.dart

```<code>import 'dart:async';

import 'package:flutter_reactive_ble/flutter_reactive_ble.dart';
import 'package:get/get.dart';

class BleController {
  final frb = FlutterReactiveBle();
  late StreamSubscription<ConnectionStateUpdate> connection;
  late QualifiedCharacteristic rx;
  RxString status = 'not connected'.obs;
  RxString temperature = ' '.obs;

  void connect() async {
    status.value = 'Please turn on your device...';
    connection = frb.connectToDevice(id: 'F1:02:00:02:36:DB').listen((state) {
      if (state.connectionState == DeviceConnectionState.connected) {
        status.value = 'connected!';

        // get rx
        rx = QualifiedCharacteristic(
            serviceId: Uuid.parse("0000fff0-0000-1000-8000-00805f9b34fb"),
            characteristicId:
                Uuid.parse("0000fff1-0000-1000-8000-00805f9b34fb"),
            deviceId: 'F1:02:00:XX:XX:XX');

        // subscribe to rx
// ignore: unnecessary_statements
        frb.subscribeToCharacteristic(rx).listen((data) {
          print("Hello");
          print(data);
          print(data.elementAt(5));
          print(data.elementAt(6));
          print((data.elementAt(4) * 256 + data.elementAt(5)) / 10);
          double final_temp =
              (data.elementAt(4) * 256 + data.elementAt(5)) / 10;
          String final_temp_value = final_temp.toString();
          temperature.value = final_temp_value;
        });
      } else {
        status.value = 'Connect Your Device!';

      }
    });
  }

  void disconnect() async {
    connection.cancel();
  }
}
</code>```

答:
You should avoid null value in onpressed button. You will try this code</p>
```<code>Obx(
        () => Container(
          child: c.status != 'connected!'
              ? ElevatedButton(
                  onPressed: c.connect,
                  child: Text(
                    'connect',
                    style: myStyle,
                  ),
                )
              : ElevatedButton(
                  onPressed: c.disconnect,
                  child: Text(
                    'Disconnect Now',
                    style: myStyle,
                  ),
                ),
        ),
      ),
</code>```

Body:
in the code below, the codes are correct, but there is problem in connected

when status!='connected!'- Connect Button appear- once connected - button disappears since status=='connected' as set in the code.

However, when status=='connected' actually, Disconnect button should appear. In  my case , it is not appearing.Please see the  code below, I commented out where I feel is the problem.

Like

main.dart

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import './blecontroller.dart';

void main() {
  runApp(MyApp());}

class MyApp extends StatelessWidget {
@override Widget build(BuildContext context) {
return GetMaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,),
home: MyHomePage());}}

class MyHomePage extends StatelessWidget {
TextStyle myStyle = TextStyle(fontSize: 30);
final BleController c = Get.put(BleController());
MyHomePage();
@override Widget build(BuildContext context){
return Scaffold(
appBar: AppBar(title: Text('Thermometer test')),
body: Column(children: <Widget>[

  SizedBox(height:50),

  Obx(() => Text('${c.status}',
    style:myStyle)),

  SizedBox(height:50),

  Obx(() => Text('Temperature: ${c.temperature}',
    style:myStyle)),

  SizedBox(height:50),

  Obx(() => Container(
    child: c.status != 'connected!'
      ? ElevatedButton(onPressed: c.connect,
          child: Text('connect',
            style:myStyle))
      : null)

      ),

      Obx(() => Container( //Button disconnect does not appear when status='connected'
    child: c.status=='connected!'
      ? ElevatedButton(onPressed: c.disconnect,
          child: Text('Disconnect Now',
            style:myStyle))
      : null)),

      ]));}}

blecontroller.dart

import 'dart:async';

import 'package:flutter_reactive_ble/flutter_reactive_ble.dart';
import 'package:get/get.dart';

class BleController {
  final frb = FlutterReactiveBle();
  late StreamSubscription<ConnectionStateUpdate> connection;
  late QualifiedCharacteristic rx;
  RxString status = 'not connected'.obs;
  RxString temperature = ' '.obs;

  void connect() async {
    status.value = 'Please turn on your device...';
    connection = frb.connectToDevice(id: 'F1:02:00:02:36:DB').listen((state) {
      if (state.connectionState == DeviceConnectionState.connected) {
        status.value = 'connected!';

        // get rx
        rx = QualifiedCharacteristic(
            serviceId: Uuid.parse("0000fff0-0000-1000-8000-00805f9b34fb"),
            characteristicId:
                Uuid.parse("0000fff1-0000-1000-8000-00805f9b34fb"),
            deviceId: 'F1:02:00:XX:XX:XX');

        // subscribe to rx
// ignore: unnecessary_statements
        frb.subscribeToCharacteristic(rx).listen((data) {
          print("Hello");
          print(data);
          print(data.elementAt(5));
          print(data.elementAt(6));
          print((data.elementAt(4) * 256 + data.elementAt(5)) / 10);
          double final_temp =
              (data.elementAt(4) * 256 + data.elementAt(5)) / 10;
          String final_temp_value = final_temp.toString();
          temperature.value = final_temp_value;
        });
      } else {
        status.value = 'Connect Your Device!';

      }
    });
  }

  void disconnect() async {
    connection.cancel();
  }
}

Body:
You should avoid null value in onpressed button. You will try this code

Obx(
        () => Container(
          child: c.status != 'connected!'
              ? ElevatedButton(
                  onPressed: c.connect,
                  child: Text(
                    'connect',
                    style: myStyle,
                  ),
                )
              : ElevatedButton(
                  onPressed: c.disconnect,
                  child: Text(
                    'Disconnect Now',
                    style: myStyle,
                  ),
                ),
        ),
      ),


答:
With the line f1 = (input_file[:i]) you get a list of the entire file up to the line in which you find the string "City". If you replace your for-loop with the following, you're done. I'll explain below what the trick is.

for i, line in enumerate(input_file):
    if 'City' in line:
        f1 = input_file[i-1]
        print(f1.strip())
```

What you do in the line with f1 is that you get the "row" previous to the one you find the string "City". In the line thereafter, we print the line with any whitespace "stripped".

Body:
With the line f1 = (input_file[:i]) you get a list of the entire file up to the line in which you find the string "City". If you replace your for-loop with the following, you're done. I'll explain below what the trick is.

for i, line in enumerate(input_file):
    if 'City' in line:
        f1 = input_file[i-1]
        print(f1.strip())

What you do in the line with f1 is that you get the "row" previous to the one you find the string "City". In the line thereafter, we print the line with any whitespace "stripped".


答:
You may use regex to find out what you need. As an example:</p>
```<code>import re
your_match = re.search(r'(.+\R)City', your_text).group(1)
</code>```

Body:
You may use regex to find out what you need. As an example:

import re
your_match = re.search(r'(.+\R)City', your_text).group(1)


问:
How do I stop having carriage returns added to my file output in Python?
I'm trying to parse a BMP file, do some changes and then reassemble a new BMP using Python.

The carriage return seems to be a huge problem.  When I open the bitmap file using Notepad++ and search for "\r', the character does not exist.  I read the file in Python (readData = fileIn.read()) and try searching using readData.find('\r') it returns -1.  Searching for "\n" works fine.  All is good for now.

When I try to write this exact same block of text into a new BMP using fileOut.write(readData) and I use Notepad++ to search for "\r", I am able to find it (twice, each corresponding to the preexisting "\n" characters).

Is there a way to write this block of data to a new BMP without "\r" being added automatically?  I've tried applying .strip() and .replace('\r','') to the string before writing it to the new file.

答:
You're probably opening the file as text (the default) when you want to open it as binary.

```<code>open("example.bmp", "rb") # to [r]ead as [b]inary
open("example.bmp", "wb") # to [w]rite as [b]inary
</code>```

From the documentation:

The default is to use text mode, which may convert '\n' characters to a platform-specific representation on writing and back on reading. Thus, when opening a binary file, you should append 'b' to the mode value to open the file in binary mode, which will improve portability.

Body:
You're probably opening the file as text (the default) when you want to open it as binary.

open("example.bmp", "rb") # to [r]ead as [b]inary
open("example.bmp", "wb") # to [w]rite as [b]inary

From the documentation:

The default is to use text mode, which may convert '\n' characters to a platform-specific representation on writing and back on reading. Thus, when opening a binary file, you should append 'b' to the mode value to open the file in binary mode, which will improve portability.


问:
Why do I need to learn ReactJS before NextJS?
Learned TS and have to pick a framework.

Can someone please explain to me why we have to learn ReactJS BEFORE NextJS? All the articles advice of this but no one ever goes into WHY.

Can't I just learn NextJS and build UI elements with that? Or do we use react UI elements in our NextJS app and add routing to the ReactJS components via NextJS? Is this how it works? Or am I missing something...

If we use ReactJS UI elements in NextJS, I should spend my learning curve with ReactJS simply building UI elements I want for my site, then when I am comfortable with react. Try to couple them in a NextJS project, correct?

Edit: Let me clarify. What part of React CANNOT BE DONE IN NEXT. That we NEED to learn React for? I already know that React does CSR and Next can do SSR/SSG.

答: Because NextJS covers some advanced topics like Server-Side-Rendering, API routes, and page routing. Without knowing React you might learn NextJS but it will be painful probably. Also, most of the documents and videos out there assume that you know React so you may consider this too. I think it is like learning Typescript without knowing Javascript.</p>


答:
While iterating the file line-wise, keep track of the line before the current one:

```<code>with open("h.txt","w") as f:
    f.write("""NEW FUSTAT TOURS
City
USA
Addres
napolean
Phone Number
************
Email
***************
PACKAGES
Test TOURS
City
UK
Addres
napolean
Phone Number
************
Email
***************
PACKAGES""")

last_line = None
r = []
with open("h.txt") as f:
    for line in f:
        if line.strip() == "City" and last_line:
            r.append(last_line)
        else:
            last_line = line.strip()

print(r)
</code>```

Output:

```<code>['NEW FUSTAT TOURS', 'Test TOURS']
</code>```

Body:
While iterating the file line-wise, keep track of the line before the current one:

with open("h.txt","w") as f:
    f.write("""NEW FUSTAT TOURS
City
USA
Addres
napolean
Phone Number
************
Email
***************
PACKAGES
Test TOURS
City
UK
Addres
napolean
Phone Number
************
Email
***************
PACKAGES""")

last_line = None
r = []
with open("h.txt") as f:
    for line in f:
        if line.strip() == "City" and last_line:
            r.append(last_line)
        else:
            last_line = line.strip()

print(r)

Output:

['NEW FUSTAT TOURS', 'Test TOURS']


问:
How to add Text to multiple videos with ffmpeg
How to add Text to multiple videos with ffmpeg</p>
```<code>......... File.txt..
file 'Vidos1.mkv' -vf "drawtext=text='Good ':x=0:y=h-th:fontsize=24:fontcolor=white"
file 'Vidos2.mkv' -vf "drawtext=text='God':x=0:y=h-th:fontsize=24:fontcolor=white"
file 'Vidos3.mkv' -vf "drawtext=text='Go':x=0:y=h-th:fontsize=24:fontcolor=white"
......... File.txt..

ffmpeg  -f concat -safe 0 -re -i /File.txt ............
</code>```

答:
Reset PTS, then use drawtext filter and concat.</p>
```<code>ffmpeg -i Vidos1.mkv -i Vidos2.mkv -i Vidos3.mkv -filter_complex \
   "[0:v]setpts=PTS-STARTPTS,drawtext=text='Good ':x=0:y=h-th:fontsize=24:fontcolor=white[0v];\
    [1:v]setpts=PTS-STARTPTS,drawtext=text='God ':x=0:y=h-th:fontsize=24:fontcolor=white[1v];\
    [2:v]setpts=PTS-STARTPTS,drawtext=text='Go ':x=0:y=h-th:fontsize=24:fontcolor=white[2v];\
    [0:a]asetpts=PTS-STARTPTS[0a];[1:a]asetpts=PTS-STARTPTS[1a];[2:a]asetpts=PTS-STARTPTS[2a];\
    [0v][0a][1v][1a][2v][2a]concat=n=3:v=1:a=1" ...
</code>```

Body:
How to add Text to multiple videos with ffmpeg

......... File.txt..
file 'Vidos1.mkv' -vf "drawtext=text='Good ':x=0:y=h-th:fontsize=24:fontcolor=white"
file 'Vidos2.mkv' -vf "drawtext=text='God':x=0:y=h-th:fontsize=24:fontcolor=white"
file 'Vidos3.mkv' -vf "drawtext=text='Go':x=0:y=h-th:fontsize=24:fontcolor=white"
......... File.txt..

ffmpeg  -f concat -safe 0 -re -i /File.txt ............

Body:
Reset PTS, then use drawtext filter and concat.

ffmpeg -i Vidos1.mkv -i Vidos2.mkv -i Vidos3.mkv -filter_complex \
   "[0:v]setpts=PTS-STARTPTS,drawtext=text='Good ':x=0:y=h-th:fontsize=24:fontcolor=white[0v];\
    [1:v]setpts=PTS-STARTPTS,drawtext=text='God ':x=0:y=h-th:fontsize=24:fontcolor=white[1v];\
    [2:v]setpts=PTS-STARTPTS,drawtext=text='Go ':x=0:y=h-th:fontsize=24:fontcolor=white[2v];\
    [0:a]asetpts=PTS-STARTPTS[0a];[1:a]asetpts=PTS-STARTPTS[1a];[2:a]asetpts=PTS-STARTPTS[2a];\
    [0v][0a][1v][1a][2v][2a]concat=n=3:v=1:a=1" ...


问:
Read EXIF and determine if the flash has fired
I have been reading some EXIF data with my PHP script. I want to determine for a certain image if the flash has been used. Here are the values returned by EXIF reader

```<code>0x0     = No Flash
0x1     = Fired
0x5     = Fired, Return not detected
0x7     = Fired, Return detected
0x8     = On, Did not fire
0x9     = On, Fired
0xd     = On, Return not detected
0xf     = On, Return detected
0x10    = Off, Did not fire
0x14    = Off, Did not fire, Return not detected
0x18    = Auto, Did not fire
0x19    = Auto, Fired
0x1d    = Auto, Fired, Return not detected
0x1f    = Auto, Fired, Return detected
0x20    = No flash function
0x30    = Off, No flash function
0x41    = Fired, Red-eye reduction
0x45    = Fired, Red-eye reduction, Return not detected
0x47    = Fired, Red-eye reduction, Return detected
0x49    = On, Red-eye reduction
0x4d    = On, Red-eye reduction, Return not detected
0x4f    = On, Red-eye reduction, Return detected
0x50    = Off, Red-eye reduction
0x58    = Auto, Did not fire, Red-eye reduction
0x59    = Auto, Fired, Red-eye reduction
0x5d    = Auto, Fired, Red-eye reduction, Return not detected
0x5f    = Auto, Fired, Red-eye reduction, Return detected
</code>```

Which of them mean that the flash has been used?

Best regards,
Mladjo

答:
The flash property is actually a combination of the following flags:

```<code>0:  FlashDidNotFire
1:  FlashFired
2:  StrobeReturnLightDetected
4:  StrobeReturnLightNotDetected
8:  CompulsoryFlashMode
16: AutoMode
32: NoFlashFunction
64: RedEyeReductionMode
</code>```

To check if the flash has fired, bitwise AND the flash property with 1:

```<code>$flashfired = ($exifflashproperty & 1) != 0;
</code>```

Body:
I have been reading some EXIF data with my PHP script. I want to determine for a certain image if the flash has been used. Here are the values returned by EXIF reader

0x0     = No Flash
0x1     = Fired
0x5     = Fired, Return not detected
0x7     = Fired, Return detected
0x8     = On, Did not fire
0x9     = On, Fired
0xd     = On, Return not detected
0xf     = On, Return detected
0x10    = Off, Did not fire
0x14    = Off, Did not fire, Return not detected
0x18    = Auto, Did not fire
0x19    = Auto, Fired
0x1d    = Auto, Fired, Return not detected
0x1f    = Auto, Fired, Return detected
0x20    = No flash function
0x30    = Off, No flash function
0x41    = Fired, Red-eye reduction
0x45    = Fired, Red-eye reduction, Return not detected
0x47    = Fired, Red-eye reduction, Return detected
0x49    = On, Red-eye reduction
0x4d    = On, Red-eye reduction, Return not detected
0x4f    = On, Red-eye reduction, Return detected
0x50    = Off, Red-eye reduction
0x58    = Auto, Did not fire, Red-eye reduction
0x59    = Auto, Fired, Red-eye reduction
0x5d    = Auto, Fired, Red-eye reduction, Return not detected
0x5f    = Auto, Fired, Red-eye reduction, Return detected

Which of them mean that the flash has been used?

Best regards,
Mladjo

Body:
The flash property is actually a combination of the following flags:

0:  FlashDidNotFire
1:  FlashFired
2:  StrobeReturnLightDetected
4:  StrobeReturnLightNotDetected
8:  CompulsoryFlashMode
16: AutoMode
32: NoFlashFunction
64: RedEyeReductionMode

To check if the flash has fired, bitwise AND the flash property with 1:

$flashfired = ($exifflashproperty & 1) != 0;


问:
User Defined Function with Strings giving error

Date
Name

24-Jun-68
Bill

I would like to create a function that transforms this Date into a working date format. However, I am unable to get this function to return anything I am getting an error that says. AttributeError: 'str' object has no attribute 'str'. The function is below

```<code>    day=x.str.split("-")[0]
    month=x.str.split("-")[1]
    year=x.str.split("-")[2]
    return month+"/"+day+"/"+"19"+year

df['New Date'] = df['Date'].apply(get_date)```

```

答: str is supposed to be the string you are passing. So it should be x.split("-")[0], x.split("-")[1], and x.split("-")[2]

Body:
Date
Name

24-Jun-68
Bill

I would like to create a function that transforms this Date into a working date format. However, I am unable to get this function to return anything I am getting an error that says. AttributeError: 'str' object has no attribute 'str'. The function is below

    day=x.str.split("-")[0]
    month=x.str.split("-")[1]
    year=x.str.split("-")[2]
    return month+"/"+day+"/"+"19"+year

df['New Date'] = df['Date'].apply(get_date)```


问:
Run a Maven Project using IntelliJ IDEA
I'm new to IntelliJ IDEA and I would like to run a simple Maven Quickstart project using it.

I followed all the instructions, the project was sucessfully built. But when I try to compile and run it , the Run button is not activated.

It looks like IntelliJ IDEA couldn't figure out where the main class is.

This is a picture of the project's hierarchy.

What is the problem ? And how can I fix it ?

Thanks !

答:
If maven not visible top-right side then maven plugins not avaiable in your intellij IDE.

Follow below steps:
click settings icon(top-right side)->select plugin->click on checkbox at maven option->click apply button then ok button.

After few minutes maven able to see in you IDE.

Title: Run a Maven Project using IntelliJ IDEA


问:
Pure CSS Parallax additional space problem

What I want to achieve

I want to add a parallax effect to a single fullscreen section with dynamic content (has not fixed height) and a background.

I would like that on a scroll the background would move slower than the content and that the background would be high enough to cover the whole content.

What I've tried

To achieve that I have:

set perspective: 10px to .root

set transform: translateZ(-10px) scale(2) to .background

put .background into .container and set it's position to absolute so it has the container's height (which is dependent on content's height)

Problem

The problem is that when I scroll down to the bottom I can see:

bottom of the .content

a piece of a .background

a black piece of body's black background (appears on Chrome)

When I would scroll down to the bottom I would like that the .content would be the end of the screen and that I wouldn't see anything else beneath it.

Code

body { margin: 0; background: #000; }

.wrapper {
  height: 100vh;
  overflow: scroll;
  perspective: 10px;
}

.container {
  position: relative;
  transform-style: preserve-3d;
}

.content {
  display: flex; flex-direction: column; justify-content: space-between;
  height: calc(100vh + 100px);
  padding: 20px 0;
  background: rgba(255, 0, 0, 0.2);
  text-align: center;
}

.background {
  position: absolute; top: 0; right: 0; bottom: 0; left: 0; z-index: -1;
  background-image: linear-gradient(cyan, pink);
  transform: translateZ(-10px) scale(2);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <div class="container">
    <div class="content">
      <p>top content</p>
      <p>center content</p>
      <p>bottom content</p>
    </div>

    <div class="background"></div>
  </div>
</div></code>```

Question

How can I achieve it?
I have no idea how can I make it work.

Please help

答:
Something like this?

body { margin: 0; background: #000; }

.wrapper {
  height: 100vh;
  overflow: scroll;
  perspective: 10px;
}

.container {
  position: relative;
  transform-style: preserve-3d;
}

.content {
  display: flex; flex-direction: column; justify-content: space-between;
  padding: 20px 0;
  background: rgba(255, 0, 0, 0.2);
  text-align: center;
}

.content p {

  height: 100vh;
 }

.background {
  position: absolute; top: 0; right: 0; bottom: 0; left: 0; z-index: -1;
  background-image: linear-gradient(cyan, pink);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <div class="container">
    <div class="content">
      <p>top content</p>
      <p>center content</p>
      <p>bottom content</p>
    </div>

    <div class="background"></div>
  </div>
</div></code>```

Body:
What I want to achieve

I want to add a parallax effect to a single fullscreen section with dynamic content (has not fixed height) and a background.

I would like that on a scroll the background would move slower than the content and that the background would be high enough to cover the whole content.

What I've tried

To achieve that I have:

set perspective: 10px to .root

set transform: translateZ(-10px) scale(2) to .background

put .background into .container and set it's position to absolute so it has the container's height (which is dependent on content's height)

Problem

The problem is that when I scroll down to the bottom I can see:

bottom of the .content

a piece of a .background

a black piece of body's black background (appears on Chrome)

When I would scroll down to the bottom I would like that the .content would be the end of the screen and that I wouldn't see anything else beneath it.

Code

body { margin: 0; background: #000; }

.wrapper {
  height: 100vh;
  overflow: scroll;
  perspective: 10px;
}

.container {
  position: relative;
  transform-style: preserve-3d;
}

.content {
  display: flex; flex-direction: column; justify-content: space-between;
  height: calc(100vh + 100px);
  padding: 20px 0;
  background: rgba(255, 0, 0, 0.2);
  text-align: center;
}

.background {
  position: absolute; top: 0; right: 0; bottom: 0; left: 0; z-index: -1;
  background-image: linear-gradient(cyan, pink);
  transform: translateZ(-10px) scale(2);
}

top content

center content

bottom content

Question

How can I achieve it?
I have no idea how can I make it work.

Please help

Body:
Something like this?

body { margin: 0; background: #000; }

.wrapper {
  height: 100vh;
  overflow: scroll;
  perspective: 10px;
}

.container {
  position: relative;
  transform-style: preserve-3d;
}

.content {
  display: flex; flex-direction: column; justify-content: space-between;
  padding: 20px 0;
  background: rgba(255, 0, 0, 0.2);
  text-align: center;
}

.content p {

  height: 100vh;
 }

.background {
  position: absolute; top: 0; right: 0; bottom: 0; left: 0; z-index: -1;
  background-image: linear-gradient(cyan, pink);
}

<div class="wrapper">
  <div class="container">
    <div class="content">
      <p>top content</p>
      <p>center content</p>
      <p>bottom content</p>
    </div>

    <div class="background"></div>
  </div>
</div>