问:
Parsing a string containing code into a list / tree in python
as the title suggests I'm trying to parse a piece of code into a tree or a list.
First off I would like to thank for any contribution and time spent on this.
So far my code is doing what I expect, yet I am not sure that this is the optimal / most generic way to do this.

Problem

1. I want to have a more generic solution since in the future I am going to need further analysis of this sintax.
2. I am unable right now to separate the operators like '=' or '>=' as you can see below in the output I share.
In the future I might change the content of the list / tree from strings to tuples so i can identify the kind of operator (parameter, comparison like = or >= ....). But this is not a real need right now.

Research

My first attempt was parsing the text character by character, but my code was getting too messy and barely readable, so I assumed that I was doing something wrong there (I don't have that code to share here anymore)
So i started looking around how people where doing it and found some approaches that didn't necessarily fullfil the requirements of simplicity and generic.
I would share the links to the sites but I didn't keep track of them.

The Syntax of the code

The syntax is pretty simple, after all I'm no interested in types or any further detail. just the functions and parameters.
strings are defined as 'my string', variables as !variable and numbers as in any other language.
Here is a sample of code:

```<code>db('1', '2', if(ATTRS('Dim 1', !Element Structure, 'ID') = '3','4','5'), 6)
</code>```

My Output

Here my output is partialy correct since I'm still unable to separate the "= '3'" part (of course I have to separate it because in this case its a comparison operator and not part of a string)

```<code>[{'db': ["'1'", "'2'", {'if': [{'ATTRS': ["'Dim 1'", '!Element Structure', "'ID'"]}, "= '3'", "'4'", "'5'"]}, '6']}]
</code>```

Desired Output

```<code>[{'db': ["'1'", "'2'", {'if': [{'ATTRS': ["'Dim 1'", '!Element Structure', "'ID'"]}, "=", "'3'", "'4'", "'5'"]}, '6']}]
</code>```

My code so far

The parseRecursive method is the entry point.

```<code>import re

class FileParser:

    #order is important to avoid miss splits
    COMPARATOR_SIGN = {
        '@='
        ,'@<>'
        ,'<>'
        ,'>='
        ,'<='
        ,'='
        ,'>'
        ,'<'
    }

    def __init__(self):
        pass

    def __charExistsInOccurences(self,current_needle, needles, text):
        """
        check if other needles are present in text
        current_needle : string -> the current needle being evaluated
        needles : list -> list of needles
        text : string/list<string> -> a string or a list of string to evaluate
        """
        #if text is a string convert it to list of strings
        text = text if isinstance(text, list) else [text]

        exists = False

        for t in text:
            #check if needle is inside text value
            for needle in needles:
                    #dont check the same key
                    if needle != current_needle:
                        regex_search_needle = split_regex = '\s*'+'\s*'.join(needle) + '\s*'
                        #list of 1's and 0's . 1 if another character is found in the string.
                        found = [1 if re.search(regex_search_needle, x) else 0 for x in t]
                        if sum(found) > 0:
                            exists = True
                            break

        return exists

    def findOperator(self, needles, haystack):
        """
        split parameters from operators
        needles : list -> list of operators
        haystack : string
        """
        string_open = haystack.find("'")

        #if no string has been found set the index to 0
        if string_open < 0:
            string_open = 0

        occurences = []

        string_closure = haystack.rfind("'")
        operator = ''
        for needle in needles:
            #regex to ignore the possible spaces between characters of the needle
            split_regex = '\s*'+'\s*'.join(needle) + '\s*'

            #parse parameters before and after the string
            before_string = re.split(split_regex, haystack[0:string_open])
            after_string = re.split(split_regex, haystack[string_closure+1:])

            #check if any other needle exists in the results found
            before_string_exists = self.__charExistsInOccurences(needle, needles, before_string)
            after_string_exists = self.__charExistsInOccurences(needle, needles, after_string)

            #if the operator has been found merge the results with the occurences and assign the operator
            if not before_string_exists and not after_string_exists:
                occurences.extend(before_string)
                occurences.extend([haystack[string_open:string_closure+1]])
                occurences.extend(after_string)
                operator = needle

        #filter blank spaces generated
        occurences = list(filter(lambda x: len(x.strip())>0,occurences))
        result_check = [1 if x==haystack else 0 for x in occurences]
        #if the haystack was originaly a simple string like '1' the occurences list is going to be filled with the same character over and over due to the before string an after string part
        if len(result_check) == sum(result_check):
            occurences= [haystack]
            operator = ''

        return operator, occurences

    def parseRecursive(self,text):
        """
        parse a block of text
        text : string
        """

        assert(len(text) < 1, "text is empty")

        function_open = text.find('(')
        accumulated_params = []
        if function_open > -1:
            #there is another function nested
            text_prev_function = text[0:function_open]

            #find last space coma or equal to retrieve the function name
            last_space = -1
            for j in range(len(text_prev_function)-1, 0 , -1):
                if text_prev_function[j] == ' ' or text_prev_function[j] == ',' or text_prev_function[j] == '=':
                    last_space = j
                    break

            func_name = ''

            if last_space > -1:
                #there is something else behind the function name
                func_name = text_prev_function[last_space+1:]
                #no parentesis before so previous characters from function name are parameters
                text_prev_func_params = list(filter(lambda x: len(x.strip())>0,text_prev_function[:last_space+1].split(',')))
                text_prev_func_params = [x.strip() for x in text_prev_func_params]
                #debug here
                #accumulated_params.extend(text_prev_func_params)

                for itext_prev in text_prev_func_params:
                    operator, text_prev_operator = self.findOperator(self.COMPARATOR_SIGN,itext_prev)
                    if operator == '':
                        accumulated_params.extend(text_prev_operator)
                    else:
                        text_prev_operator.append(operator)
                        accumulated_params.extend(text_prev_operator)

                #accumulated_params.extend(text_prev_operator)
            else:
                #function name is the start of the string
                func_name = text_prev_function[0:].strip()

            #find the closure of parentesis
            function_close = text.rfind(')')
            #parse the next function and extend the current list of parameters
            next_func = text[function_open+1:function_close]
            func_params = {func_name : self.parseRecursive(next_func)}
            accumulated_params.append(func_params)

            #
            # parameters after the function
            #
            new_text = text[function_close+1:]
            accumulated_params.extend(self.parseRecursive(new_text))
        else:
            #there is no other function nested
            split_text = text.split(',')
            current_func_params = list(filter(lambda x: len(x.strip())>0,split_text))
            current_func_params = [x.strip() for x in current_func_params]
            accumulated_params.extend(current_func_params)

        #accumulated_params = list(filter(lambda x: len(x.strip())>0,accumulated_params))
        return accumulated_params

text = "db('1', '2', if(ATTRS('Dim 1', !Element Structure, 'ID') = '3','4','5'), 6)"
obj = FileParser()
print(obj.parseRecursive(text))
</code>```

答:
You can use pyparsing to deal with such a case.

* pyparsing can be installed by pip install pyparsing

Code:

import pyparsing as pp

# A parsing pattern
w = pp.Regex(r'(?:![^(),]+)|[^(), ]+') ^ pp.Suppress(',')
pattern = w + pp.nested_expr('(', ')', content=w)

# A recursive function to transform a pyparsing result into your desirable format
def transform(elements):
    stack = []
    for e in elements:
        if isinstance(e, list):
            key = stack.pop()
            stack.append({key: transform(e)})
        else:
            stack.append(e)
    return stack

# A sample
string = "db('1', '2', if(ATTRS('Dim 1', !Element Structure, 'ID') = '3','4','5'), 6)"

# Operations to parse the sample string
elements = pattern.parse_string(string).as_list()
result = transform(elements)

# Assertion
assert result == [{'db': ["'1'", "'2'", {'if': [{'ATTRS': ["'Dim 1'", '!Element Structure', "'ID'"]}, '=', "'3'", "'4'", "'5'"]}, '6']}]

# Show the result
print(result)
```
<h2>Output:</h2>
<pre class="lang-py prettyprint-override"><code>[{'db': ["'1'", "'2'", {'if': [{'ATTRS': ["'Dim 1'", '!Element Structure', "'ID'"]}, '=', "'3'", "'4'", "'5'"]}, '6']}]
</code>```

Note:

If there is an unbalanced parenthesis inside () (for example a(b(c), a(b)c), etc), an unexpected result is obtained or an IndexError is raised. So be careful in such cases.

At the moment, only a single sample is available to make a pattern to parse string. So if you encounter a parsing error, provide more examples in your question.

Body:
as the title suggests I'm trying to parse a piece of code into a tree or a list.
First off I would like to thank for any contribution and time spent on this.
So far my code is doing what I expect, yet I am not sure that this is the optimal / most generic way to do this.

Problem

1. I want to have a more generic solution since in the future I am going to need further analysis of this sintax.
2. I am unable right now to separate the operators like '=' or '>=' as you can see below in the output I share.
In the future I might change the content of the list / tree from strings to tuples so i can identify the kind of operator (parameter, comparison like = or >= ....). But this is not a real need right now.

Research

My first attempt was parsing the text character by character, but my code was getting too messy and barely readable, so I assumed that I was doing something wrong there (I don't have that code to share here anymore)
So i started looking around how people where doing it and found some approaches that didn't necessarily fullfil the requirements of simplicity and generic.
I would share the links to the sites but I didn't keep track of them.

The Syntax of the code

The syntax is pretty simple, after all I'm no interested in types or any further detail. just the functions and parameters.
strings are defined as 'my string', variables as !variable and numbers as in any other language.
Here is a sample of code:

db('1', '2', if(ATTRS('Dim 1', !Element Structure, 'ID') = '3','4','5'), 6)

My Output

Here my output is partialy correct since I'm still unable to separate the "= '3'" part (of course I have to separate it because in this case its a comparison operator and not part of a string)

[{'db': ["'1'", "'2'", {'if': [{'ATTRS': ["'Dim 1'", '!Element Structure', "'ID'"]}, "= '3'", "'4'", "'5'"]}, '6']}]

Desired Output

[{'db': ["'1'", "'2'", {'if': [{'ATTRS': ["'Dim 1'", '!Element Structure', "'ID'"]}, "=", "'3'", "'4'", "'5'"]}, '6']}]

My code so far

The parseRecursive method is the entry point.

import re

class FileParser:

    #order is important to avoid miss splits
    COMPARATOR_SIGN = {
        '@='
        ,'@<>'
        ,'<>'
        ,'>='
        ,'<='
        ,'='
        ,'>'
        ,'<'
    }

    def __init__(self):
        pass

    def __charExistsInOccurences(self,current_needle, needles, text):
        """
        check if other needles are present in text
        current_needle : string -> the current needle being evaluated
        needles : list -> list of needles
        text : string/list<string> -> a string or a list of string to evaluate
        """
        #if text is a string convert it to list of strings
        text = text if isinstance(text, list) else [text]

        exists = False

        for t in text:
            #check if needle is inside text value
            for needle in needles:
                    #dont check the same key
                    if needle != current_needle:
                        regex_search_needle = split_regex = '\s*'+'\s*'.join(needle) + '\s*'
                        #list of 1's and 0's . 1 if another character is found in the string.
                        found = [1 if re.search(regex_search_needle, x) else 0 for x in t]
                        if sum(found) > 0:
                            exists = True
                            break

        return exists

    def findOperator(self, needles, haystack):
        """
        split parameters from operators
        needles : list -> list of operators
        haystack : string
        """
        string_open = haystack.find("'")

        #if no string has been found set the index to 0
        if string_open < 0:
            string_open = 0

        occurences = []

        string_closure = haystack.rfind("'")
        operator = ''
        for needle in needles:
            #regex to ignore the possible spaces between characters of the needle
            split_regex = '\s*'+'\s*'.join(needle) + '\s*'

            #parse parameters before and after the string
            before_string = re.split(split_regex, haystack[0:string_open])
            after_string = re.split(split_regex, haystack[string_closure+1:])

            #check if any other needle exists in the results found
            before_string_exists = self.__charExistsInOccurences(needle, needles, before_string)
            after_string_exists = self.__charExistsInOccurences(needle, needles, after_string)

            #if the operator has been found merge the results with the occurences and assign the operator
            if not before_string_exists and not after_string_exists:
                occurences.extend(before_string)
                occurences.extend([haystack[string_open:string_closure+1]])
                occurences.extend(after_string)
                operator = needle

        #filter blank spaces generated
        occurences = list(filter(lambda x: len(x.strip())>0,occurences))
        result_check = [1 if x==haystack else 0 for x in occurences]
        #if the haystack was originaly a simple string like '1' the occurences list is going to be filled with the same character over and over due to the before string an after string part
        if len(result_check) == sum(result_check):
            occurences= [haystack]
            operator = ''

        return operator, occurences

    def parseRecursive(self,text):
        """
        parse a block of text
        text : string
        """

        assert(len(text) < 1, "text is empty")

        function_open = text.find('(')
        accumulated_params = []
        if function_open > -1:
            #there is another function nested
            text_prev_function = text[0:function_open]

            #find last space coma or equal to retrieve the function name
            last_space = -1
            for j in range(len(text_prev_function)-1, 0 , -1):
                if text_prev_function[j] == ' ' or text_prev_function[j] == ',' or text_prev_function[j] == '=':
                    last_space = j
                    break

            func_name = ''

            if last_space > -1:
                #there is something else behind the function name
                func_name = text_prev_function[last_space+1:]
                #no parentesis before so previous characters from function name are parameters
                text_prev_func_params = list(filter(lambda x: len(x.strip())>0,text_prev_function[:last_space+1].split(',')))
                text_prev_func_params = [x.strip() for x in text_prev_func_params]
                #debug here
                #accumulated_params.extend(text_prev_func_params)

                for itext_prev in text_prev_func_params:
                    operator, text_prev_operator = self.findOperator(self.COMPARATOR_SIGN,itext_prev)
                    if operator == '':
                        accumulated_params.extend(text_prev_operator)
                    else:
                        text_prev_operator.append(operator)
                        accumulated_params.extend(text_prev_operator)

                #accumulated_params.extend(text_prev_operator)
            else:
                #function name is the start of the string
                func_name = text_prev_function[0:].strip()

            #find the closure of parentesis
            function_close = text.rfind(')')
            #parse the next function and extend the current list of parameters
            next_func = text[function_open+1:function_close]
            func_params = {func_name : self.parseRecursive(next_func)}
            accumulated_params.append(func_params)

            #
            # parameters after the function
            #
            new_text = text[function_close+1:]
            accumulated_params.extend(self.parseRecursive(new_text))
        else:
            #there is no other function nested
            split_text = text.split(',')
            current_func_params = list(filter(lambda x: len(x.strip())>0,split_text))
            current_func_params = [x.strip() for x in current_func_params]
            accumulated_params.extend(current_func_params)

        #accumulated_params = list(filter(lambda x: len(x.strip())>0,accumulated_params))
        return accumulated_params

text = "db('1', '2', if(ATTRS('Dim 1', !Element Structure, 'ID') = '3','4','5'), 6)"
obj = FileParser()
print(obj.parseRecursive(text))

Body:
You can use pyparsing to deal with such a case.

* pyparsing can be installed by pip install pyparsing

Code:

import pyparsing as pp

# A parsing pattern
w = pp.Regex(r'(?:![^(),]+)|[^(), ]+') ^ pp.Suppress(',')
pattern = w + pp.nested_expr('(', ')', content=w)

# A recursive function to transform a pyparsing result into your desirable format
def transform(elements):
    stack = []
    for e in elements:
        if isinstance(e, list):
            key = stack.pop()
            stack.append({key: transform(e)})
        else:
            stack.append(e)
    return stack

# A sample
string = "db('1', '2', if(ATTRS('Dim 1', !Element Structure, 'ID') = '3','4','5'), 6)"

# Operations to parse the sample string
elements = pattern.parse_string(string).as_list()
result = transform(elements)

# Assertion
assert result == [{'db': ["'1'", "'2'", {'if': [{'ATTRS': ["'Dim 1'", '!Element Structure', "'ID'"]}, '=', "'3'", "'4'", "'5'"]}, '6']}]

# Show the result
print(result)

Output:

[{'db': ["'1'", "'2'", {'if': [{'ATTRS': ["'Dim 1'", '!Element Structure', "'ID'"]}, '=', "'3'", "'4'", "'5'"]}, '6']}]

Note:

If there is an unbalanced parenthesis inside () (for example a(b(c), a(b)c), etc), an unexpected result is obtained or an IndexError is raised. So be careful in such cases.

At the moment, only a single sample is available to make a pattern to parse string. So if you encounter a parsing error, provide more examples in your question.


来源: stackexchange

问:
Publishing Azure function app with Api Management service -- Failed to update your API in Azure (Status code: BadRequest)
I have an Azure function app that uses api management service running locally. I created it with Visual Studio 2022. But when I try to publish it, everything looks good until this error appears.

```<code>========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========
========== Publish: 1 succeeded, 0 failed, 0 skipped ==========
Waiting for function app to be ready...
Finished waiting for function app to be ready
Starting to update your API
Failed to update your API in Azure (Status code: BadRequest).
</code>```

The app is created under the resource group, but not the api management service. And analysis file was generated.

```<code>Microsoft.WebTools.Shared.Exceptions.WebToolsException: Failed to update your API in Azure (Status code: BadRequest).

   at Microsoft.WebTools.Azure.Publish.ApiMApi.BaseApiMApiUpdater.EmitTerminatingError(String bucketName, String displayedErrorMessage, String loggedErrorMessage)
   at Microsoft.WebTools.Azure.Publish.ApiMApi.BaseApiMApiUpdater.<UpdateApiMApiInAzureAsync>d__10.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.WebTools.Azure.Publish.ApiMApi.FunctionAppApiMApiPublishHandler.FunctionApiMApiUpdater.<ImportSwaggerLinkToApiMAppAsync>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.WebTools.Azure.Publish.ApiMApi.FunctionAppApiMApiPublishHandler.FunctionApiMApiUpdater.<RunUpdateAsync>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.WebTools.Azure.Publish.ApiMApi.BaseApiMApiUpdater.<RunUpdateWithTelemetryAsync>d__9.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.WebTools.Azure.Publish.ApiMApi.FunctionAppApiMApiPublishHandler.<UpdateApiMApiAsync>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.WebTools.Azure.Functions.PublishProviders.AzureFunctionProfileVisual.<FunctionsAfterPostPublishAsync>d__42.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Publish.Framework.Nexus.PublishProfilesServiceImpl.ServerProjectProfilesManager.
<RunPublishTaskAsync>d__56.MoveNext()

===================
</code>```

I also tried deleting everything and retrying, this time creating the api management service when I did the publish. The app was created as before, but the api management service was not created.

答:
Here is the workaround I did to publish the Azure Function - .Net Stack - Http Trigger with Open API.

Created the Azure Functions (.Net 3.1 Stack - Http Trigger with Open API) and got the boilerplate code which takes the name as Query Parameter and sends the result.

Published it by creating the Azure Functions App Instance and Azure APIM Instance from Visual Studio Publish Window and it is successful.

Modified the boilerplate code by removing the name parameter and displaying the custom response message.

Published the updated function code to the Azure APIM and updated the API Successfully.

Note:

```<code>Microsoft.WebTools.Shared.Exceptions.WebToolsException: Failed to update your API in Azure (Status code: BadRequest).
</code>```

This error happens when there have been current updates to Visual Studio at least to my knowledge.

And this error is related to build problem or Run time error I guess.

To resolve this error, follow the steps below:

Stop or Cancel Building the application if the build is stuck.

Make sure you save your changes

Close Visual Studio and open your project again.

When the project loads into Visual Studio, Clean the Solution

Then build the solution

After building the solution, go ahead and publish if you need to.

ContentLicense: CC BY-SA 4.0

Body:
I have an Azure function app that uses api management service running locally. I created it with Visual Studio 2022. But when I try to publish it, everything looks good until this error appears.

========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========
========== Publish: 1 succeeded, 0 failed, 0 skipped ==========
Waiting for function app to be ready...
Finished waiting for function app to be ready
Starting to update your API
Failed to update your API in Azure (Status code: BadRequest).

The app is created under the resource group, but not the api management service. And analysis file was generated.

Microsoft.WebTools.Shared.Exceptions.WebToolsException: Failed to update your API in Azure (Status code: BadRequest).

   at Microsoft.WebTools.Azure.Publish.ApiMApi.BaseApiMApiUpdater.EmitTerminatingError(String bucketName, String displayedErrorMessage, String loggedErrorMessage)
   at Microsoft.WebTools.Azure.Publish.ApiMApi.BaseApiMApiUpdater.<UpdateApiMApiInAzureAsync>d__10.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.WebTools.Azure.Publish.ApiMApi.FunctionAppApiMApiPublishHandler.FunctionApiMApiUpdater.<ImportSwaggerLinkToApiMAppAsync>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.WebTools.Azure.Publish.ApiMApi.FunctionAppApiMApiPublishHandler.FunctionApiMApiUpdater.<RunUpdateAsync>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.WebTools.Azure.Publish.ApiMApi.BaseApiMApiUpdater.<RunUpdateWithTelemetryAsync>d__9.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.WebTools.Azure.Publish.ApiMApi.FunctionAppApiMApiPublishHandler.<UpdateApiMApiAsync>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.WebTools.Azure.Functions.PublishProviders.AzureFunctionProfileVisual.<FunctionsAfterPostPublishAsync>d__42.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Publish.Framework.Nexus.PublishProfilesServiceImpl.ServerProjectProfilesManager.
<RunPublishTaskAsync>d__56.MoveNext()

===================

I also tried deleting everything and retrying, this time creating the api management service when I did the publish. The app was created as before, but the api management service was not created.

Body:
Here is the workaround I did to publish the Azure Function - .Net Stack - Http Trigger with Open API.

Created the Azure Functions (.Net 3.1 Stack - Http Trigger with Open API) and got the boilerplate code which takes the name as Query Parameter and sends the result.

Published it by creating the Azure Functions App Instance and Azure APIM Instance from Visual Studio Publish Window and it is successful.

Modified the boilerplate code by removing the name parameter and displaying the custom response message.

Published the updated function code to the Azure APIM and updated the API Successfully.

Note:

Microsoft.WebTools.Shared.Exceptions.WebToolsException: Failed to update your API in Azure (Status code: BadRequest).

This error happens when there have been current updates to Visual Studio at least to my knowledge.

And this error is related to build problem or Run time error I guess.

To resolve this error, follow the steps below:

Stop or Cancel Building the application if the build is stuck.

Make sure you save your changes

Close Visual Studio and open your project again.

When the project loads into Visual Studio, Clean the Solution

Then build the solution

After building the solution, go ahead and publish if you need to.


问:
what happens to events after the object it references is disposed of?
what happens if i link a method of some object to a delegate, and then dispose of the object?

Like this:

```<code>class Hunter
{
    public event Action Shoot;

    public execute()
    {
        Form formBabySeal = new Form();

        Shoot += formBabySeal.Close;

        formBabySeal.Show();
        formBabySeal.Close(); //Dispose Form

        if (Shoot != null)
        {
             Shoot(); //event is null?
        }
    }
}
</code>```

答: WinDBG with SOS extensions has a way to show GCRoot of any object.  This might give you more clues.</p>

ContentLicense: CC BY-SA 3.0

Body:
what happens if i link a method of some object to a delegate, and then dispose of the object?

Like this:

class Hunter
{
    public event Action Shoot;

    public execute()
    {
        Form formBabySeal = new Form();

        Shoot += formBabySeal.Close;

        formBabySeal.Show();
        formBabySeal.Close(); //Dispose Form

        if (Shoot != null)
        {
             Shoot(); //event is null?
        }
    }
}


问:
How to update a fork from it's original via the Github API
I've created a fork of a github repository via the github API. Now, later on, I want to pull any updates from the origin repository into the fork. This should always be a fast-forward in my use case. I have read access to the origin repository and read-write to the fork.

I thought of maybe creating a Pull Request then accepting (both of which you can do via the API) but this creates noise (Pull Requests being created and destroyed) and just doesn't seem right.

Is there any way to do this via the API?

答:
This is now possible in the GitHub API; documentation here, and announcement here.

In summary, make a POST request to /repos/{owner}/{repo}/merge-upstream with the proper authentication and the payload of { "branch": "branch-name" }.


问:
How to configure Babel to only output es2017/modern code?
I'm trying to configure web with optimize-plugin and babel to create module/nomodule bundles. In fact, I son't mind too much the nomodule thing, but I'd like to be sure to correctly configure babel to output es2017 code. In several tuts, for example this one, I've found a preset like 'es2017', but from babel docs it seems it's not supported anymore. Instead, I should use '@babel/preset-env' along with a browserlist config. It's not really clear to me how I should compose the browserlist. For now, I would say something like:

```<code>module.exports = {
  presets : [ '@babel/preset-env' ],

  targets : {
    browsers: "last 2 versions, not dead, not IE 11",
    esmodules: true
  }
};
</code>```

But not really sure.. Can someone tell me the perfect one? :)

答:
I've just found an answer by reading this code that comes from here. It's simply:

```<code>'last 2 Chrome versions',
'last 2 Safari versions',
'last 2 iOS versions',
'last 2 Edge versions',
'Firefox ESR',
</code>```

And not using the esmodules target due to this issue, as reported in  comments on linked code above:

https://github.com/babel/babel/issues/8809

Even if probably with babel 8 we will be able to use it:

https://github.com/babel/babel/pull/12189

Body:
I'm trying to configure web with optimize-plugin and babel to create module/nomodule bundles. In fact, I son't mind too much the nomodule thing, but I'd like to be sure to correctly configure babel to output es2017 code. In several tuts, for example this one, I've found a preset like 'es2017', but from babel docs it seems it's not supported anymore. Instead, I should use '@babel/preset-env' along with a browserlist config. It's not really clear to me how I should compose the browserlist. For now, I would say something like:

module.exports = {
  presets : [ '@babel/preset-env' ],

  targets : {
    browsers: "last 2 versions, not dead, not IE 11",
    esmodules: true
  }
};

But not really sure.. Can someone tell me the perfect one? :)

Body:
I've just found an answer by reading this code that comes from here. It's simply:

'last 2 Chrome versions',
'last 2 Safari versions',
'last 2 iOS versions',
'last 2 Edge versions',
'Firefox ESR',

And not using the esmodules target due to this issue, as reported in  comments on linked code above:

https://github.com/babel/babel/issues/8809

Even if probably with babel 8 we will be able to use it:

https://github.com/babel/babel/pull/12189


问:
Getting text from header columns
I have an MS Word document with a three-column header like in the screenshot below.
Please advise a VBA macro to get the text in each of the columns (in my case "foo", "bar" and "baz").

So far I have tried

```<code>Sub Test()
  MsgBox Documents(1).Sections(1).Headers(wdHeaderFooterPrimary).Range.Text
End Sub
enter code here
</code>```

, but it returns text with zeros ("foo0bar0baz"), which seems not to be suitable to break this text in general case, when the column texts themselves can contain zeros (e.g. "foo0", "0bar00" and "0baz").

答:
You use the Split function to create an array of the text. You will need to know what character has been used to separate the columns. It will probably be either a normal tab or an alignment tab.

For a normal tab:

```<code>Sub SplitHeader()
   Dim colHeads As Variant
   colHeads = Split(ActiveDocument.Sections(1).Headers(wdHeaderFooterPrimary).Range.Text, vbTab)
   Debug.Print colHeads(0)
   Debug.Print colHeads(1)
   Debug.Print colHeads(2)
End Sub
</code>```

For an alignment tab:

```<code>Sub SplitHeader()
   Dim colHeads As Variant
   colHeads = Split(ActiveDocument.Sections(1).Headers(wdHeaderFooterPrimary).Range.Text, Chr(48))

End Sub
</code>```

Title: Getting text from header columns

Body:
I have an MS Word document with a three-column header like in the screenshot below.
Please advise a VBA macro to get the text in each of the columns (in my case "foo", "bar" and "baz").

So far I have tried

Sub Test()
  MsgBox Documents(1).Sections(1).Headers(wdHeaderFooterPrimary).Range.Text
End Sub
enter code here

, but it returns text with zeros ("foo0bar0baz"), which seems not to be suitable to break this text in general case, when the column texts themselves can contain zeros (e.g. "foo0", "0bar00" and "0baz").

Body:
You use the Split function to create an array of the text. You will need to know what character has been used to separate the columns. It will probably be either a normal tab or an alignment tab.

For a normal tab:

Sub SplitHeader()
   Dim colHeads As Variant
   colHeads = Split(ActiveDocument.Sections(1).Headers(wdHeaderFooterPrimary).Range.Text, vbTab)
   Debug.Print colHeads(0)
   Debug.Print colHeads(1)
   Debug.Print colHeads(2)
End Sub

For an alignment tab:

Sub SplitHeader()
   Dim colHeads As Variant
   colHeads = Split(ActiveDocument.Sections(1).Headers(wdHeaderFooterPrimary).Range.Text, Chr(48))

End Sub


问:
Codeigniter in subdirectory - why does resolving controller/class/function not work?
I have a base codeigniter setup and can not get it to run. I thought I had understood that it works like the following:

```<code>http://localhost/index.php/class/function
</code>```

where class points to the controller.

The problem I have is that my install is in a subfolder like so:

```<code>http://localhost/path%20to%20ci/index.php/class/function
</code>```

and CI always gives me a 404 even the controller class exists.

I've digged into the CI source and it shows me that the whole request URI is taken as input:

```<code>path to ci/index.php/class/function
</code>```

Is there anything I need to configure to make CI detect the prefix automatically for  resolving class and function?

Can I or even do I need to setup a base path?

Concrete Example

My CI path is accessible via:

```<code>http://localhost/workspace/Limesurvey%20CI/index.php
</code>```

The working controller is:

```<code>http://localhost/workspace/Limesurvey%20CI/index.php/installer
</code>```

Setting the base path in application/config/config.php to:

```<code>$config['base_url'] = 'http://localhost/workspace/Limesurvey%20CI/';
</code>```

which is according to the documentation given for that setting.

答:
You define the base_url within application/config/config.php by setting the config variable $config['base_url'].

Once configured it should resolve your issue.

Body:
I have a base codeigniter setup and can not get it to run. I thought I had understood that it works like the following:

http://localhost/index.php/class/function

where class points to the controller.

The problem I have is that my install is in a subfolder like so:

http://localhost/path%20to%20ci/index.php/class/function

and CI always gives me a 404 even the controller class exists.

I've digged into the CI source and it shows me that the whole request URI is taken as input:

path to ci/index.php/class/function

Is there anything I need to configure to make CI detect the prefix automatically for  resolving class and function?

Can I or even do I need to setup a base path?

Concrete Example

My CI path is accessible via:

http://localhost/workspace/Limesurvey%20CI/index.php

The working controller is:

http://localhost/workspace/Limesurvey%20CI/index.php/installer

Setting the base path in application/config/config.php to:

$config['base_url'] = 'http://localhost/workspace/Limesurvey%20CI/';

which is according to the documentation given for that setting.


问:
Second time FPDF runs, crashes
I use the code below to generate monthly reports. When I need to get reports of two different months, the first month is created correctly, then I change the month and restart the program. Upon output, fpdf crashes with the traceback you see below
To get the two months' reports I have to create the first report, completely exit the py program, restart and create the second report.

From what I see in the traceback it doesn't seem to find any images, but they are the same ones used for the first report

```<code>class Build_Pdf(FPDF):

    table = ''
pdf = FPDF('L', 'mm', 'A4')
pdf.alias_nb_pages()

def top(year, meonth, table):
    pdf.add_font('IndieFlower-Regular', '', '/usr/.local/share/fonts/IndieFlower-Regular.ttf', uni=True)
    write_year = 'Reference: ' + month + ' ' + year
    pdf.add_page()
    pdf.image('/opt/rambo/logo.jpg', 25, 8, 30)
    pdf.set_font('IndieFlower-Regular', '', 15)
    pdf.set_y(50)
    pdf.set_x(15)
    pdf.cell(50, 7, write_year, 0, 1, 'L')
    pdf.image('/opt/rambo/gg.png', 65, 30, 15)
    return

def create_Pdf(year, month):
    global error, none
    month = Functions.convert_month_number[month]
    check = check_table(year, month, daysinmonth, table = 'timetable')
    if check is not 0:
        go_Pdf (year, month, table = 'timetable')
    [...]
    pdffile = '/media/hdb1/temp/Location.pdf'
    if os.path.exists(pdffile):
        os.remove(pdffile)
    pdf.output(pdffile, 'F')
    pdf.close()
    msg = QMessageBox()
    msg.setIcon(QMessageBox.Information)
    msg.setText("Pdf file is in /media/hdb1/temp/Location.pdf")
    msg.exec_()
    return

Traceback (most recent call last):
  File "../PycharmProjects/SecondOne/index.py", line 333, in MakePdf
    Create_Pdf(year, month)
  File "../PycharmProjects/SecondOne/makepdfhour_data.py", line 86, in Create_Pdf
    pdf.output(pdffile, 'F')
  File ".../fpdf/fpdf.py", line 1065, in output
    self.close()
  File ".../fpdf/fpdf.py", line 246, in close
    self._enddoc()
  File ".../fpdf/fpdf.py", line 1637, in _enddoc
    self._putresources()
  File ".../fpdf/fpdf.py", line 1585, in _putresources
    self._putimages()
  File ".../fpdf/fpdf.py", line 1515, in _putimages
    del info['data']
KeyError: 'data'
</code>```

答:
Just add a constructor to your class like the below code and it will work.</p>
```<code>def __init__(self):
    self.table = ''
    self.pdf = FPDF('L', 'mm', 'A4')
    self.pdf.alias_nb_pages()
</code>```

Title: Second time FPDF runs, crashes

Body:
I use the code below to generate monthly reports. When I need to get reports of two different months, the first month is created correctly, then I change the month and restart the program. Upon output, fpdf crashes with the traceback you see below
To get the two months' reports I have to create the first report, completely exit the py program, restart and create the second report.

From what I see in the traceback it doesn't seem to find any images, but they are the same ones used for the first report

class Build_Pdf(FPDF):

    table = ''
pdf = FPDF('L', 'mm', 'A4')
pdf.alias_nb_pages()

def top(year, meonth, table):
    pdf.add_font('IndieFlower-Regular', '', '/usr/.local/share/fonts/IndieFlower-Regular.ttf', uni=True)
    write_year = 'Reference: ' + month + ' ' + year
    pdf.add_page()
    pdf.image('/opt/rambo/logo.jpg', 25, 8, 30)
    pdf.set_font('IndieFlower-Regular', '', 15)
    pdf.set_y(50)
    pdf.set_x(15)
    pdf.cell(50, 7, write_year, 0, 1, 'L')
    pdf.image('/opt/rambo/gg.png', 65, 30, 15)
    return

def create_Pdf(year, month):
    global error, none
    month = Functions.convert_month_number[month]
    check = check_table(year, month, daysinmonth, table = 'timetable')
    if check is not 0:
        go_Pdf (year, month, table = 'timetable')
    [...]
    pdffile = '/media/hdb1/temp/Location.pdf'
    if os.path.exists(pdffile):
        os.remove(pdffile)
    pdf.output(pdffile, 'F')
    pdf.close()
    msg = QMessageBox()
    msg.setIcon(QMessageBox.Information)
    msg.setText("Pdf file is in /media/hdb1/temp/Location.pdf")
    msg.exec_()
    return

Traceback (most recent call last):
  File "../PycharmProjects/SecondOne/index.py", line 333, in MakePdf
    Create_Pdf(year, month)
  File "../PycharmProjects/SecondOne/makepdfhour_data.py", line 86, in Create_Pdf
    pdf.output(pdffile, 'F')
  File ".../fpdf/fpdf.py", line 1065, in output
    self.close()
  File ".../fpdf/fpdf.py", line 246, in close
    self._enddoc()
  File ".../fpdf/fpdf.py", line 1637, in _enddoc
    self._putresources()
  File ".../fpdf/fpdf.py", line 1585, in _putresources
    self._putimages()
  File ".../fpdf/fpdf.py", line 1515, in _putimages
    del info['data']
KeyError: 'data'

Body:
Just add a constructor to your class like the below code and it will work.

def __init__(self):
    self.table = ''
    self.pdf = FPDF('L', 'mm', 'A4')
    self.pdf.alias_nb_pages()


问:
Dynamically getting the keys from a nested object
I have a 3 level object will be generated similar to how openApi works, at project install time, or as a first step at compile time.

```<code>const translations = {
    26: {
        ro: {
            test: 'test',
        },
        en: {
            lorem: 'test',
            test: 'test',
        },
    },
    32: {
        en: {
            test: 'test',
        },
    },
};
</code>```

The structure represents:

translations -> moduleID (dynamic) -> language (dynamic based on some other settings) ->
dynamic based on moduleID

Later in my code we want:

```<code>const lang = 'en'
function getModuleTranslations<K extends keyof typeof x, T extends keyof typeof x[K][lang]>(mid: K): (key: T) => any {
        return (key) => x[mid][lang][key];
    }

....

const translate = getModuleTranslations(32);  // We want type checking & autocomplete here
const testString = translate('test'); // We want type checking & autocomplete here as well based on the above getModuleTranslations(32)

</code>```

In our case, the language param will be given by the class, at runtime.

I found multiple ways of accessing nested properties this way (translations, '32.en.test'), but this isn't what we want.

答:
Would it work for you to add an intermediate function call to go from the module to the language within that module? If so, this will work:

const translations = {
  26: {
    ro: {
      test: "test",
    },
    en: {
      lorem: "test",
      test: "test",
    },
  },
  32: {
    en: {
      test: "test",
    },
  },
} as const;

function getModuleTranslations(mid: keyof typeof translations) {
  const m = translations[mid];

  return (lang: keyof typeof m) => {
    const l = m[lang];

    return (key: keyof typeof l) => {
      return l[key];
    };
  };
}

const getLanguageTranslations = getModuleTranslations(32);
const translate = getLanguageTranslations("en");

const translateTest = translate("test");
console.log(translateTest);

// Argument of type '"not there"' is not assignable to parameter of type '"test"'.
const translateNotThere = translate("not there");
console.log(translateNotThere);
```

TS Playground

Body:
I have a 3 level object will be generated similar to how openApi works, at project install time, or as a first step at compile time.

const translations = {
    26: {
        ro: {
            test: 'test',
        },
        en: {
            lorem: 'test',
            test: 'test',
        },
    },
    32: {
        en: {
            test: 'test',
        },
    },
};

The structure represents:

translations -> moduleID (dynamic) -> language (dynamic based on some other settings) ->
dynamic based on moduleID

Later in my code we want:

const lang = 'en'
function getModuleTranslations<K extends keyof typeof x, T extends keyof typeof x[K][lang]>(mid: K): (key: T) => any {
        return (key) => x[mid][lang][key];
    }

....

const translate = getModuleTranslations(32);  // We want type checking & autocomplete here
const testString = translate('test'); // We want type checking & autocomplete here as well based on the above getModuleTranslations(32)

In our case, the language param will be given by the class, at runtime.

I found multiple ways of accessing nested properties this way (translations, '32.en.test'), but this isn't what we want.

Body:
Would it work for you to add an intermediate function call to go from the module to the language within that module? If so, this will work:

const translations = {
  26: {
    ro: {
      test: "test",
    },
    en: {
      lorem: "test",
      test: "test",
    },
  },
  32: {
    en: {
      test: "test",
    },
  },
} as const;

function getModuleTranslations(mid: keyof typeof translations) {
  const m = translations[mid];

  return (lang: keyof typeof m) => {
    const l = m[lang];

    return (key: keyof typeof l) => {
      return l[key];
    };
  };
}

const getLanguageTranslations = getModuleTranslations(32);
const translate = getLanguageTranslations("en");

const translateTest = translate("test");
console.log(translateTest);

// Argument of type '"not there"' is not assignable to parameter of type '"test"'.
const translateNotThere = translate("not there");
console.log(translateNotThere);

<a href="https://www.typescriptlang.org/play?#code/MYewdgzgLgBFBOBDSAbRUCW4IwLwwG8AoGGAJgDYAuQk0meEG4++qAU2hoCIPpuANHVIBfIa3Zhmw+ihDx2AWx58ogmaVUrOa8fTF0DpAMxlpEqbVaad2-ntF6DImIhyhIUANxEiAMwBXMGBMcBgAc3YoAFkQABMAlHYAFSRUdCxIAApFDDiaAGt2AE8QPzhigAd2Mrg0iDRQyABKKxgPaBhFPDrkBozsAG1cuIBdHzoFKAD4MBgstDBwwpLaqCqa8sVW3AA+NtIO2BQexUHF8PHfVimZuayi4pXS8vXq2pQd-ZZrW9mYFCDR5XVgiHyiHwiXxHCJRAAyyHCAUQkVSfUamRw+EiMXiiRS9Qx2CypmaPhhCHR6HYPRxCKWyNRhIG2W4km4ZOh2FglPSHGSOh6vP6HCyvB0HPJ2BASQAdHJwllhY0UjpOUQAPQamAAQXgSMUklgaw2MAA5NwwCAeQALdgKbhmmAYHBW2BuCAYcJgRAAIyScBAMEqiCQho48BgJuq5vF-DNsqIFOZHAActbknaFEKU+wxW64Fn2JKk9K5Qqlbn01BM-b2GSgA" rel="nofollow noreferrer">TS Playground


问:
How to change bitmap from VCL.Graphics.TBitmap to FMX.Graphics.TBitmap
I'm trying to show an image taken with a camera on a multi-device form with paintbox after processing it with opencv. However, cvImage2Bitmap returns VCL.Graphics.TBitmap. So I need to convert this to FMX.Graphics.TBitmap.

unit xml_cam2;

interface

uses
  System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
  FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, VCL.Graphics, FMX.Dialogs, FMX.ScrollBox,
  FMX.Memo, FMX.Objects, FMX.Controls.Presentation, FMX.StdCtrls,
  ocv.highgui_c,
  ocv.core_c,
  ocv.core.types_c,
  ocv.imgproc_c,
  ocv.imgproc.types_c,
  ocv.utils;

type
  TForm1 = class(TForm)
    Button1: TButton;
    OpenDialog1: TOpenDialog;
    PaintBox1: TPaintBox;
    Memo1: TMemo;
    procedure PaintBox1Paint(Sender: TObject; Canvas: TCanvas);
    procedure FormCreate(Sender: TObject);
  private
    capture: pCvCapture;
    frame: pIplImage;
    procedure OnIdle(Sender: TObject; var Done: Boolean);
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

var
  Bitmap, PaintBoxBitmap: FMX.Graphics.TBitmap;

{$R *.fmx}

procedure TForm1.FormCreate(Sender: TObject);
begin
  capture := cvCreateCameraCapture(CV_CAP_ANY);
  if Assigned(capture) then
    Application.OnIdle := OnIdle;
end;

procedure TForm1.OnIdle(Sender: TObject; var Done: Boolean);
begin
  if Assigned(capture) then
  begin
    frame := cvQueryFrame(capture);
    if Assigned(frame) then
    begin
      Bitmap := cvImage2Bitmap(frame);
      //cvImage2Bitmap returns VCL.Graphics.TBitmap
    end;
  end;

  Memo1.Lines.Add(IntToStr(Bitmap.Width));
  Memo1.Lines.Add(IntToStr(Bitmap.Height));

  if (PaintBoxBitmap = nil) then
    PaintBoxBitmap := FMX.Graphics.TBitmap.Create;
  PaintBoxBitmap.Assign(Bitmap);
  Invalidate;
  Bitmap.Free;
end;

procedure TForm1.PaintBox1Paint(Sender: TObject; Canvas: TCanvas);
begin
  if Assigned(PaintBoxBitmap) then
    PaintBox1.Canvas.DrawBitmap(PaintBoxBitmap, PaintBox1.ClipRect, PaintBox1.ClipRect, 1);
    Memo1.Lines.Add('b');
end;

end.
```

If you know any other efficient way to show iplimage to paintbox, please let us know.

答:
There are a couple of ways to do this. One way is to write the VCL bitmap to a TStream and then read it into the FMX bitmap. However, you can't convert the other way like that and it may be quite slow. I prefer to use Scanlines to convert between one and the other. In my code below I'm using 24 bit VCL bitmaps because I've found that the Windows API prefers these (AVIFile32 for example). Both bitmaps need to be created before calling the procedures. Of course you need to be creating an FMX application for Windows and include VCL.Graphics in your uses. Any transparency in the FMX bitmap will be lost when converting to a 24 bit VCL bitmap.

Convert 24 bit VCL bitmap to FMX bitmap

```<code>procedure VCLtoFMX_Bitmap(const VCLBmp : VCL.Graphics.TBitmap ; out FMXBmp : FMX.Graphics.TBitmap);
var
  bData : TBitmapData;
  x, y : Integer;
  pfmxbyte, pvclbyte : PByte;
begin
  VCLBmp.PixelFormat := pf24bit;
  FMXBmp.SetSize(VCLBmp.Width, VCLBmp.Height);
  FMXBmp.Map(TMapAccess.ReadWrite, bdata);

  try
    for y := 0 to FMXBmp.Height - 1 do begin
      pfmxbyte := bdata.GetScanline(y);
      pvclbyte := VCLBmp.Scanline[y];
      for x := 0 to FMXBmp.Width - 1 do begin
        pfmxbyte^ := pvclbyte^; Inc(pvclbyte); Inc(pfmxbyte);
        pfmxbyte^ := pvclbyte^; Inc(pvclbyte); Inc(pfmxbyte);
        pfmxbyte^ := pvclbyte^; Inc(pvclbyte); Inc(pfmxbyte);
        pfmxbyte^ := $FF; Inc(pfmxbyte); // Full opacity
      end;
    end;
  finally
    FMXBmp.Unmap(bdata);
  end;
end;
</code>```

Convert FMX bitmap to 24 bit VCL bitmap

```<code>procedure FMXtoVCL_Bitmap(const FMXBmp : FMX.Graphics.TBitmap ; out VCLBmp : VCL.Graphics.TBitmap);
var
  bData : TBitmapData;
  x, y : Integer;
  pfmxbyte, pvclbyte : PByte;
begin
  VCLBmp.PixelFormat := pf24bit;
  VCLBmp.SetSize(FMXBmp.Width, FMXBmp.Height);
  FMXBmp.Map(TMapAccess.Read, bdata);

  try
    for y := 0 to FMXBmp.Height - 1 do begin
      pfmxbyte := bdata.GetScanline(y);
      pvclbyte := VCLBmp.Scanline[y];
      for x := 0 to FMXBmp.Width - 1 do begin
        pvclbyte^ := pfmxbyte^; Inc(pvclbyte); Inc(pfmxbyte);
        pvclbyte^ := pfmxbyte^; Inc(pvclbyte); Inc(pfmxbyte);
        pvclbyte^ := pfmxbyte^; Inc(pvclbyte); Inc(pfmxbyte, 2);
      end;
    end;
  finally
    FMXBmp.Unmap(bdata);
  end;
end;
</code>```

Body:
I'm trying to show an image taken with a camera on a multi-device form with paintbox after processing it with opencv. However, cvImage2Bitmap returns VCL.Graphics.TBitmap. So I need to convert this to FMX.Graphics.TBitmap.

unit xml_cam2;

interface

uses
  System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
  FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, VCL.Graphics, FMX.Dialogs, FMX.ScrollBox,
  FMX.Memo, FMX.Objects, FMX.Controls.Presentation, FMX.StdCtrls,
  ocv.highgui_c,
  ocv.core_c,
  ocv.core.types_c,
  ocv.imgproc_c,
  ocv.imgproc.types_c,
  ocv.utils;

type
  TForm1 = class(TForm)
    Button1: TButton;
    OpenDialog1: TOpenDialog;
    PaintBox1: TPaintBox;
    Memo1: TMemo;
    procedure PaintBox1Paint(Sender: TObject; Canvas: TCanvas);
    procedure FormCreate(Sender: TObject);
  private
    capture: pCvCapture;
    frame: pIplImage;
    procedure OnIdle(Sender: TObject; var Done: Boolean);
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

var
  Bitmap, PaintBoxBitmap: FMX.Graphics.TBitmap;

{$R *.fmx}

procedure TForm1.FormCreate(Sender: TObject);
begin
  capture := cvCreateCameraCapture(CV_CAP_ANY);
  if Assigned(capture) then
    Application.OnIdle := OnIdle;
end;

procedure TForm1.OnIdle(Sender: TObject; var Done: Boolean);
begin
  if Assigned(capture) then
  begin
    frame := cvQueryFrame(capture);
    if Assigned(frame) then
    begin
      Bitmap := cvImage2Bitmap(frame);
      //cvImage2Bitmap returns VCL.Graphics.TBitmap
    end;
  end;

  Memo1.Lines.Add(IntToStr(Bitmap.Width));
  Memo1.Lines.Add(IntToStr(Bitmap.Height));

  if (PaintBoxBitmap = nil) then
    PaintBoxBitmap := FMX.Graphics.TBitmap.Create;
  PaintBoxBitmap.Assign(Bitmap);
  Invalidate;
  Bitmap.Free;
end;

procedure TForm1.PaintBox1Paint(Sender: TObject; Canvas: TCanvas);
begin
  if Assigned(PaintBoxBitmap) then
    PaintBox1.Canvas.DrawBitmap(PaintBoxBitmap, PaintBox1.ClipRect, PaintBox1.ClipRect, 1);
    Memo1.Lines.Add('b');
end;

end.

If you know any other efficient way to show iplimage to paintbox, please let us know.

Body:
There are a couple of ways to do this. One way is to write the VCL bitmap to a TStream and then read it into the FMX bitmap. However, you can't convert the other way like that and it may be quite slow. I prefer to use Scanlines to convert between one and the other. In my code below I'm using 24 bit VCL bitmaps because I've found that the Windows API prefers these (AVIFile32 for example). Both bitmaps need to be created before calling the procedures. Of course you need to be creating an FMX application for Windows and include VCL.Graphics in your uses. Any transparency in the FMX bitmap will be lost when converting to a 24 bit VCL bitmap.

Convert 24 bit VCL bitmap to FMX bitmap

procedure VCLtoFMX_Bitmap(const VCLBmp : VCL.Graphics.TBitmap ; out FMXBmp : FMX.Graphics.TBitmap);
var
  bData : TBitmapData;
  x, y : Integer;
  pfmxbyte, pvclbyte : PByte;
begin
  VCLBmp.PixelFormat := pf24bit;
  FMXBmp.SetSize(VCLBmp.Width, VCLBmp.Height);
  FMXBmp.Map(TMapAccess.ReadWrite, bdata);

  try
    for y := 0 to FMXBmp.Height - 1 do begin
      pfmxbyte := bdata.GetScanline(y);
      pvclbyte := VCLBmp.Scanline[y];
      for x := 0 to FMXBmp.Width - 1 do begin
        pfmxbyte^ := pvclbyte^; Inc(pvclbyte); Inc(pfmxbyte);
        pfmxbyte^ := pvclbyte^; Inc(pvclbyte); Inc(pfmxbyte);
        pfmxbyte^ := pvclbyte^; Inc(pvclbyte); Inc(pfmxbyte);
        pfmxbyte^ := $FF; Inc(pfmxbyte); // Full opacity
      end;
    end;
  finally
    FMXBmp.Unmap(bdata);
  end;
end;

Convert FMX bitmap to 24 bit VCL bitmap

procedure FMXtoVCL_Bitmap(const FMXBmp : FMX.Graphics.TBitmap ; out VCLBmp : VCL.Graphics.TBitmap);
var
  bData : TBitmapData;
  x, y : Integer;
  pfmxbyte, pvclbyte : PByte;
begin
  VCLBmp.PixelFormat := pf24bit;
  VCLBmp.SetSize(FMXBmp.Width, FMXBmp.Height);
  FMXBmp.Map(TMapAccess.Read, bdata);

  try
    for y := 0 to FMXBmp.Height - 1 do begin
      pfmxbyte := bdata.GetScanline(y);
      pvclbyte := VCLBmp.Scanline[y];
      for x := 0 to FMXBmp.Width - 1 do begin
        pvclbyte^ := pfmxbyte^; Inc(pvclbyte); Inc(pfmxbyte);
        pvclbyte^ := pfmxbyte^; Inc(pvclbyte); Inc(pfmxbyte);
        pvclbyte^ := pfmxbyte^; Inc(pvclbyte); Inc(pfmxbyte, 2);
      end;
    end;
  finally
    FMXBmp.Unmap(bdata);
  end;
end;


问:
Run gradle task and save its return value to shell script variable
Is there a way to run a gradle task and save it output to shell variable ?

For example lets consider a gradle task that prints module version :

```<code>task getVersion << {
    println '2.2.0'
}
</code>```

I run this task in the shell like this :

```<code>$./gradlew getVersion
</code>```

Is it possible to save output of gradle task getVersion into shell variable. For example:

```<code>VERSION=`./gradlew getVersion`
echo "Module Version is $VERSION"
</code>```

答:
If you are using the Kotlin DSL to write the task, you can do it without printing the newline. In your build.gradle.kts:

```<code>tasks.register("getVersion") {
    doLast {
        print(project.version)
    }
}
</code>```

And then you can execute from your terminal:

```<code>VERSION=$(./gradlew -q getVersion)
</code>```

Body:
Is there a way to run a gradle task and save it output to shell variable ?

For example lets consider a gradle task that prints module version :

task getVersion << {
    println '2.2.0'
}

I run this task in the shell like this :

$./gradlew getVersion

Is it possible to save output of gradle task getVersion into shell variable. For example:

VERSION=`./gradlew getVersion`
echo "Module Version is $VERSION"

Body:
If you are using the Kotlin DSL to write the task, you can do it without printing the newline. In your build.gradle.kts:

tasks.register("getVersion") {
    doLast {
        print(project.version)
    }
}

And then you can execute from your terminal:

VERSION=$(./gradlew -q getVersion)


问:
Missing data fields in Wikidata Query Service results despite items having these data
I am trying to retrieve some municipalities from Wikidata using SPARQL but several items returned have much of their fields empty despite these items having these data. I do not understand what is wrong with the query below (link to WQS). For example, the municipality Almelo has its coordinates (P625), and parent place (P131) erroneously missing in the results:

```<code>SELECT ?mun ?munLabel ?coords ?parentPlace ?area WHERE {
  ?mun p:P31 ?instanceOf # Get statement because we need this later
       .
  ?instanceOf ps:P31/wdt:279* wd:Q2039348.

  OPTIONAL {
    ?mun wdt:P625 ?coords;
      wdt:P131 ?parentPlace;
      wdt:P2046 ?area
      .
  }

  MINUS { ?instanceOf pq:P582 ?endTime. } # Don't show municipalities that have an end time

  service wikibase:label { bd:serviceParam wikibase:language "en". }
} ORDER BY ?munLabel
</code>```

答:
You have to declare OPTIONAL each statement independently:

```<code>  OPTIONAL { ?mun wdt:P625 ?coords . }
  OPTIONAL { ?mun wdt:P131 ?parentPlace . }
  OPTIONAL { ?mun wdt:P2046 ?area . }
</code>```

Otherwise, if one of them is missing, then the whole OPTIONAL block is ignored.

See also Multiple Optional Graph Patterns.

Body:
I am trying to retrieve some municipalities from Wikidata using SPARQL but several items returned have much of their fields empty despite these items having these data. I do not understand what is wrong with the query below (<a href="https://query.wikidata.org/#%20%20%20%20SELECT%20%3Fmun%20%3FmunLabel%20%3Fcoords%20%3FparentPlace%20%3Farea%20WHERE%20%7B%0A%20%20%20%20%20%20%3Fmun%20p%3AP31%20%3FinstanceOf%20%23%20Get%20statement%20because%20we%20need%20this%20later%0A%20%20%20%20%20%20%20%20%20%20%20.%0A%20%20%20%20%20%20%3FinstanceOf%20ps%3AP31%2Fwdt%3A279%2A%20wd%3AQ2039348.%0A%20%20%20%20%20%20%0A%20%20%20%20%20%20OPTIONAL%20%7B%0A%20%20%20%20%20%20%20%20%3Fmun%20wdt%3AP625%20%3Fcoords%3B%0A%20%20%20%20%20%20%20%20%20%20wdt%3AP131%20%3FparentPlace%3B%20%0A%20%20%20%20%20%20%20%20%20%20wdt%3AP2046%20%3Farea%0A%20%20%20%20%20%20%20%20%20%20.%0A%20%20%20%20%20%20%7D%0A%20%20%20%20%20%20%0A%20%20%20%20%20%20MINUS%20%7B%20%3FinstanceOf%20pq%3AP582%20%3FendTime.%20%7D%20%23%20Don%27t%20show%20municipalities%20that%20have%20an%20end%20time%0A%20%20%20%20%20%20%0A%20%20%20%20%20%20service%20wikibase%3Alabel%20%7B%20bd%3AserviceParam%20wikibase%3Alanguage%20%22en%22.%20%7D%0A%20%20%20%20%7D%20ORDER%20BY%20%3FmunLabel" rel="nofollow noreferrer">link to WQS). For example, the municipality Almelo has its coordinates (P625), and parent place (P131) erroneously missing in the results:

SELECT ?mun ?munLabel ?coords ?parentPlace ?area WHERE {
  ?mun p:P31 ?instanceOf # Get statement because we need this later
       .
  ?instanceOf ps:P31/wdt:279* wd:Q2039348.

  OPTIONAL {
    ?mun wdt:P625 ?coords;
      wdt:P131 ?parentPlace;
      wdt:P2046 ?area
      .
  }

  MINUS { ?instanceOf pq:P582 ?endTime. } # Don't show municipalities that have an end time

  service wikibase:label { bd:serviceParam wikibase:language "en". }
} ORDER BY ?munLabel

Body:
You have to declare OPTIONAL each statement independently:

  OPTIONAL { ?mun wdt:P625 ?coords . }
  OPTIONAL { ?mun wdt:P131 ?parentPlace . }
  OPTIONAL { ?mun wdt:P2046 ?area . }

Otherwise, if one of them is missing, then the whole OPTIONAL block is ignored.

See also Multiple Optional Graph Patterns.


问:
How to remove "!" in a sentence except last?
I want to write a program that removes all exclamation points except those that are at the end of a sentence.

I have done this, to remove every exclamation point in a given sentence.

```<code>string = input("Enter a string with exclamation marks: ")

char = set('!')

if any((c in char) for c in string):
    print (string.replace('!', ''))
</code>```

So basically now, how I target the last that are after the last letter of a sentence?

答:
If you have more than one exclamation mark at the end of the sentence, then you need to count them first and use their length to reduce the original length of the sentence, as follows:`

```<code>Sentence = "!!!one! one two two! two!!! three! ! three one!!!"
length=len(Sentence)
c=0
for i in Sentence[::-1]:
  if(i=='!'):
    c+=1
  else:
    break
Sentence=Sentence[:(length-c)].replace('!','')+Sentence[(length-c):length]
</code>```

`

Body:
I want to write a program that removes all exclamation points except those that are at the end of a sentence.

I have done this, to remove every exclamation point in a given sentence.

string = input("Enter a string with exclamation marks: ")

char = set('!')

if any((c in char) for c in string):
    print (string.replace('!', ''))

So basically now, how I target the last that are after the last letter of a sentence?

Body:
If you have more than one exclamation mark at the end of the sentence, then you need to count them first and use their length to reduce the original length of the sentence, as follows:`

Sentence = "!!!one! one two two! two!!! three! ! three one!!!"
length=len(Sentence)
c=0
for i in Sentence[::-1]:
  if(i=='!'):
    c+=1
  else:
    break
Sentence=Sentence[:(length-c)].replace('!','')+Sentence[(length-c):length]

`


问:
serialize models method with parameter in django REST API error " Object of type method is not JSON serializable "
how to serialize a models function with parameter . ? when i try this get an error . like this :

raise TypeError(f'Object of type {o.class.name} '
TypeError: Object of type method is not JSON serializable

models.py

```<code>class Post(models.Model):
  title = models.CharField(max_length=150)

  def likes_exist(self,user):
        liked = ""
        for i in self.likes.all():
            if i.user == user:
                liked = liked

            else:
                liked = not liked
        return liked

class LikePost(models.Model):
  user = models.ForeignKey(Customer,on_delete=models.CASCADE,related_name='news_likes')
  post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='likes')
</code>```

views.py

```<code>@api_view(["POST"])
def post(request):
  id = request.data["id"]
  user = Customer.objects.filter(id=id)
  post_object = Post()
  post_object.likes_exist(user)
  return PostSerializer #something else
</code>```

Serializer.py

```<code>class PostSerializer(serializers.ModelSerializer):
  class Meta:
        model = Post
        fields  = ["title","likes_exist"]
</code>```

error:

```<code>        Traceback (most recent call last):
  File "/home/shamsucm/.local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/home/shamsucm/.local/lib/python3.8/site-packages/django/core/handlers/base.py", line 204, in _get_response
    response = response.render()
  File "/home/shamsucm/.local/lib/python3.8/site-packages/django/template/response.py", line 105, in render
    self.content = self.rendered_content
  File "/home/shamsucm/.local/lib/python3.8/site-packages/rest_framework/response.py", line 70, in rendered_content
    ret = renderer.render(self.data, accepted_media_type, context)
  File "/home/shamsucm/.local/lib/python3.8/site-packages/rest_framework/renderers.py", line 100, in render
    ret = json.dumps(
  File "/home/shamsucm/.local/lib/python3.8/site-packages/rest_framework/utils/json.py", line 25, in dumps
    return json.dumps(*args, **kwargs)
  File "/usr/lib/python3.8/json/__init__.py", line 234, in dumps
    return cls(
  File "/usr/lib/python3.8/json/encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/usr/lib/python3.8/json/encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "/home/shamsucm/.local/lib/python3.8/site-packages/rest_framework/utils/encoders.py", line 67, in default
    return super().default(obj)
  File "/usr/lib/python3.8/json/encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type method is not JSON serializable
</code>```

how to fix this error . ? why is this error ?

Thank you

答:
I think you should create liked variable globally in your Post model class
And in PostSerilaizer Meta class add liked field instead of likes_exist

Body:
how to serialize a models function with parameter . ? when i try this get an error . like this :

raise TypeError(f'Object of type {o.class.name} '
TypeError: Object of type method is not JSON serializable

models.py

class Post(models.Model):
  title = models.CharField(max_length=150)

  def likes_exist(self,user):
        liked = ""
        for i in self.likes.all():
            if i.user == user:
                liked = liked

            else:
                liked = not liked
        return liked

class LikePost(models.Model):
  user = models.ForeignKey(Customer,on_delete=models.CASCADE,related_name='news_likes')
  post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='likes')

views.py

@api_view(["POST"])
def post(request):
  id = request.data["id"]
  user = Customer.objects.filter(id=id)
  post_object = Post()
  post_object.likes_exist(user)
  return PostSerializer #something else

Serializer.py

class PostSerializer(serializers.ModelSerializer):
  class Meta:
        model = Post
        fields  = ["title","likes_exist"]

error:

        Traceback (most recent call last):
  File "/home/shamsucm/.local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/home/shamsucm/.local/lib/python3.8/site-packages/django/core/handlers/base.py", line 204, in _get_response
    response = response.render()
  File "/home/shamsucm/.local/lib/python3.8/site-packages/django/template/response.py", line 105, in render
    self.content = self.rendered_content
  File "/home/shamsucm/.local/lib/python3.8/site-packages/rest_framework/response.py", line 70, in rendered_content
    ret = renderer.render(self.data, accepted_media_type, context)
  File "/home/shamsucm/.local/lib/python3.8/site-packages/rest_framework/renderers.py", line 100, in render
    ret = json.dumps(
  File "/home/shamsucm/.local/lib/python3.8/site-packages/rest_framework/utils/json.py", line 25, in dumps
    return json.dumps(*args, **kwargs)
  File "/usr/lib/python3.8/json/__init__.py", line 234, in dumps
    return cls(
  File "/usr/lib/python3.8/json/encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/usr/lib/python3.8/json/encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "/home/shamsucm/.local/lib/python3.8/site-packages/rest_framework/utils/encoders.py", line 67, in default
    return super().default(obj)
  File "/usr/lib/python3.8/json/encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type method is not JSON serializable

how to fix this error . ? why is this error ?

Thank you


问:
how to get country code like(+91 ,+1 etc) using user's current location flutter
I'm working on flutter app and I have a text widget where I want to show user's current country code based on his location without any dropdown.
I'm getting value like "IN","US" using Locale, but I don't want it,
I need numeric country code like +91 (for India), +1 (for US) etc.
anyone help me please.</p>

答:
You can use these files countries.dart and country.dart

Get the user country code from http://ip-api.com/json with http package and then use it to get the country phone code from countryList:

```<code> Future<String> getCountryPhoneCode() async {
    var response = await http.get(Uri.parse('http://ip-api.com/json'));
    var jsonResponse = json.decode(response.body);
    final isoCode = jsonResponse['countryCode'];
    print("country code " + isoCode);
    return "+" +
        countryList
            .firstWhere((element) => element.isoCode == isoCode,
                orElse: () => countryList.first)
            .phoneCode;
  }

</code>```

I tested this and it works for me but you can improve it to avoid http exceptions

Body:
You can use these files countries.dart and country.dart

Get the user country code from http://ip-api.com/json with http package and then use it to get the country phone code from countryList:

 Future<String> getCountryPhoneCode() async {
    var response = await http.get(Uri.parse('http://ip-api.com/json'));
    var jsonResponse = json.decode(response.body);
    final isoCode = jsonResponse['countryCode'];
    print("country code " + isoCode);
    return "+" +
        countryList
            .firstWhere((element) => element.isoCode == isoCode,
                orElse: () => countryList.first)
            .phoneCode;
  }

I tested this and it works for me but you can improve it to avoid http exceptions


问:
How to update Dart on VS Code?
enter image description hereenter image description hereToday VS Code sent me an error:

Version 2.16.1 of the Dart SDK is available (you have 2.16.0). Some features of Dart Code may not work correctly with an old SDK.

Do I have to download it again as ZIP and add it to PATH for the update?

答: You can upgrade from Extensions from VScode

Title: How to update Dart on VS Code?


问:
Can't access form data in PHP
I'm not a novice, but I'm not an expert either; I'm a keen learner.

Problem (minimalised) - I have a basic form which posts a name to another page which is supposed to receive name and print name. Code of both forms is below.

Form:

```<code><?php
    echo "Hello, World!";
    echo "
        <form action='CFAcomments.php' method='POST'>
            <table style='width: 50%;' border='0'>
                <tbody>
                    <tr>
                        <td><label for='name'>name: </label></td>
                        <td><input type='Text' name='name' value='anon' /></td>
                    </tr>
                    <tr>
                        <td><input type='submit' name='send' value='Send' /></td>
                    </tr>
                </tbody>
            </table>
        </form>
    ";
?>
</code>```

Form Process:

```<code><?php
    echo "Hello, World 1!";
    echo "<br/>";
    var_dump($_POST);
    $name = $_POST("name");
    echo "Hello $name!";
?>
</code>```

Result:

```<code>Hello, World 1!
array(2) { ["name"]=> string(11) "anon" ["send"]=> string(4) "Send" }
</code>```

Problem:

Even though var_dump($_POST) shows data being sent, echo $name print nothing. Changing echo $name to echo "test" prints nothing too. The code seems to stop executing at $name = $_post("name");. If I remove this line echo "anything" works.

I've used PHP and forms for the last two years and never come across this. Any help would be appreciated.

答:
Array keys are referenced with square brackets, not parentheses.</p>

```<code>$name = $_POST("name");

// Should be
$name = $_POST["name"];
</code>```

Title: Can't access form data in PHP

Body:
I'm not a novice, but I'm not an expert either; I'm a keen learner.

Problem (minimalised) - I have a basic form which posts a name to another page which is supposed to receive name and print name. Code of both forms is below.

Form:

<?php
    echo "Hello, World!";
    echo "
        <form action='CFAcomments.php' method='POST'>

                        name:
                        <input type='Text' name='name' value='anon' />

                        <input type='submit' name='send' value='Send' />

        </form>
    ";
?>

Form Process:

<?php
    echo "Hello, World 1!";
    echo "
";
    var_dump($_POST);
    $name = $_POST("name");
    echo "Hello $name!";
?>

Result:

Hello, World 1!
array(2) { ["name"]=> string(11) "anon" ["send"]=> string(4) "Send" }

Problem:

Even though var_dump($_POST) shows data being sent, echo $name print nothing. Changing echo $name to echo "test" prints nothing too. The code seems to stop executing at $name = $_post("name");. If I remove this line echo "anything" works.

I've used PHP and forms for the last two years and never come across this. Any help would be appreciated.

Body:
Array keys are referenced with square brackets, not parentheses.

$name = $_POST("name");

// Should be
$name = $_POST["name"];


问:
.NET WMI - How to detect when a bitlocker device is unlocked
I have an specific application that must react (searching for a specific file on the device) each time a new USB volume is connected or disconnected to/from the system.

For normal unencrypted devices I managed just creating a watcher for new USB use the

```<code>  ManagementEventWatcher watcher = new ManagementEventWatcher();
  WqlEventQuery query = new WqlEventQuery("SELECT * FROM Win32_VolumeChangeEvent WHERE EventType = 2 or EventType = 3");
  watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);
  watcher.Query = query;
  watcher.Start();
</code>```

My problem is with bitlocker drives. The alert triggers but I need to wait until the user does introduce the correct password. How to deal with this wait is my main concern.

Could someone help me to fine tune the wql query so it only alerts for unencrypted volumes?
The idea is that right after the user introduces the bitlocker password, the watcher (with the fine tuned query) should trigger. So basically for my program the bitlocker becomes transparent.

答:
I know that is very late for you, but maybe can help someone in the future, i had the same problem (more or less) I wanted to know when the device is unlocked by Bitlocker, for put a FileSystemWatcher, and I had a idea for not using a continuos do while. When the device is pluged, is "easy" to know it with `            WqlEventQuery insertQuery = new WqlEventQuery(
"SELECT * FROM __InstanceCreationEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_USBHub'");

```<code>        insertWatcher = new ManagementEventWatcher(insertQuery);
        insertWatcher.EventArrived += new EventArrivedEventHandler(DeviceInsertedEvent);
        insertWatcher.Start();`
</code>```

But is not easy to know when the device is unlocked, but i saw when you unlock the device, that trigger all events WMI about CIM_DataFile and CIM_Directory, then you can use this like this: `            WqlEventQuery waitForBitlockerQuery = new WqlEventQuery(
"SELECT * From __InstanceCreationEvent WITHIN 5 Where TargetInstance ISA "CIM_Directory" And TargetInstance.Drive="" + driveUnit.Name.Replace("\", "") + "" And TargetInstance.Path = ''");
//Creamos un evento que cuando el dispotivo pueda, disparara el evento con el direcotrio raiz, y por tanto indicando que el file system ya tiene acceso al dispositivo (isReady = true)

```<code>        ManagementEventWatcher copyWatcher = new ManagementEventWatcher(waitForBitlockerQuery);
        copyWatcher.EventArrived += new EventArrivedEventHandler(DeviceStatusChanged);
        copyWatcher.Start();`
</code>```

And use the function DeviceStatusChanged for make whatever you want after the device is unlocked

Body:
I have an specific application that must react (searching for a specific file on the device) each time a new USB volume is connected or disconnected to/from the system.

For normal unencrypted devices I managed just creating a watcher for new USB use the

  ManagementEventWatcher watcher = new ManagementEventWatcher();
  WqlEventQuery query = new WqlEventQuery("SELECT * FROM Win32_VolumeChangeEvent WHERE EventType = 2 or EventType = 3");
  watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);
  watcher.Query = query;
  watcher.Start();

My problem is with bitlocker drives. The alert triggers but I need to wait until the user does introduce the correct password. How to deal with this wait is my main concern.

Could someone help me to fine tune the wql query so it only alerts for unencrypted volumes?
The idea is that right after the user introduces the bitlocker password, the watcher (with the fine tuned query) should trigger. So basically for my program the bitlocker becomes transparent.

Body:
I know that is very late for you, but maybe can help someone in the future, i had the same problem (more or less) I wanted to know when the device is unlocked by Bitlocker, for put a FileSystemWatcher, and I had a idea for not using a continuos do while. When the device is pluged, is "easy" to know it with `            WqlEventQuery insertQuery = new WqlEventQuery(
"SELECT * FROM __InstanceCreationEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_USBHub'");

        insertWatcher = new ManagementEventWatcher(insertQuery);
        insertWatcher.EventArrived += new EventArrivedEventHandler(DeviceInsertedEvent);
        insertWatcher.Start();`

But is not easy to know when the device is unlocked, but i saw when you unlock the device, that trigger all events WMI about CIM_DataFile and CIM_Directory, then you can use this like this: `            WqlEventQuery waitForBitlockerQuery = new WqlEventQuery(
"SELECT * From __InstanceCreationEvent WITHIN 5 Where TargetInstance ISA "CIM_Directory" And TargetInstance.Drive="" + driveUnit.Name.Replace("\", "") + "" And TargetInstance.Path = ''");
//Creamos un evento que cuando el dispotivo pueda, disparara el evento con el direcotrio raiz, y por tanto indicando que el file system ya tiene acceso al dispositivo (isReady = true)

        ManagementEventWatcher copyWatcher = new ManagementEventWatcher(waitForBitlockerQuery);
        copyWatcher.EventArrived += new EventArrivedEventHandler(DeviceStatusChanged);
        copyWatcher.Start();`

And use the function DeviceStatusChanged for make whatever you want after the device is unlocked


问:
How to design readiness and livness probe for Angular application
I have an angular application which is deployed on apache container running on Kubernetes. I wanted to setup liveness and readiness probe for pods but I am out of ideas .Any help would be appreciated.</p>

答:
Base on the link you provided, you can use the following as a start:</p>
```<code>apiVersion: v1
kind: Pod
...
spec:
  ...
  containers:
  - name: ...
    ...
    livenessProbe:
      tcpSocket:
        port: 80               # <-- live when your web server is running
      initialDelaySeconds: 5   # <-- wait 5s before starting to probe
      periodSeconds: 20        # <-- do this probe every 20 seconds
    readinessProbe:
      httpGet:
        path: /                # <-- ready to accept connection when your home page is serving
        port: 80
      initialDelaySeconds: 15
      periodSeconds: 10
      failureThreshold: 3      # <-- must not fail > 3 probes
</code>```

Body:
Base on the link you provided, you can use the following as a start:

apiVersion: v1
kind: Pod
...
spec:
  ...
  containers:
  - name: ...
    ...
    livenessProbe:
      tcpSocket:
        port: 80               # <-- live when your web server is running
      initialDelaySeconds: 5   # <-- wait 5s before starting to probe
      periodSeconds: 20        # <-- do this probe every 20 seconds
    readinessProbe:
      httpGet:
        path: /                # <-- ready to accept connection when your home page is serving
        port: 80
      initialDelaySeconds: 15
      periodSeconds: 10
      failureThreshold: 3      # <-- must not fail > 3 probes


问:
Im trying something with IF in Batch but is not working as im expecting
I need to do an script that looks for some text in a file and also look for a file itself in a %userprofile% path, and it works fine but when i tried to unify it so that instead of outputing 2 confirming messages only output 1, something is not going as expected, this is the code:

```<code>hostname > hstnm.txt
SET /p hstnm=<hstnm.txt
SET pccer=.filextension1
SET pcsip=.filextension2
SET fullhost=%hstnm%%pccer%
SET fullsip=%hstnm%%pcsip%
SET fullroute=%userprofile%\thepath\%fullhost%
SET siproute=%userprofile%\thepath\%fullsip%

FINDSTR /m "<Protocol>TLS</Protocol>" "%siproute%"
IF %errorlevel%==0 (
 SET siptest="true"
) ELSE (
 SET siptest="false"
)

IF EXIST "%fullroute%" (
 SET certest="true"
) ELSE (
 SET certest="false"
)

IF %siptest%=="true" & %certest%=="true" (
ECHO message if everything good
) ELSE (
ECHO message if something bad
)
pause
</code>```

The FINDSTR and the IF EXIST are working properly (if u swap SET for an ECHO it does display a message). The problem arrives at the part of using the %certest% and the %siproute%, it is doing nothing, just outputs this (if i quit the @echo off)

```<code>...
C:\path>IF EXIST "C:\Users\Administrador\Appdata\Roaming\Interactive Intelligence\PureCloud Softphone\certificates\sip\GSSES0401107C.grupogss.corp.cer" (SET certest="true" )  ELSE (SET certest="false" )
No se esperaba & en este momento.
C:\path>IF "true"=="true" & "true"=="true" (
C:\path>
</code>```

Help me please! thanks in advance.

答:
Sometimes we do not need to do parenthesized if's.

There is already a variable containing the hostname called %COMPUTERNAME% which you can use without having to create a temp file

Pre-set variables and only change them if the files do not exist instead of the if else statements.

nested if's do not use &. We simply put the next after the other. if one condition returns true, it will do the next, etc. if any condition fails, it will stop processing the rest of the line and continue to the next line:

```<code>@echo off
set "pccer=.filextension1"
set "pcsip=.filextension2"
set "fullhost=%COMPUTERNAME%%pccer%"
set "fullsip=%COMPUTERNAME%%pcsip%"
set "fullroute=%userprofile%\thepath\%fullhost%"
set "siproute=%userprofile%\thepath\%fullsip%"
set "siptest=false"
set "certest=false"

FINDSTR /m "<Protocol>TLS</Protocol>" "%siproute%"
if not errorlevel 1 set "siptest=true"
if exist "%fullroute%" set "certest=true"

if "%siptest%" == "true" if "%certest%" == "true" echo message if everything good & goto :done
echo message if something bad

:done
pause
</code>```

Body:
I need to do an script that looks for some text in a file and also look for a file itself in a %userprofile% path, and it works fine but when i tried to unify it so that instead of outputing 2 confirming messages only output 1, something is not going as expected, this is the code:

hostname > hstnm.txt
SET /p hstnm=<hstnm.txt
SET pccer=.filextension1
SET pcsip=.filextension2
SET fullhost=%hstnm%%pccer%
SET fullsip=%hstnm%%pcsip%
SET fullroute=%userprofile%\thepath\%fullhost%
SET siproute=%userprofile%\thepath\%fullsip%

FINDSTR /m "<Protocol>TLS</Protocol>" "%siproute%"
IF %errorlevel%==0 (
 SET siptest="true"
) ELSE (
 SET siptest="false"
)

IF EXIST "%fullroute%" (
 SET certest="true"
) ELSE (
 SET certest="false"
)

IF %siptest%=="true" & %certest%=="true" (
ECHO message if everything good
) ELSE (
ECHO message if something bad
)
pause

The FINDSTR and the IF EXIST are working properly (if u swap SET for an ECHO it does display a message). The problem arrives at the part of using the %certest% and the %siproute%, it is doing nothing, just outputs this (if i quit the @echo off)

...
C:\path>IF EXIST "C:\Users\Administrador\Appdata\Roaming\Interactive Intelligence\PureCloud Softphone\certificates\sip\GSSES0401107C.grupogss.corp.cer" (SET certest="true" )  ELSE (SET certest="false" )
No se esperaba & en este momento.
C:\path>IF "true"=="true" & "true"=="true" (
C:\path>

Help me please! thanks in advance.

Body:
Sometimes we do not need to do parenthesized if's.

There is already a variable containing the hostname called %COMPUTERNAME% which you can use without having to create a temp file

Pre-set variables and only change them if the files do not exist instead of the if else statements.

nested if's do not use &. We simply put the next after the other. if one condition returns true, it will do the next, etc. if any condition fails, it will stop processing the rest of the line and continue to the next line:

@echo off
set "pccer=.filextension1"
set "pcsip=.filextension2"
set "fullhost=%COMPUTERNAME%%pccer%"
set "fullsip=%COMPUTERNAME%%pcsip%"
set "fullroute=%userprofile%\thepath\%fullhost%"
set "siproute=%userprofile%\thepath\%fullsip%"
set "siptest=false"
set "certest=false"

FINDSTR /m "<Protocol>TLS</Protocol>" "%siproute%"
if not errorlevel 1 set "siptest=true"
if exist "%fullroute%" set "certest=true"

if "%siptest%" == "true" if "%certest%" == "true" echo message if everything good & goto :done
echo message if something bad

:done
pause


问:
local time doesnt save in local storage after page refresh
Im quite a newbie with coding

So i got the code below, the local time is being set correctly on the webpage and in local storage. However, after refreshing the time sets again and i dont need that. I was looking through several topics and couldnt find anything that fits my problem.
Tried document.write() etc, but didnt work

What could be the solution to this problem or what are the issues in my code that the time sets new after refresh?

const date = new Date().toLocaleTimeString();
document.getElementById('entryTime').textContent = date

localStorage.setItem('time', JSON.stringify(date));

if (localStorage.getItem("time")) {
  entryTime = JSON.parse(localStorage.getItem("time"));
} else {
  // No data, start with an empty array
  entryTime = [];
}
console.log(date);
document.getElementById('entryTime').innerHTML = date```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row" style="margin-top: 10px !important; margin-bottom: 1px !important; font-size: 30px;" id="entryTime"></div></code>```

答:
The first thing you do when the page loads is, unconditionally, to get the time and store it in Local Storage.

If you only want to set the time to LS when there isn't a time there already, try to read it first and only set it if it isn't set already.


问:
how to configure credentials at outlook.com connector in azure logic app
I have created outlook.com connector in an azure logic app using visual studio.
From the logic app designer, when i select outlook.com. It shows sign option, where i have signed in with emailid and password.
But, when i look at logic app.json file below values displayed under parameters. I dont see email and password.
I need these values to be configurable so that i can change the credentials on need basis.
How can we achieve this. appreciate if any one can help on this.</p>
```<code>"outlook_1_Connection_Name": {
  "type": "string",
  "defaultValue": "outlook"
},
"outlook_1_Connection_DisplayName": {
  "type": "string",
  "defaultValue": "Outlook.com"
}
</code>```

答: You cannot change the credentials from json file but you can directly change the connection by navigating to the outlook connector from your designer > Change Connection > Add new > Use Another account. Here are the screenshots for your reference -

Body:
I have created outlook.com connector in an azure logic app using visual studio.
From the logic app designer, when i select outlook.com. It shows sign option, where i have signed in with emailid and password.
But, when i look at logic app.json file below values displayed under parameters. I dont see email and password.
I need these values to be configurable so that i can change the credentials on need basis.
How can we achieve this. appreciate if any one can help on this.

"outlook_1_Connection_Name": {
  "type": "string",
  "defaultValue": "outlook"
},
"outlook_1_Connection_DisplayName": {
  "type": "string",
  "defaultValue": "Outlook.com"
}