问:
AWX docker: How to authenticate with Azure using Active Directory. Will not work for me
I've been banging my head for about a week now.

I have AWX running via docker-compose and setup on an EC2 instance.
My department does not have credentials to create Azure Service Principals so while I'm waiting on that request to go through I'm trying to get AWX to authenticate with Azure via active directory credentials. While testing, for simplicity, I have a test task setup that runs azure_rm_dnsrecordset_facts, so I can simply pull a TXT record to show that authentication is authenticating. On my development machine I can install azure cli, run az login and execute playbooks et al via ansible-playbook command, and it works: I can see the test pulls the expected TXT record. But on AWX I get errors.

Using az login and copying the files at /root/.azure/ to /var/lib/awx/.azure/ I get this error:

```<code>{
    "_ansible_parsed": false,
    "exception": "Traceback (most recent call last):\n  File \"/root/.ansible/tmp/ansible-tmp-1558728025.48-180262108746971/AnsiballZ_azure_rm_dnsrecordset_facts.py\", line 113, in <module>\n    _ansiballz_main()\n  File \"/root/.ansible/tmp/ansible-tmp-1558728025.48-180262108746971/AnsiballZ_azure_rm_dnsrecordset_facts.py\", line 105, in _ansiballz_main\n    invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\n  File \"/root/.ansible/tmp/ansible-tmp-1558728025.48-180262108746971/AnsiballZ_azure_rm_dnsrecordset_facts.py\", line 48, in invoke_module\n    imp.load_module('__main__', mod, module, MOD_DESC)\n  File \"/tmp/ansible_azure_rm_dnsrecordset_facts_payload_PlPfUW/__main__.py\", line 202, in <module>\n  File \"/tmp/ansible_azure_rm_dnsrecordset_facts_payload_PlPfUW/__main__.py\", line 198, in main\n  File \"/tmp/ansible_azure_rm_dnsrecordset_facts_payload_PlPfUW/__main__.py\", line 133, in __init__\n  File \"/tmp/ansible_azure_rm_dnsrecordset_facts_payload_PlPfUW/ansible_azure_rm_dnsrecordset_facts_payload.zip/ansible/module_utils/azure_rm_common.py\", line 301, in __init__\n  File \"/tmp/ansible_azure_rm_dnsrecordset_facts_payload_PlPfUW/ansible_azure_rm_dnsrecordset_facts_payload.zip/ansible/module_utils/azure_rm_common.py\", line 1045, in __init__\n  File \"/var/lib/awx/venv/ansible/lib/python2.7/site-packages/msrestazure/azure_active_directory.py\", line 383, in __init__\n    self.set_token()\n  File \"/var/lib/awx/venv/ansible/lib/python2.7/site-packages/msrestazure/azure_active_directory.py\", line 415, in set_token\n    raise_with_traceback(AuthenticationError, \"\", err)\n  File \"/var/lib/awx/venv/ansible/lib/python2.7/site-packages/msrest/exceptions.py\", line 48, in raise_with_traceback\n    raise error\nmsrest.exceptions.AuthenticationError: , InvalidGrantError: (invalid_grant) AADSTS50126: Invalid username or password.\r\nTrace ID: 01cd8ac6-1c05-4391-96da-031e0da30500\r\nCorrelation ID: 03f28850-04cf-4344-b405-18594d8845a1\r\nTimestamp: 2019-05-24 20:00:26Z\n",
    "_ansible_no_log": false,
    "module_stderr": "Traceback (most recent call last):\n  File \"/root/.ansible/tmp/ansible-tmp-1558728025.48-180262108746971/AnsiballZ_azure_rm_dnsrecordset_facts.py\", line 113, in <module>\n    _ansiballz_main()\n  File \"/root/.ansible/tmp/ansible-tmp-1558728025.48-180262108746971/AnsiballZ_azure_rm_dnsrecordset_facts.py\", line 105, in _ansiballz_main\n    invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\n  File \"/root/.ansible/tmp/ansible-tmp-1558728025.48-180262108746971/AnsiballZ_azure_rm_dnsrecordset_facts.py\", line 48, in invoke_module\n    imp.load_module('__main__', mod, module, MOD_DESC)\n  File \"/tmp/ansible_azure_rm_dnsrecordset_facts_payload_PlPfUW/__main__.py\", line 202, in <module>\n  File \"/tmp/ansible_azure_rm_dnsrecordset_facts_payload_PlPfUW/__main__.py\", line 198, in main\n  File \"/tmp/ansible_azure_rm_dnsrecordset_facts_payload_PlPfUW/__main__.py\", line 133, in __init__\n  File \"/tmp/ansible_azure_rm_dnsrecordset_facts_payload_PlPfUW/ansible_azure_rm_dnsrecordset_facts_payload.zip/ansible/module_utils/azure_rm_common.py\", line 301, in __init__\n  File \"/tmp/ansible_azure_rm_dnsrecordset_facts_payload_PlPfUW/ansible_azure_rm_dnsrecordset_facts_payload.zip/ansible/module_utils/azure_rm_common.py\", line 1045, in __init__\n  File \"/var/lib/awx/venv/ansible/lib/python2.7/site-packages/msrestazure/azure_active_directory.py\", line 383, in __init__\n    self.set_token()\n  File \"/var/lib/awx/venv/ansible/lib/python2.7/site-packages/msrestazure/azure_active_directory.py\", line 415, in set_token\n    raise_with_traceback(AuthenticationError, \"\", err)\n  File \"/var/lib/awx/venv/ansible/lib/python2.7/site-packages/msrest/exceptions.py\", line 48, in raise_with_traceback\n    raise error\nmsrest.exceptions.AuthenticationError: , **InvalidGrantError: (invalid_grant) AADSTS50126: Invalid username or password**.\r\nTrace ID: 01cd8ac6-1c05-4391-96da-031e0da30500\r\nCorrelation ID: 03f28850-04cf-4344-b405-18594d8845a1\r\nTimestamp: 2019-05-24 20:00:26Z\n",
    "changed": false,
    "module_stdout": "",
    "rc": 1,
    "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error"
}
</code>```

while using ad_username, password and subscription_id values as environment variables, extra vars and passed into the module from the vault all result in the same error:

```<code>{
    "_ansible_parsed": true,
    "_ansible_no_log": false,
    "invocation": {
        "module_args": {
            "profile": null,
            "resource_group": "publicdns**********",
            "tags": null,
            "cloud_environment": "AzureCloud",
            "relative_name": "_acme-challenge",
            "record_type": "TXT",
            "client_id": null,
            "api_profile": "latest",
            "adfs_authority_url": null,
            "zone_name": "*************",
            "password": null,
            "tenant": null,
            "top": "100",
            "append_tags": true,
            "ad_user": null,
            "cert_validation_mode": null,
            "secret": null,
            "auth_source": null,
            "subscription_id": null
        }
    },
    "changed": false,
    "msg": "**Failed to get credentials. Either pass as parameters, set environment variables, define a profile in ~/.azure/credentials, or log in with Azure CLI (`az login`)**."
}
</code>```

Is it just me or is this a bug? I can't find anything that explicitly walks you through setting this up, except what I've found reading through the docs. I expected this to be straight forward and so far it's been anything but.

Here are one of the docs I've followed most recently: https://docs.ansible.com/ansible-tower/3.2.6/html/userguide/credentials.html#microsoft-azure-resource-manager

Thanks for the help. Here is a list of things I've tried:

Setting environment variables for AZURE_AD_USER, AZURE_PASSWORD and AZURE_SUBSCRIPTION_ID in both awx_task and awx_web containers.

I have set ad_user, password and subscription_id credentials as as extra vars.

I have placed credentials in the vault and passed directly to the ansible module, with and without azure_adfs_authority_url.

In the awx_task docker container I have installed ansible[azure] and azure cli, run az login, verified the /root/.azure/azureProfile.json file is populated.

I have copied the files from /root/.azure/ to /var/lib/awx/.azure/ which is where it appears AWX is looking for these files. I've also verified read write access and file ownership.

I tinkered with the Microsoft Azure Resource Manager credential but it appears to not be what I want.

ON The EC2 instance, nslookup for the azure_adfs_authority_url shows that it is hitting the correct ADFS server.

Thanks for your help

答:
The error is "AADSTS50126 invalid username or password" so I would suggest you to double check and ensure that the username or password are correct for the managed domain to connect. If still issue persists then (AFAIK mostly authentication fails for federated Azure tenants so) give a try by resetting the password of the user and/or try by setting tenant_id / tenant as well. A similar issue is raised here which you may check for future updates.

Hope this helps!!

Body:
I've been banging my head for about a week now.

I have AWX running via docker-compose and setup on an EC2 instance.
My department does not have credentials to create Azure Service Principals so while I'm waiting on that request to go through I'm trying to get AWX to authenticate with Azure via active directory credentials. While testing, for simplicity, I have a test task setup that runs azure_rm_dnsrecordset_facts, so I can simply pull a TXT record to show that authentication is authenticating. On my development machine I can install azure cli, run az login and execute playbooks et al via ansible-playbook command, and it works: I can see the test pulls the expected TXT record. But on AWX I get errors.

Using az login and copying the files at /root/.azure/ to /var/lib/awx/.azure/ I get this error:

{
    "_ansible_parsed": false,
    "exception": "Traceback (most recent call last):\n  File \"/root/.ansible/tmp/ansible-tmp-1558728025.48-180262108746971/AnsiballZ_azure_rm_dnsrecordset_facts.py\", line 113, in <module>\n    _ansiballz_main()\n  File \"/root/.ansible/tmp/ansible-tmp-1558728025.48-180262108746971/AnsiballZ_azure_rm_dnsrecordset_facts.py\", line 105, in _ansiballz_main\n    invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\n  File \"/root/.ansible/tmp/ansible-tmp-1558728025.48-180262108746971/AnsiballZ_azure_rm_dnsrecordset_facts.py\", line 48, in invoke_module\n    imp.load_module('__main__', mod, module, MOD_DESC)\n  File \"/tmp/ansible_azure_rm_dnsrecordset_facts_payload_PlPfUW/__main__.py\", line 202, in <module>\n  File \"/tmp/ansible_azure_rm_dnsrecordset_facts_payload_PlPfUW/__main__.py\", line 198, in main\n  File \"/tmp/ansible_azure_rm_dnsrecordset_facts_payload_PlPfUW/__main__.py\", line 133, in __init__\n  File \"/tmp/ansible_azure_rm_dnsrecordset_facts_payload_PlPfUW/ansible_azure_rm_dnsrecordset_facts_payload.zip/ansible/module_utils/azure_rm_common.py\", line 301, in __init__\n  File \"/tmp/ansible_azure_rm_dnsrecordset_facts_payload_PlPfUW/ansible_azure_rm_dnsrecordset_facts_payload.zip/ansible/module_utils/azure_rm_common.py\", line 1045, in __init__\n  File \"/var/lib/awx/venv/ansible/lib/python2.7/site-packages/msrestazure/azure_active_directory.py\", line 383, in __init__\n    self.set_token()\n  File \"/var/lib/awx/venv/ansible/lib/python2.7/site-packages/msrestazure/azure_active_directory.py\", line 415, in set_token\n    raise_with_traceback(AuthenticationError, \"\", err)\n  File \"/var/lib/awx/venv/ansible/lib/python2.7/site-packages/msrest/exceptions.py\", line 48, in raise_with_traceback\n    raise error\nmsrest.exceptions.AuthenticationError: , InvalidGrantError: (invalid_grant) AADSTS50126: Invalid username or password.\r\nTrace ID: 01cd8ac6-1c05-4391-96da-031e0da30500\r\nCorrelation ID: 03f28850-04cf-4344-b405-18594d8845a1\r\nTimestamp: 2019-05-24 20:00:26Z\n",
    "_ansible_no_log": false,
    "module_stderr": "Traceback (most recent call last):\n  File \"/root/.ansible/tmp/ansible-tmp-1558728025.48-180262108746971/AnsiballZ_azure_rm_dnsrecordset_facts.py\", line 113, in <module>\n    _ansiballz_main()\n  File \"/root/.ansible/tmp/ansible-tmp-1558728025.48-180262108746971/AnsiballZ_azure_rm_dnsrecordset_facts.py\", line 105, in _ansiballz_main\n    invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\n  File \"/root/.ansible/tmp/ansible-tmp-1558728025.48-180262108746971/AnsiballZ_azure_rm_dnsrecordset_facts.py\", line 48, in invoke_module\n    imp.load_module('__main__', mod, module, MOD_DESC)\n  File \"/tmp/ansible_azure_rm_dnsrecordset_facts_payload_PlPfUW/__main__.py\", line 202, in <module>\n  File \"/tmp/ansible_azure_rm_dnsrecordset_facts_payload_PlPfUW/__main__.py\", line 198, in main\n  File \"/tmp/ansible_azure_rm_dnsrecordset_facts_payload_PlPfUW/__main__.py\", line 133, in __init__\n  File \"/tmp/ansible_azure_rm_dnsrecordset_facts_payload_PlPfUW/ansible_azure_rm_dnsrecordset_facts_payload.zip/ansible/module_utils/azure_rm_common.py\", line 301, in __init__\n  File \"/tmp/ansible_azure_rm_dnsrecordset_facts_payload_PlPfUW/ansible_azure_rm_dnsrecordset_facts_payload.zip/ansible/module_utils/azure_rm_common.py\", line 1045, in __init__\n  File \"/var/lib/awx/venv/ansible/lib/python2.7/site-packages/msrestazure/azure_active_directory.py\", line 383, in __init__\n    self.set_token()\n  File \"/var/lib/awx/venv/ansible/lib/python2.7/site-packages/msrestazure/azure_active_directory.py\", line 415, in set_token\n    raise_with_traceback(AuthenticationError, \"\", err)\n  File \"/var/lib/awx/venv/ansible/lib/python2.7/site-packages/msrest/exceptions.py\", line 48, in raise_with_traceback\n    raise error\nmsrest.exceptions.AuthenticationError: , **InvalidGrantError: (invalid_grant) AADSTS50126: Invalid username or password**.\r\nTrace ID: 01cd8ac6-1c05-4391-96da-031e0da30500\r\nCorrelation ID: 03f28850-04cf-4344-b405-18594d8845a1\r\nTimestamp: 2019-05-24 20:00:26Z\n",
    "changed": false,
    "module_stdout": "",
    "rc": 1,
    "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error"
}

while using ad_username, password and subscription_id values as environment variables, extra vars and passed into the module from the vault all result in the same error:

{
    "_ansible_parsed": true,
    "_ansible_no_log": false,
    "invocation": {
        "module_args": {
            "profile": null,
            "resource_group": "publicdns**********",
            "tags": null,
            "cloud_environment": "AzureCloud",
            "relative_name": "_acme-challenge",
            "record_type": "TXT",
            "client_id": null,
            "api_profile": "latest",
            "adfs_authority_url": null,
            "zone_name": "*************",
            "password": null,
            "tenant": null,
            "top": "100",
            "append_tags": true,
            "ad_user": null,
            "cert_validation_mode": null,
            "secret": null,
            "auth_source": null,
            "subscription_id": null
        }
    },
    "changed": false,
    "msg": "**Failed to get credentials. Either pass as parameters, set environment variables, define a profile in ~/.azure/credentials, or log in with Azure CLI (`az login`)**."
}

Is it just me or is this a bug? I can't find anything that explicitly walks you through setting this up, except what I've found reading through the docs. I expected this to be straight forward and so far it's been anything but.

Here are one of the docs I've followed most recently: https://docs.ansible.com/ansible-tower/3.2.6/html/userguide/credentials.html#microsoft-azure-resource-manager

Thanks for the help. Here is a list of things I've tried:

Setting environment variables for AZURE_AD_USER, AZURE_PASSWORD and AZURE_SUBSCRIPTION_ID in both awx_task and awx_web containers.

I have set ad_user, password and subscription_id credentials as as extra vars.

I have placed credentials in the vault and passed directly to the ansible module, with and without azure_adfs_authority_url.

In the awx_task docker container I have installed ansible[azure] and azure cli, run az login, verified the /root/.azure/azureProfile.json file is populated.

I have copied the files from /root/.azure/ to /var/lib/awx/.azure/ which is where it appears AWX is looking for these files. I've also verified read write access and file ownership.

I tinkered with the Microsoft Azure Resource Manager credential but it appears to not be what I want.

ON The EC2 instance, nslookup for the azure_adfs_authority_url shows that it is hitting the correct ADFS server.

Thanks for your help


来源: stackexchange

问:
Undefined method uploading apk with Fastlane
I'm getting an error on gitlab ci server deploying/uploading an apk to Fabric with Fastlane. The strange thing is that it is working if I run the task from my local. The Fastlane is the same version in both cases 2.123.0.

The method of the task that is failing is:

```<code>31 desc "Generate QA release notes"
32 private_lane :qa_release_notes do
33 commit = last_git_commit
34 short_hash = commit[:abbreviated_commit_hash]
35 author = commit[:author]
36 message = commit[:message]
37 "Release notes of commit " + short_hash + " by " + author +":\n " + message
38 end
</code>```

And the error printed in the ci log is:

```<code>[15:43:34]: Error in your Fastfile at line 34
[15:43:34]: 32:  private_lane :qa_release_notes do
[15:43:34]: 33:  commit = last_git_commit
[15:43:34]: => 34:   short_hash = commit[:abbreviated_commit_hash]
[15:43:34]: 35:  author = commit[:author]
[15:43:34]: 36:  message = commit[:message]
</code>```

(...)

```<code>Fastfile:34:in block (2 levels) in parsing_binding': [!] undefined method []' for nil:NilClass (NoMethodError)
    from /var/lib/gems/2.3.0/gems/fastlane-2.123.0/fastlane/lib/fastlane/lane.rb:33:in `call'
</code>```

It seems the problem is with the method commit[:abbreviated_commit_hash]
But I don't know what the problem is...Any idea?

答: The error was the last_git_commit was getting an empty result (as @janpio said here) because for some reason the git was missing in the Docker image.

ContentLicense: CC BY-SA 4.0

Body:
I'm getting an error on gitlab ci server deploying/uploading an apk to Fabric with Fastlane. The strange thing is that it is working if I run the task from my local. The Fastlane is the same version in both cases 2.123.0.

The method of the task that is failing is:

31 desc "Generate QA release notes"
32 private_lane :qa_release_notes do
33 commit = last_git_commit
34 short_hash = commit[:abbreviated_commit_hash]
35 author = commit[:author]
36 message = commit[:message]
37 "Release notes of commit " + short_hash + " by " + author +":\n " + message
38 end

And the error printed in the ci log is:

[15:43:34]: Error in your Fastfile at line 34
[15:43:34]: 32:  private_lane :qa_release_notes do
[15:43:34]: 33:  commit = last_git_commit
[15:43:34]: => 34:   short_hash = commit[:abbreviated_commit_hash]
[15:43:34]: 35:  author = commit[:author]
[15:43:34]: 36:  message = commit[:message]

(...)

Fastfile:34:in block (2 levels) in parsing_binding': [!] undefined method []' for nil:NilClass (NoMethodError)
    from /var/lib/gems/2.3.0/gems/fastlane-2.123.0/fastlane/lib/fastlane/lane.rb:33:in `call'

It seems the problem is with the method commit[:abbreviated_commit_hash]
But I don't know what the problem is...Any idea?


问:
Matcher.Find() returns false when it should be true
```<code>        String s = "test";
        Pattern pattern = Pattern.compile("\\n((\\w+\\s*[^\\n]){0,2})(\\b" + s + "\\b\\s)((\\w+\\s*){0,2})\\n?");
        Matcher matcher = pattern.matcher(searchableText);
        boolean topicTitleFound = matcher.find();
        startIndex = 0;
        while (topicTitleFound) {
            int i = searchableText.indexOf(matcher.group(0));
            if (i > startIndex) {
                builder.append(documentText.substring(startIndex, i - 1));
        ...
</code>```

This is the text that I tacle:

Some text comes here

  topicTitle test :

test1 : testing123

test2 : testing456

test3 : testing789

test4 : testing9097

When I'm testing this regex on http://regexpal.com/ or http://www.regexplanet.com I clearly find the title that is saying: "topicTitle test". But in my java code topicTitleFound returns false.

Please help

答:
It could be that you have carriage-return characters ('\r') before the newline characters ('\n') in your searchableText. This would cause the match to fail at line boundaries.

To make your multi-line pattern more robust, try using the MULTILINE option when compiling the regex. Then use ^ and $ as needed to match line boundaries.

```<code>Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
</code>```

Update:

After actually testing out your code, I see that the pattern matches whether carriage-returns are present or not. In other words, your code "works" as-is, and topicTitleFound is true when it is first assigned (outside the while loop).

Are you sure that you are getting false for topicTitleFound? Or is the problem in the loop?

By the way, the use of indexOf() is wasteful and awkward, since the matcher already stores the index at which group 0 begins. Use this instead:

```<code>int i = matcher.start(0);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
        String s = "test";
        Pattern pattern = Pattern.compile("\\n((\\w+\\s*[^\\n]){0,2})(\\b" + s + "\\b\\s)((\\w+\\s*){0,2})\\n?");
        Matcher matcher = pattern.matcher(searchableText);
        boolean topicTitleFound = matcher.find();
        startIndex = 0;
        while (topicTitleFound) {
            int i = searchableText.indexOf(matcher.group(0));
            if (i > startIndex) {
                builder.append(documentText.substring(startIndex, i - 1));
        ...

This is the text that I tacle:

Some text comes here

  topicTitle test :

test1 : testing123

test2 : testing456

test3 : testing789

test4 : testing9097

When I'm testing this regex on http://regexpal.com/ or http://www.regexplanet.com I clearly find the title that is saying: "topicTitle test". But in my java code topicTitleFound returns false.

Please help

Body:
It could be that you have carriage-return characters ('\r') before the newline characters ('\n') in your searchableText. This would cause the match to fail at line boundaries.

To make your multi-line pattern more robust, try using the MULTILINE option when compiling the regex. Then use ^ and $ as needed to match line boundaries.

Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);

Update:

After actually testing out your code, I see that the pattern matches whether carriage-returns are present or not. In other words, your code "works" as-is, and topicTitleFound is true when it is first assigned (outside the while loop).

Are you sure that you are getting false for topicTitleFound? Or is the problem in the loop?

By the way, the use of indexOf() is wasteful and awkward, since the matcher already stores the index at which group 0 begins. Use this instead:

int i = matcher.start(0);


问:
Comparing value of an object with null
The null literal can only be assigned to reference variables, and usually, we use the .equals() method in comparing with them

Why do we use the operators "equal to" and "not equal to" instead of the .equals() method if dealing with null?

答:
Method "equals()" is an instance method, and to call any instance method , you need a non null object reference. So calling equals() with null reference will result in NPE.

If the method is static, then you can invoke that method with null reference too as static method is not bound to any instance.

Title: Comparing value of an object with null


问:
Retrieving data from an API using Blazor. Data not being pulled
Using ASP.net Core 3.0 and Blazor. I am modifying the project found here: https://ankitsharmablogs.com/asp-net-core-crud-using-blazor-and-entity-framework-core/

I used Scofold-DbContext to build my Context file and the Model class. VS had no issue contacting the Database to create the required files.

Razor View:

```<code>@using ShopLive1.Shared.Models
@page "/fetchemployees"
@inject  HttpClient Http

<h1>Shop Live - Repair Order Update</h1>

@if(roList == null)
{
    <p><em>Loading....</em></p>
}
else
{
    <table class="table">
        <thead>
            <tr>
                <th>Control Number</th>
                <th>VIN</th>
                <th>Make</th>
                <th>Model</th>
                <th>Customer</th>
                <th>Repair Stage</th>
                <th>Location</th>
                <th>Assigned</th>
            </tr>
        </thead>
        <tbody>
            @foreach(var ro in roList)
            {
                <tr>
                    <td>@ro.ControlNumber</td>
                    <td>@ro.Vin</td>
                    <td>@ro.Make</td>
                    <td>@ro.Model</td>
                    <td>@ro.Customer</td>
                    <td>@ro.Stage</td>
                    <td>@ro.VehicleLocation</td>
                    <td>@ro.Technician</td>
                </tr>
            }
        </tbody>
    </table>
}

@functions{
    RepairOrder[] roList;

    protected override async Task OnInitAsync()
    {
        roList = await Http.GetJsonAsync<RepairOrder[]>("api/RepairOrder/Index");
    }
}
</code>```

Data Access layer class:

```<code>ShopLiveContext db = new ShopLiveContext();

        //To get all repair orders
        public List<RepairOrder> GetAllRepairOrders()
        {
            try
            {
                return db.RepairOrder.ToList();
            }
            catch
            {
                throw;
            }

        }

        //To add new Repair Orders
        public void AddRepairOrder(RepairOrder ro)
        {
            try
            {
                db.RepairOrder.Add(ro);
                db.SaveChanges();
            }
            catch
            {
                throw;
            }
        }

        //To update Repair Orders
        public void UpdateRepairOrder(RepairOrder ro)
        {
            try
            {
                db.Entry(ro).State = EntityState.Modified;
                db.SaveChanges();
            }
            catch
            {
                throw;
            }
        }

        //Get the details of a particular RO
        public RepairOrder GetRepairOrderDetails(int id)
        {
            try
            {
                RepairOrder ro = db.RepairOrder.Find(id);
                return ro;
            }
            catch
            {
                throw;
            }
        }

        //To delete a record
        public void DeleteRepairOrder(int id)
        {
            try
            {
                RepairOrder ro = db.RepairOrder.Find(id);
                db.RepairOrder.Remove(ro);
                db.SaveChanges();
            }
            catch
            {
                throw;
            }
        }
    }
}
</code>```

Data context file:

```<code>public ShopLiveContext()
        {
        }

        public ShopLiveContext(DbContextOptions<ShopLiveContext> options)
            : base(options)
        {
        }

        public virtual DbSet<RepairOrder> RepairOrder { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                optionsBuilder.UseSqlServer("Data Source=sumcso-8g5lr52;Initial Catalog=ShopLive;Integrated Security=True");
            }
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.HasAnnotation("ProductVersion", "3.0.0-preview5.19227.1");

            modelBuilder.Entity<RepairOrder>(entity =>
            {
                entity.Property(e => e.ControlNumber)
                    .IsRequired()
                    .HasMaxLength(13)
                    .IsUnicode(false);

                entity.Property(e => e.Customer)
                    .IsRequired()
                    .HasMaxLength(50)
                    .IsUnicode(false);

                entity.Property(e => e.Make)
                    .HasMaxLength(50)
                    .IsUnicode(false);

                entity.Property(e => e.ManagerNote)
                    .HasMaxLength(5000)
                    .IsUnicode(false);

                entity.Property(e => e.Model)
                    .HasMaxLength(50)
                    .IsUnicode(false);

                entity.Property(e => e.Stage)
                    .IsRequired()
                    .HasMaxLength(50)
                    .IsUnicode(false);

                entity.Property(e => e.TechncicianNote)
                    .HasMaxLength(5000)
                    .IsUnicode(false);

                entity.Property(e => e.Technician)
                    .HasMaxLength(50)
                    .IsUnicode(false);

                entity.Property(e => e.VehicleLocation)
                    .IsRequired()
                    .HasMaxLength(50)
                    .IsUnicode(false);

                entity.Property(e => e.Vin)
                    .HasColumnName("VIN")
                    .HasMaxLength(20)
                    .IsUnicode(false);
            });
        }
    }
</code>```

When I run the project, and click the link to the new page, it shows "loading..." but never grabs the data from the database and loads the table.

Can someone point me in the right direction as to what I maybe missing?

答:
I guess it's because your url is wrong. You use

"api/RepairOrder/Index" instead of "api/Employee/Index"

There might be other problems with this app, but this is the first my weak eyes noticed.

Note:

This app is ancient. Almost pre-history. It was composed even before I heard of Blazor.

You should have used tools such as postman or Fiddler to verify whether your Web API returns data. This could save you lots of troubles.

I'd advise you not to learn Blazor by following the articles and books composed by this guy. He himself needs lots of courses in Blazor and how the Internet works. He also never seriously goes beyond CRUD. The article you provided a link to is full of mistakes and basic understanding of the web, of SPA and of Blazor itself.

Learn instead:

Blazor Documents

I've started learning Blazor and recommend you to use

https://chrissainty.com/blazor/

https://learn-blazor.com/
This is an excellent source of learning. Was deserted by its owner for a while. But I hope he has started to update it.

https://github.com/dotnet-presentations/blazor-workshop

https://github.com/aspnet/samples/tree/master/samples/aspnetcore/blazor

Hope this helps...

Body:
Using ASP.net Core 3.0 and Blazor. I am modifying the project found here: https://ankitsharmablogs.com/asp-net-core-crud-using-blazor-and-entity-framework-core/

I used Scofold-DbContext to build my Context file and the Model class. VS had no issue contacting the Database to create the required files.

Razor View:

@using ShopLive1.Shared.Models
@page "/fetchemployees"
@inject  HttpClient Http

Shop Live - Repair Order Update

@if(roList == null)
{

Loading....

}
else
{

                Control Number
                VIN
                Make
                Model
                Customer
                Repair Stage
                Location
                Assigned

            @foreach(var ro in roList)
            {

                    @ro.ControlNumber
                    @ro.Vin
                    @ro.Make
                    @ro.Model
                    @ro.Customer
                    @ro.Stage
                    @ro.VehicleLocation
                    @ro.Technician

            }

}

@functions{
    RepairOrder[] roList;

    protected override async Task OnInitAsync()
    {
        roList = await Http.GetJsonAsync<RepairOrder[]>("api/RepairOrder/Index");
    }
}

Data Access layer class:

ShopLiveContext db = new ShopLiveContext();

        //To get all repair orders
        public List<RepairOrder> GetAllRepairOrders()
        {
            try
            {
                return db.RepairOrder.ToList();
            }
            catch
            {
                throw;
            }

        }

        //To add new Repair Orders
        public void AddRepairOrder(RepairOrder ro)
        {
            try
            {
                db.RepairOrder.Add(ro);
                db.SaveChanges();
            }
            catch
            {
                throw;
            }
        }

        //To update Repair Orders
        public void UpdateRepairOrder(RepairOrder ro)
        {
            try
            {
                db.Entry(ro).State = EntityState.Modified;
                db.SaveChanges();
            }
            catch
            {
                throw;
            }
        }

        //Get the details of a particular RO
        public RepairOrder GetRepairOrderDetails(int id)
        {
            try
            {
                RepairOrder ro = db.RepairOrder.Find(id);
                return ro;
            }
            catch
            {
                throw;
            }
        }

        //To delete a record
        public void DeleteRepairOrder(int id)
        {
            try
            {
                RepairOrder ro = db.RepairOrder.Find(id);
                db.RepairOrder.Remove(ro);
                db.SaveChanges();
            }
            catch
            {
                throw;
            }
        }
    }
}

Data context file:

public ShopLiveContext()
        {
        }

        public ShopLiveContext(DbContextOptions<ShopLiveContext> options)
            : base(options)
        {
        }

        public virtual DbSet<RepairOrder> RepairOrder { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                optionsBuilder.UseSqlServer("Data Source=sumcso-8g5lr52;Initial Catalog=ShopLive;Integrated Security=True");
            }
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.HasAnnotation("ProductVersion", "3.0.0-preview5.19227.1");

            modelBuilder.Entity<RepairOrder>(entity =>
            {
                entity.Property(e => e.ControlNumber)
                    .IsRequired()
                    .HasMaxLength(13)
                    .IsUnicode(false);

                entity.Property(e => e.Customer)
                    .IsRequired()
                    .HasMaxLength(50)
                    .IsUnicode(false);

                entity.Property(e => e.Make)
                    .HasMaxLength(50)
                    .IsUnicode(false);

                entity.Property(e => e.ManagerNote)
                    .HasMaxLength(5000)
                    .IsUnicode(false);

                entity.Property(e => e.Model)
                    .HasMaxLength(50)
                    .IsUnicode(false);

                entity.Property(e => e.Stage)
                    .IsRequired()
                    .HasMaxLength(50)
                    .IsUnicode(false);

                entity.Property(e => e.TechncicianNote)
                    .HasMaxLength(5000)
                    .IsUnicode(false);

                entity.Property(e => e.Technician)
                    .HasMaxLength(50)
                    .IsUnicode(false);

                entity.Property(e => e.VehicleLocation)
                    .IsRequired()
                    .HasMaxLength(50)
                    .IsUnicode(false);

                entity.Property(e => e.Vin)
                    .HasColumnName("VIN")
                    .HasMaxLength(20)
                    .IsUnicode(false);
            });
        }
    }

When I run the project, and click the link to the new page, it shows "loading..." but never grabs the data from the database and loads the table.

Can someone point me in the right direction as to what I maybe missing?


问:
Why the NMI function address stored in the NMI Vector address ends with the bit 1 in the ARM cortex?
I have got a STM32-F49ZI nucleo board which is ARM Cortex 4 - 32 bits MCU. I have my own NMI handler i.e. NMI_Handler function, whose address ends with a bit 0. I can see that in the debugger. However, the vector address of NMI Handler stores the same address of NMI_Handler function except that the bit ends with 1. My question why there is a discrepancy. I got to know that this is because ARM cortex M supports only Thumb instructions i.e. 16-bit instructions only. I am unable to understand this reasoning. What's the reason behind it? Why it sets the last bit to 1.

```<code>void NMI_Handler()
{

}
</code>```

Watchdog window shows

```<code>NMI_Handler address - 0x8010 1000
</code>```

However, the address stored in the NMI Vector address is -

```<code>0x8010 1001.
</code>```

答:
Although the Cortex-M4 only supports the THUMB2 instruction set, for binary compatibility across all current ARM parts, it uses the LSB of all vector, branch and jump addresses to indicate THUMB mode in order to support ARM/THUMB interworking.  It indicates to the processor that the code about to be jumped to is THUMB code.  For processors that support ARM and THUMB instruction sets, it causes an instruction set mode switch if the current mode is not THUMB.

Your NMI_Handler handler function will be located at an even address as indicated in your link map, but the vector will have the LSB set.  When the program-counter is loaded from a vector or branch address the LSB is set to zero.

See the "Note" box in the Cortex M4 technical reference section 3.9.1 Exception handling and prioritization

Body:
I have got a STM32-F49ZI nucleo board which is ARM Cortex 4 - 32 bits MCU. I have my own NMI handler i.e. NMI_Handler function, whose address ends with a bit 0. I can see that in the debugger. However, the vector address of NMI Handler stores the same address of NMI_Handler function except that the bit ends with 1. My question why there is a discrepancy. I got to know that this is because ARM cortex M supports only Thumb instructions i.e. 16-bit instructions only. I am unable to understand this reasoning. What's the reason behind it? Why it sets the last bit to 1.

void NMI_Handler()
{

}

Watchdog window shows

NMI_Handler address - 0x8010 1000

However, the address stored in the NMI Vector address is -

0x8010 1001.


问:
Selecting Only The Latest Version Of A Field
I have a table schema with ID, Title, Date

and data looks something like this:

```<code>1  The title1    2011-04-05 00:00:00.000
2  Another title 2011-04-11 00:00:00.000
3  The title1    2011-04-11 16:49:23.633
4  The title1    2011-04-11 00:00:00.000
</code>```

I need help with sql to give me the latest date of each title.
So the output for the above data is

```<code>2  Another title 2011-04-11 00:00:00.000
3  The title1    2011-04-11 16:49:23.633
</code>```

答:
```<code>select id,title,date from [schema]
where title in (select title from [schema] group by title having date=max(date))
</code>```

try this

Body:
I have a table schema with ID, Title, Date

and data looks something like this:

1  The title1    2011-04-05 00:00:00.000
2  Another title 2011-04-11 00:00:00.000
3  The title1    2011-04-11 16:49:23.633
4  The title1    2011-04-11 00:00:00.000

I need help with sql to give me the latest date of each title.
So the output for the above data is

2  Another title 2011-04-11 00:00:00.000
3  The title1    2011-04-11 16:49:23.633

Body:
select id,title,date from [schema]
where title in (select title from [schema] group by title having date=max(date))

try this


问:
How to address backend host with axios, when frontend and backend are in virtual docker network
I'm building a simple Website with login, and my vue-frontend needs to retrieve user data from my nodejs-backend which connects to a sql database.
I decided to use docker-compose for this, and as I understand, docker-compose sets up a network automatically for the services that are mentioned in my docker-compose.yml.

What doesn't seem to work, is the way I address the backend in my code.
I suspect that it might be because of the way I use axios to send a request to my backend.

I have inspected the default docker-network and was able to ping from my frontend to my backend using the dns names I found in the network-configuration.
But using the same names inside my code didn't work.

What does work, is mapping a host port to my exposed api port and using http://localhost:5000 as address, but this defeats the purpose of a docker network.

my docker-compose.yml:

```<code>version: '3.3'

services:
    vue-frontend:
        image: flowmotion/vue-js-frontend
        ports:
            - 8070:80
        depends_on:
            - db-user-api

    db-user-api:
        image: flowmotion/user-db-api
        environment:
            - PORT=5000
        ports:
            - 5000:5000 #only needed if docker network connection can't be established
</code>```

the Vue-fontend files in question:

Login.vue

```<code>methods: {
    async login() {
      try {
        const response = await authenticationService.login({
          email: this.email,
          password: this.password
        });
        this.$store.dispatch("setToken", response.data.token);
        this.$store.dispatch("setUser", response.data.user);
        this.$router.push({ path: "/" });
      } catch (error) {
        this.showError = true;
        this.error = error.response.data.error;
      }
    }
  }
};
</script>
</code>```

authenticationService.js

```<code>import api from "@/services/api";

export default {
  login(credentials) {
    return api().post("login", credentials);
  }
};
</code>```

api.js

```<code>import axios from 'axios';
import config from '../config/config';
export default () => {
    return axios.create({
        baseURL: config.userBackendServer
    });
};
</code>```

config.js ()

```<code>module.exports = {
    userBackendServer: 'http://cl-dashboard_db-user-api_1:5000' //this doesn't seem to work
};

//using 'http://localhost:5000' works if ports are mapped to host machine.
</code>```

expected result would be my backend doing a sql lookup.

actuel result is, instead of connecting to my backend my frontend gives me a 404 status and my backend is never reached

答:
you are correct assuming containers in the docker network can talk to each other without opening any ports to the outer world.

point is- your vue app is not in any container- it is served from a container as a js script file to your browser, which is the one sending the requests to your node backend. since your browser is by any means not inside the docker network - you must use the outer port mapping (localhost:5000 in your case) to reach the backend.

let me know if you have any more questions about that.

Body:
I'm building a simple Website with login, and my vue-frontend needs to retrieve user data from my nodejs-backend which connects to a sql database.
I decided to use docker-compose for this, and as I understand, docker-compose sets up a network automatically for the services that are mentioned in my docker-compose.yml.

What doesn't seem to work, is the way I address the backend in my code.
I suspect that it might be because of the way I use axios to send a request to my backend.

I have inspected the default docker-network and was able to ping from my frontend to my backend using the dns names I found in the network-configuration.
But using the same names inside my code didn't work.

What does work, is mapping a host port to my exposed api port and using http://localhost:5000 as address, but this defeats the purpose of a docker network.

my docker-compose.yml:

version: '3.3'

services:
    vue-frontend:
        image: flowmotion/vue-js-frontend
        ports:
            - 8070:80
        depends_on:
            - db-user-api

    db-user-api:
        image: flowmotion/user-db-api
        environment:
            - PORT=5000
        ports:
            - 5000:5000 #only needed if docker network connection can't be established

the Vue-fontend files in question:

Login.vue

methods: {
    async login() {
      try {
        const response = await authenticationService.login({
          email: this.email,
          password: this.password
        });
        this.$store.dispatch("setToken", response.data.token);
        this.$store.dispatch("setUser", response.data.user);
        this.$router.push({ path: "/" });
      } catch (error) {
        this.showError = true;
        this.error = error.response.data.error;
      }
    }
  }
};
</script>

authenticationService.js

import api from "@/services/api";

export default {
  login(credentials) {
    return api().post("login", credentials);
  }
};

api.js

import axios from 'axios';
import config from '../config/config';
export default () => {
    return axios.create({
        baseURL: config.userBackendServer
    });
};

config.js ()

module.exports = {
    userBackendServer: 'http://cl-dashboard_db-user-api_1:5000' //this doesn't seem to work
};

//using 'http://localhost:5000' works if ports are mapped to host machine.

expected result would be my backend doing a sql lookup.

actuel result is, instead of connecting to my backend my frontend gives me a 404 status and my backend is never reached


问:
Saving a file in Cordova on iOS not working - fine in Android
I have a cordova app where i'm downloading a pdf file, saving it locally and then opening it.
It works fine in Android but iOS gives a message in the output window that its written the file but cant open a file of null.

Originally I was using cordova.file.externalRootDirectory which worked in Android but not iOS.
I changed this to cordova.file.dataDirectory which again working in Android but not iOS.

According to searches I've done, using cordova.file.dataDirectory should work on both platforms.

I've tried adding

to the config file, but this makes no difference.

```<code>var contentType = "application/pdf";
var folderpath = cordova.file.dataDirectory;
var filename = filedate + ".pdf";

savebase64AsPDF(folderpath,filename,data,contentType)

function b64toBlob(b64Data, contentType, sliceSize) {
    contentType = contentType || '';
    sliceSize = sliceSize || 512;

    var byteCharacters = atob(b64Data);
    var byteArrays = [];

    for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
        var slice = byteCharacters.slice(offset, offset + sliceSize);

        var byteNumbers = new Array(slice.length);
        for (var i = 0; i < slice.length; i++) {
            byteNumbers[i] = slice.charCodeAt(i);
        }

        var byteArray = new Uint8Array(byteNumbers);

        byteArrays.push(byteArray);
    }

  var blob = new Blob(byteArrays, {type: contentType});
  return blob;
}

function savebase64AsPDF(folderpath,filename,content,contentType){
// Convert the base64 string in a Blob
var DataBlob = b64toBlob(content,contentType);

console.log("Starting to write the file :3");

window.resolveLocalFileSystemURL(folderpath, function(dir) {
    console.log("Access to the directory granted succesfully");
    dir.getFile(filename, {create:true}, function(file) {
        console.log("File created succesfully.");
        file.createWriter(function(fileWriter) {
            console.log("Writing content to file");
            fileWriter.write(DataBlob);
            console.log("Finished writing file.");
            //open file
            cordova.plugins.fileOpener2.open(folderpath + filename, 'application/pdf');
        }, function(){
            alert('Unable to save file in path '+ folderpath);
        });
    });
});
}
</code>```

The expected (and desired) result is what happens on Android in that the file is saved locally and then opened in the default pdf reader.

The best I can get from iOS is a message in the output window of xcode that says it has "Finished writing file" and then another line stating that "looking for file at (null)"

No exceptions or errors, just nothing.

Any help would be gratefully received.

答:
The plugin fileOpener2 has a known issue with spaces in the filename for iOS. You can reportedly use decodeURIComponent to display files affected by this, e.g., in this case:

var docUrl = folderpath + filename;

if ( device.platform.toLowerCase() === 'ios' ) { // only change for iOS
  docUrl = decodeURIComponent( docUrl );
}

cordova.plugins.fileOpener2.open(docUrl, 'application/pdf');
```

You can also simply remove/replace the spaces when saving.

(This plugin also has issues with non-ASCII characters. Solutions here can get a little complex.)

Body:
I have a cordova app where i'm downloading a pdf file, saving it locally and then opening it.
It works fine in Android but iOS gives a message in the output window that its written the file but cant open a file of null.

Originally I was using cordova.file.externalRootDirectory which worked in Android but not iOS.
I changed this to cordova.file.dataDirectory which again working in Android but not iOS.

According to searches I've done, using cordova.file.dataDirectory should work on both platforms.

I've tried adding

to the config file, but this makes no difference.

var contentType = "application/pdf";
var folderpath = cordova.file.dataDirectory;
var filename = filedate + ".pdf";

savebase64AsPDF(folderpath,filename,data,contentType)

function b64toBlob(b64Data, contentType, sliceSize) {
    contentType = contentType || '';
    sliceSize = sliceSize || 512;

    var byteCharacters = atob(b64Data);
    var byteArrays = [];

    for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
        var slice = byteCharacters.slice(offset, offset + sliceSize);

        var byteNumbers = new Array(slice.length);
        for (var i = 0; i < slice.length; i++) {
            byteNumbers[i] = slice.charCodeAt(i);
        }

        var byteArray = new Uint8Array(byteNumbers);

        byteArrays.push(byteArray);
    }

  var blob = new Blob(byteArrays, {type: contentType});
  return blob;
}

function savebase64AsPDF(folderpath,filename,content,contentType){
// Convert the base64 string in a Blob
var DataBlob = b64toBlob(content,contentType);

console.log("Starting to write the file :3");

window.resolveLocalFileSystemURL(folderpath, function(dir) {
    console.log("Access to the directory granted succesfully");
    dir.getFile(filename, {create:true}, function(file) {
        console.log("File created succesfully.");
        file.createWriter(function(fileWriter) {
            console.log("Writing content to file");
            fileWriter.write(DataBlob);
            console.log("Finished writing file.");
            //open file
            cordova.plugins.fileOpener2.open(folderpath + filename, 'application/pdf');
        }, function(){
            alert('Unable to save file in path '+ folderpath);
        });
    });
});
}

The expected (and desired) result is what happens on Android in that the file is saved locally and then opened in the default pdf reader.

The best I can get from iOS is a message in the output window of xcode that says it has "Finished writing file" and then another line stating that "looking for file at (null)"

No exceptions or errors, just nothing.

Any help would be gratefully received.

Body:
The plugin fileOpener2 has a known issue with spaces in the filename for iOS. You can reportedly use decodeURIComponent to display files affected by this, e.g., in this case:

var docUrl = folderpath + filename;

if ( device.platform.toLowerCase() === 'ios' ) { // only change for iOS
  docUrl = decodeURIComponent( docUrl );
}

cordova.plugins.fileOpener2.open(docUrl, 'application/pdf');

You can also simply remove/replace the spaces when saving.

(This plugin also has issues with non-ASCII characters. Solutions here can get a little complex.)


问:
How to GET rest json return from filtered perpage and specific page wordpress API link
I can get data per page with link

myWeb.com/wp-json/wp/v2/posts?per_page=10

 but how I can get data from page 2 and per_page=10,

 I wondering it would be like

myWeb.com/wp-json/wp/v2/posts?per_page=10?page=2

for 10 posts in page 2 but it's not work, does it need custom API in WP-API to get that?

答:
Hi you need to pass the arguments like this

```<code>myWeb.com/wp-json/wp/v2/posts?per_page=10&page=2
</code>```

You can check all the available Arguments from here

```<code>https://developer.wordpress.org/rest-api/reference/posts/
</code>```

Thanks!

Body:
Hi you need to pass the arguments like this

myWeb.com/wp-json/wp/v2/posts?per_page=10&page=2

You can check all the available Arguments from here

https://developer.wordpress.org/rest-api/reference/posts/

Thanks!


问:
what is the best way to update component color/font globally in `materia-ui`?
I am using material-ui for my react project and I found material-ui uses makeStyles to create the style object. Then inject the styles object as classes into each component. It seems styles is bind with each component. My question is how I can define some globally used styles like font, color etc. In css / scss, I can define some global variables and I can change them in the css files which will apply to all other components. What is the best way to do that in material-ui styles?

```<code>...

const useStyles = makeStyles({
  root: {
    background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
    border: 0,
    borderRadius: 3,
    boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
    color: 'white',
    height: 48,
    padding: '0 30px',
  },
});

return (
      <div className={classes.root}>
 ...
</code>```

答: Check the customization of Theme</p>

Body:
I am using material-ui for my react project and I found material-ui uses makeStyles to create the style object. Then inject the styles object as classes into each component. It seems styles is bind with each component. My question is how I can define some globally used styles like font, color etc. In css / scss, I can define some global variables and I can change them in the css files which will apply to all other components. What is the best way to do that in material-ui styles?

...

const useStyles = makeStyles({
  root: {
    background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
    border: 0,
    borderRadius: 3,
    boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
    color: 'white',
    height: 48,
    padding: '0 30px',
  },
});

return (

 ...

Body: Check the customization of Theme


问:
Erlang: whether two lists have a common element
```<code>a = [1, 2, 3],
b = [4, 5, 6],
c = [1, 7, 8],
</code>```

has_common_element(a, b) is false since there are no common elements between the two arrays.

has_common_element(a, c) is true since there is at least one common element (1) between the two arrays.

I can use lists:member to check whether a single element is in the list. How do I implement has_common_element in Erlang to check whether two lists have a common element?

答:
Create sets from the lists and use sets:is_disjoint:

```<code>has_common_member(L1, L2) ->
    not(sets:is_disjoint(sets:from_list(L1), sets:from_list(L2))).
</code>```

Body:
a = [1, 2, 3],
b = [4, 5, 6],
c = [1, 7, 8],

has_common_element(a, b) is false since there are no common elements between the two arrays.

has_common_element(a, c) is true since there is at least one common element (1) between the two arrays.

I can use lists:member to check whether a single element is in the list. How do I implement has_common_element in Erlang to check whether two lists have a common element?

Body:
Create sets from the lists and use sets:is_disjoint:

has_common_member(L1, L2) ->
    not(sets:is_disjoint(sets:from_list(L1), sets:from_list(L2))).


问:
javascript compare array of objects by key
I want to match id and parentId if match then add in child

ex

let menuItems = [
  {
        "id": "menu-0",
        "title": "Home",
        "parentId": "menu-1",
        "childCount": 0
    },
     {
        "id": "menu-1",
        "title": "About",
        "parentId": null,
        "childCount": 2
    },
     {
        "id": "menu-3",
        "title": "About Sub1",
        "parentId": "menu-1",
        "childCount": 2
    },
     {
        "id": "menu-5",
        "title": "About Sub2",
        "parentId": "menu-1",
        "childCount": 0
    },
     {
        "id": "menu-4",
        "title": "About Sub1 sub1",
        "parentId": "menu-3",
        "childCount": 0
    },
     {
        "id": "menu-6",
        "title": "Contact",
        "parentId": null,
        "childCount": 2
    }
]```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
 <li>About
     <ul>
         <li>
            About Sub1
         </li>
    </ul>
 </li>
 <li>
            Contact
 </li>
</ul></code>```

```<code>data[i].id == data[i].parentId
</code>```

but return false

答:
You're comparing the same object's id and parentId, that's why it always returns false. I'm not sure of what you're trying to achieve but if you want to calculate childCount you could do something like this:</p>

```<code>menuItems.forEach( parent => parent.childCount = menuItems.filter( child => parent.id === child.parentId).length);
</code>```

Body:
I want to match id and parentId if match then add in child

ex

let menuItems = [
  {
        "id": "menu-0",
        "title": "Home",
        "parentId": "menu-1",
        "childCount": 0
    },
     {
        "id": "menu-1",
        "title": "About",
        "parentId": null,
        "childCount": 2
    },
     {
        "id": "menu-3",
        "title": "About Sub1",
        "parentId": "menu-1",
        "childCount": 2
    },
     {
        "id": "menu-5",
        "title": "About Sub2",
        "parentId": "menu-1",
        "childCount": 0
    },
     {
        "id": "menu-4",
        "title": "About Sub1 sub1",
        "parentId": "menu-3",
        "childCount": 0
    },
     {
        "id": "menu-6",
        "title": "Contact",
        "parentId": null,
        "childCount": 2
    }
]

About

            About Sub1

            Contact

data[i].id == data[i].parentId

but return false

Body:
You're comparing the same object's id and parentId, that's why it always returns false. I'm not sure of what you're trying to achieve but if you want to calculate childCount you could do something like this:

menuItems.forEach( parent => parent.childCount = menuItems.filter( child => parent.id === child.parentId).length);


问:
How to use ripcord in laravel
I'm trying to use the ripcord library in Laravel 5.8, but I do not know what to make it work. I still do not understand how laravel works, so I do not know where some things fit.

This is the link from where I take the library:
https://github.com/DarkaOnLine/Ripcord

Thanks for any help you can provide.

Note: I have used the ripcord library with pure PHP.

I have only used the composer, I do not understand where to put the rest of the code to make it work.

答:
From the repo, I can tell that you have to:

Install the package

```<code>composer require darkaonline/ripcord
</code>```

Register the Service

Open your AppServiceProvider (located in app/Providers) and add this line in register function

```<code>$this->app->register(\Ripcord\Providers\Laravel\ServiceProvider::class);
</code>```

Publish the config

```<code>php artisan ripcord:publish
</code>```

Title: How to use ripcord in laravel

Body:
From the repo, I can tell that you have to:

Install the package

composer require darkaonline/ripcord

Register the Service

Open your AppServiceProvider (located in app/Providers) and add this line in register function

$this->app->register(\Ripcord\Providers\Laravel\ServiceProvider::class);

Publish the config

php artisan ripcord:publish


问:
Connection upgrade to WebSocket
I have poorly documented device that should communicate in two ways RESTful and Websocket. I'm interested only in functions accessible via Websocket. I have opened socket and was expecting some Json packet, but got message:

```<code>GET /api/v1/tasks HTTP/1.1
Upgrade: websocket
Sec-WebSocket-Key: MjhkYjNVdk93M0Fnd3lwdw==
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Host: 192.168.0.80:3701
Sec-WebSocket-Version: 13
User-Agent: DVR Server
Accept-Language: en-us,en;q=0.5
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Connection: Upgrade
</code>```

I suppose this is RESTful call and this message is trying to offer to upgrade to WebSocket. I'm right? But how to accept this? What I should send as answer? What is the best way to do this in Java?

答:
If you are looking only to accept the websocket handshake, the following code would do the work.

The first parameter of the acceptHandshake function is the writer that writes to the OutputStream of the socket.

```<code>private void acceptHandshake(PrintWriter output, String secureWebSocketKey) {
    try {
        output.println("HTTP/1.1 101 Switching Protocols");
        output.println("Upgrade: websocket");
        output.println("Connection: Upgrade");
        output.println("Sec-WebSocket-Accept: " + encode(key));
        output.println();
        output.flush();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private String encode(String key) throws Exception {
    key += "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
    byte[] bytes = MessageDigest.getInstance("SHA-1").digest(key.getBytes());
    return DatatypeConverter.printBase64Binary(bytes);
}
</code>```

Title: Connection upgrade to WebSocket

Body:
I have poorly documented device that should communicate in two ways RESTful and Websocket. I'm interested only in functions accessible via Websocket. I have opened socket and was expecting some Json packet, but got message:

GET /api/v1/tasks HTTP/1.1
Upgrade: websocket
Sec-WebSocket-Key: MjhkYjNVdk93M0Fnd3lwdw==
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Host: 192.168.0.80:3701
Sec-WebSocket-Version: 13
User-Agent: DVR Server
Accept-Language: en-us,en;q=0.5
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Connection: Upgrade

I suppose this is RESTful call and this message is trying to offer to upgrade to WebSocket. I'm right? But how to accept this? What I should send as answer? What is the best way to do this in Java?

Body:
If you are looking only to accept the websocket handshake, the following code would do the work.

The first parameter of the acceptHandshake function is the writer that writes to the OutputStream of the socket.

private void acceptHandshake(PrintWriter output, String secureWebSocketKey) {
    try {
        output.println("HTTP/1.1 101 Switching Protocols");
        output.println("Upgrade: websocket");
        output.println("Connection: Upgrade");
        output.println("Sec-WebSocket-Accept: " + encode(key));
        output.println();
        output.flush();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private String encode(String key) throws Exception {
    key += "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
    byte[] bytes = MessageDigest.getInstance("SHA-1").digest(key.getBytes());
    return DatatypeConverter.printBase64Binary(bytes);
}


问:
Generate Signed APK - ClassNotFoundException : com.google.wireless.android.sdk.stats.IntellijIndexingStats$Index
Whenever I try to generate a signed APK I get this same error :

```<code>Error:Internal error: (java.lang.ClassNotFoundException) com.google.wireless.android.sdk.stats.IntellijIndexingStats$Index
java.lang.ClassNotFoundException: com.google.wireless.android.sdk.stats.IntellijIndexingStats$Index
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at com.intellij.util.indexing.counters.IndexCounters.<clinit>(IndexCounters.java:34)
    at com.intellij.util.indexing.impl.MapReduceIndex.<init>(MapReduceIndex.java:86)
    at org.jetbrains.jps.backwardRefs.index.CompilerReferenceIndex$CompilerMapReduceIndex.<init>(CompilerReferenceIndex.java:214)
    at org.jetbrains.jps.backwardRefs.index.CompilerReferenceIndex.<init>(CompilerReferenceIndex.java:73)
    at org.jetbrains.jps.backwardRefs.JavaCompilerBackwardReferenceIndex.<init>(JavaCompilerBackwardReferenceIndex.java:12)
    at org.jetbrains.jps.backwardRefs.JavaBackwardReferenceIndexWriter.initialize(JavaBackwardReferenceIndexWriter.java:74)
    at org.jetbrains.jps.backwardRefs.JavaBackwardReferenceIndexBuilder.buildStarted(JavaBackwardReferenceIndexBuilder.java:40)
    at org.jetbrains.jps.incremental.IncProjectBuilder.runBuild(IncProjectBuilder.java:358)
    at org.jetbrains.jps.incremental.IncProjectBuilder.build(IncProjectBuilder.java:178)
    at org.jetbrains.jps.cmdline.BuildRunner.runBuild(BuildRunner.java:138)
    at org.jetbrains.jps.cmdline.BuildSession.runBuild(BuildSession.java:302)
    at org.jetbrains.jps.cmdline.BuildSession.run(BuildSession.java:135)
    at org.jetbrains.jps.cmdline.BuildMain$MyMessageHandler.lambda$channelRead0$0(BuildMain.java:229)
    at org.jetbrains.jps.service.impl.SharedThreadPoolImpl.lambda$executeOnPooledThread$0(SharedThreadPoolImpl.java:42)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

</code>```

I understand it comes from the Javac compiler, could be linked with a bug checker run before compiling, but I don't really know what to do. I do not use ProGuard yet to simplify the generation.

Any idea how to fix this  and finally allow me to generate a release-ready signed APK ?

EDIT : Here's my AndroidManifest

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.farmleap.farmleapbeaconapp"
    xmlns:tools="http://schemas.android.com/tools">

    <!-- The INTERNET permission is required for development. Specifically,
         flutter needs it to communicate with the running application
         to allow setting breakpoints, to provide hot reload, etc.
    -->
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <!-- io.flutter.app.FlutterApplication is an android.app.Application that
         calls FlutterMain.startInitialization(this); in its onCreate method.
         In most cases you can leave this as-is, but you if you want to provide
         additional functionality it is fine to subclass or reimplement
         FlutterApplication and put your custom class here. -->
    <application
        tools:replace="android:label"
        android:name="io.flutter.app.FlutterApplication"
        android:label="FarmLEAP"
        android:icon="@mipmap/ic_launcher"
        android:usesCleartextTraffic="true"
        >
        <meta-data
            android:name="com.transistorsoft.locationmanager.license"
            android:value="[REDACTED]" />
        <activity
            android:name=".MainActivity"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">
            <!-- This keeps the window background of the activity showing
                 until Flutter renders its first frame. It can be removed if
                 there is no splash screen (such as the default splash screen
                 defined in @style/LaunchTheme). -->
            <meta-data
                android:name="io.flutter.app.android.SplashScreenUntilFirstFrame"
                android:value="true" />
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <activity android:name="com.apptreesoftware.barcodescan.BarcodeScannerActivity"/>
    </application>
</manifest>
</code>```

答:
If in the LogCat window you see "Please configure Android SDK" click on it and follow the configuration for the last version. Seems that you are missing the updated SDK or you use a plugin that reference an unsupported one.

L-

Body:
Whenever I try to generate a signed APK I get this same error :

Error:Internal error: (java.lang.ClassNotFoundException) com.google.wireless.android.sdk.stats.IntellijIndexingStats$Index
java.lang.ClassNotFoundException: com.google.wireless.android.sdk.stats.IntellijIndexingStats$Index
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at com.intellij.util.indexing.counters.IndexCounters.<clinit>(IndexCounters.java:34)
    at com.intellij.util.indexing.impl.MapReduceIndex.<init>(MapReduceIndex.java:86)
    at org.jetbrains.jps.backwardRefs.index.CompilerReferenceIndex$CompilerMapReduceIndex.<init>(CompilerReferenceIndex.java:214)
    at org.jetbrains.jps.backwardRefs.index.CompilerReferenceIndex.<init>(CompilerReferenceIndex.java:73)
    at org.jetbrains.jps.backwardRefs.JavaCompilerBackwardReferenceIndex.<init>(JavaCompilerBackwardReferenceIndex.java:12)
    at org.jetbrains.jps.backwardRefs.JavaBackwardReferenceIndexWriter.initialize(JavaBackwardReferenceIndexWriter.java:74)
    at org.jetbrains.jps.backwardRefs.JavaBackwardReferenceIndexBuilder.buildStarted(JavaBackwardReferenceIndexBuilder.java:40)
    at org.jetbrains.jps.incremental.IncProjectBuilder.runBuild(IncProjectBuilder.java:358)
    at org.jetbrains.jps.incremental.IncProjectBuilder.build(IncProjectBuilder.java:178)
    at org.jetbrains.jps.cmdline.BuildRunner.runBuild(BuildRunner.java:138)
    at org.jetbrains.jps.cmdline.BuildSession.runBuild(BuildSession.java:302)
    at org.jetbrains.jps.cmdline.BuildSession.run(BuildSession.java:135)
    at org.jetbrains.jps.cmdline.BuildMain$MyMessageHandler.lambda$channelRead0$0(BuildMain.java:229)
    at org.jetbrains.jps.service.impl.SharedThreadPoolImpl.lambda$executeOnPooledThread$0(SharedThreadPoolImpl.java:42)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

I understand it comes from the Javac compiler, could be linked with a bug checker run before compiling, but I don't really know what to do. I do not use ProGuard yet to simplify the generation.

Any idea how to fix this  and finally allow me to generate a release-ready signed APK ?

EDIT : Here's my AndroidManifest

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.farmleap.farmleapbeaconapp"
    xmlns:tools="http://schemas.android.com/tools">

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        tools:replace="android:label"
        android:name="io.flutter.app.FlutterApplication"
        android:label="FarmLEAP"
        android:icon="@mipmap/ic_launcher"
        android:usesCleartextTraffic="true"
        >
        <meta-data
            android:name="com.transistorsoft.locationmanager.license"
            android:value="[REDACTED]" />
        <activity
            android:name=".MainActivity"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">

            <meta-data
                android:name="io.flutter.app.android.SplashScreenUntilFirstFrame"
                android:value="true" />
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <activity android:name="com.apptreesoftware.barcodescan.BarcodeScannerActivity"/>
    </application>
</manifest>


问:
What output and recording ports does the Java Sound API find on your computer?
I'm working with the Java Sound API, and it turns out if I want to adjust recording volumes I need to model the hardware that the OS exposes to Java. Turns out there's a lot of variety in what's presented.

Because of this I'm humbly asking that anyone able to help me run the following on their computer and post back the results so that I can get an idea of what's out there.

A thanks in advance to anyone that can assist :-)

```<code>import javax.sound.sampled.*;
public class SoundAudit {
  public static void main(String[] args) { try {
    System.out.println("OS: "+System.getProperty("os.name")+" "+
      System.getProperty("os.version")+"/"+
      System.getProperty("os.arch")+"\nJava: "+
      System.getProperty("java.version")+" ("+
      System.getProperty("java.vendor")+")\n");
      for (Mixer.Info thisMixerInfo : AudioSystem.getMixerInfo()) {
        System.out.println("Mixer: "+thisMixerInfo.getDescription()+
          " ["+thisMixerInfo.getName()+"]");
        Mixer thisMixer = AudioSystem.getMixer(thisMixerInfo);
        for (Line.Info thisLineInfo:thisMixer.getSourceLineInfo()) {
            if (thisLineInfo.getLineClass().getName().equals(
              "javax.sound.sampled.Port")) {
              Line thisLine = thisMixer.getLine(thisLineInfo);
              thisLine.open();
              System.out.println("  Source Port: "
                +thisLineInfo.toString());
              for (Control thisControl : thisLine.getControls()) {
                System.out.println(AnalyzeControl(thisControl));}
              thisLine.close();}}
        for (Line.Info thisLineInfo:thisMixer.getTargetLineInfo()) {
          if (thisLineInfo.getLineClass().getName().equals(
            "javax.sound.sampled.Port")) {
            Line thisLine = thisMixer.getLine(thisLineInfo);
            thisLine.open();
            System.out.println("  Target Port: "
              +thisLineInfo.toString());
            for (Control thisControl : thisLine.getControls()) {
              System.out.println(AnalyzeControl(thisControl));}
            thisLine.close();}}}
  } catch (Exception e) {e.printStackTrace();}}
  public static String AnalyzeControl(Control thisControl) {
    String type = thisControl.getType().toString();
    if (thisControl instanceof BooleanControl) {
      return "    Control: "+type+" (boolean)"; }
    if (thisControl instanceof CompoundControl) {
      System.out.println("    Control: "+type+
        " (compound - values below)");
      String toReturn = "";
      for (Control children:
        ((CompoundControl)thisControl).getMemberControls()) {
        toReturn+="  "+AnalyzeControl(children)+"\n";}
      return toReturn.substring(0, toReturn.length()-1);}
    if (thisControl instanceof EnumControl) {
      return "    Control:"+type+" (enum: "+thisControl.toString()+")";}
    if (thisControl instanceof FloatControl) {
      return "    Control: "+type+" (float: from "+
        ((FloatControl) thisControl).getMinimum()+" to "+
        ((FloatControl) thisControl).getMaximum()+")";}
    return "    Control: unknown type";}
}
</code>```

All the application does is print out a line about the OS, a line about the JVM, and a few lines about the hardware found that may pertain to recording hardware. For example on my PC at work I get the following:

OS: Windows XP 5.1/x86
Java: 1.6.0_07 (Sun Microsystems Inc.)

```
Mixer: Direct Audio Device: DirectSound Playback [Primary Sound Driver]
Mixer: Direct Audio Device: DirectSound Playback [SoundMAX HD Audio]
Mixer: Direct Audio Device: DirectSound Capture [Primary Sound Capture Driver]
Mixer: Direct Audio Device: DirectSound Capture [SoundMAX HD Audio]
Mixer: Software mixer and synthesizer [Java Sound Audio Engine]
Mixer: Port Mixer [Port SoundMAX HD Audio]
  Source Port: MICROPHONE source port
    Control: Microphone (compound - values below)
      Control: Select (boolean)
      Control: Microphone Boost (boolean)
      Control: Front panel microphone (boolean)
      Control: Volume (float: from 0.0 to 1.0)
  Source Port: LINE_IN source port
    Control: Line In (compound - values below)
      Control: Select (boolean)
      Control: Volume (float: from 0.0 to 1.0)
      Control: Balance (float: from -1.0 to 1.0)
```

答:
```<code>OS: Windows XP 5.1/x86
Java: 1.6.0_03 (Sun Microsystems Inc.)

Mixer: Direct Audio Device: DirectSound Playback [Primary Sound Driver]
Mixer: Direct Audio Device: DirectSound Playback [SoundMAX HD Audio]
Mixer: Direct Audio Device: DirectSound Capture [Primary Sound Capture Driver]
Mixer: Direct Audio Device: DirectSound Capture [SoundMAX HD Audio]
Mixer: Software mixer and synthesizer [Java Sound Audio Engine]
Mixer: Port Mixer [Port SoundMAX HD Audio]
  Source Port: MICROPHONE source port
    Control: Microphone (compound - values below)
      Control: Select (boolean)
      Control: Microphone Boost (boolean)
      Control: Front panel microphone (boolean)
      Control: Volume (float: from 0.0 to 1.0)
  Source Port: LINE_IN source port
    Control: Line In (compound - values below)
      Control: Select (boolean)
      Control: Volume (float: from 0.0 to 1.0)
      Control: Balance (float: from -1.0 to 1.0)
  Target Port: SPEAKER target port
    Control: Volume (float: from 0.0 to 1.0)
    Control: Balance (float: from -1.0 to 1.0)
    Control: Mute (boolean)
    Control: Wave (compound - values below)
      Control: Volume (float: from 0.0 to 1.0)
      Control: Balance (float: from -1.0 to 1.0)
      Control: Mute (boolean)
    Control: SW Synth (compound - values below)
      Control: Volume (float: from 0.0 to 1.0)
      Control: Balance (float: from -1.0 to 1.0)
      Control: Mute (boolean)
    Control: CD Player (compound - values below)
      Control: Volume (float: from 0.0 to 1.0)
      Control: Balance (float: from -1.0 to 1.0)
      Control: Mute (boolean)
    Control: Input Monitor (compound - values below)
      Control: Mute (boolean)
</code>```

OwnerDisplayName: Dave Carpeneto

Body:
I'm working with the Java Sound API, and it turns out if I want to adjust recording volumes I need to model the hardware that the OS exposes to Java. Turns out there's a lot of variety in what's presented.

Because of this I'm humbly asking that anyone able to help me run the following on their computer and post back the results so that I can get an idea of what's out there.

A thanks in advance to anyone that can assist :-)

import javax.sound.sampled.*;
public class SoundAudit {
  public static void main(String[] args) { try {
    System.out.println("OS: "+System.getProperty("os.name")+" "+
      System.getProperty("os.version")+"/"+
      System.getProperty("os.arch")+"\nJava: "+
      System.getProperty("java.version")+" ("+
      System.getProperty("java.vendor")+")\n");
      for (Mixer.Info thisMixerInfo : AudioSystem.getMixerInfo()) {
        System.out.println("Mixer: "+thisMixerInfo.getDescription()+
          " ["+thisMixerInfo.getName()+"]");
        Mixer thisMixer = AudioSystem.getMixer(thisMixerInfo);
        for (Line.Info thisLineInfo:thisMixer.getSourceLineInfo()) {
            if (thisLineInfo.getLineClass().getName().equals(
              "javax.sound.sampled.Port")) {
              Line thisLine = thisMixer.getLine(thisLineInfo);
              thisLine.open();
              System.out.println("  Source Port: "
                +thisLineInfo.toString());
              for (Control thisControl : thisLine.getControls()) {
                System.out.println(AnalyzeControl(thisControl));}
              thisLine.close();}}
        for (Line.Info thisLineInfo:thisMixer.getTargetLineInfo()) {
          if (thisLineInfo.getLineClass().getName().equals(
            "javax.sound.sampled.Port")) {
            Line thisLine = thisMixer.getLine(thisLineInfo);
            thisLine.open();
            System.out.println("  Target Port: "
              +thisLineInfo.toString());
            for (Control thisControl : thisLine.getControls()) {
              System.out.println(AnalyzeControl(thisControl));}
            thisLine.close();}}}
  } catch (Exception e) {e.printStackTrace();}}
  public static String AnalyzeControl(Control thisControl) {
    String type = thisControl.getType().toString();
    if (thisControl instanceof BooleanControl) {
      return "    Control: "+type+" (boolean)"; }
    if (thisControl instanceof CompoundControl) {
      System.out.println("    Control: "+type+
        " (compound - values below)");
      String toReturn = "";
      for (Control children:
        ((CompoundControl)thisControl).getMemberControls()) {
        toReturn+="  "+AnalyzeControl(children)+"\n";}
      return toReturn.substring(0, toReturn.length()-1);}
    if (thisControl instanceof EnumControl) {
      return "    Control:"+type+" (enum: "+thisControl.toString()+")";}
    if (thisControl instanceof FloatControl) {
      return "    Control: "+type+" (float: from "+
        ((FloatControl) thisControl).getMinimum()+" to "+
        ((FloatControl) thisControl).getMaximum()+")";}
    return "    Control: unknown type";}
}

All the application does is print out a line about the OS, a line about the JVM, and a few lines about the hardware found that may pertain to recording hardware. For example on my PC at work I get the following:

OS: Windows XP 5.1/x86
Java: 1.6.0_07 (Sun Microsystems Inc.)

Mixer: Direct Audio Device: DirectSound Playback [Primary Sound Driver]
Mixer: Direct Audio Device: DirectSound Playback [SoundMAX HD Audio]
Mixer: Direct Audio Device: DirectSound Capture [Primary Sound Capture Driver]
Mixer: Direct Audio Device: DirectSound Capture [SoundMAX HD Audio]
Mixer: Software mixer and synthesizer [Java Sound Audio Engine]
Mixer: Port Mixer [Port SoundMAX HD Audio]
  Source Port: MICROPHONE source port
    Control: Microphone (compound - values below)
      Control: Select (boolean)
      Control: Microphone Boost (boolean)
      Control: Front panel microphone (boolean)
      Control: Volume (float: from 0.0 to 1.0)
  Source Port: LINE_IN source port
    Control: Line In (compound - values below)
      Control: Select (boolean)
      Control: Volume (float: from 0.0 to 1.0)
      Control: Balance (float: from -1.0 to 1.0)

LastEditorDisplayName: sqook

ContentLicense: CC BY-SA 2.5


问:
How to create an empty file with Ansible?
What is the easiest way to create an empty file using Ansible? I know I can save an empty file into the files directory and then copy it to the remote host, but I find that somewhat unsatisfactory.

Another way is to touch a file on the remote host:

```<code>- name: create fake 'nologin' shell
  file: path=/etc/nologin state=touch owner=root group=sys mode=0555
</code>```

But then the file gets touched every time, showing up as a yellow line in the log, which is also unsatisfactory...

Is there any better solution to this simple problem?

答:
With ansible 2.7+ only

Ansible file module provide a way to touch file without modifying its time.

- name: touch a file, but do not change access time, making this task idempotent
  file:
    path: /etc/foo.conf
    state: touch
    mode: u+rw,g-wx,o-rwx
    modification_time: preserve
    access_time: preserve
```

Reference:
https://docs.ansible.com/ansible/latest/modules/file_module.html

Body:
What is the easiest way to create an empty file using Ansible? I know I can save an empty file into the files directory and then copy it to the remote host, but I find that somewhat unsatisfactory.

Another way is to touch a file on the remote host:

- name: create fake 'nologin' shell
  file: path=/etc/nologin state=touch owner=root group=sys mode=0555

But then the file gets touched every time, showing up as a yellow line in the log, which is also unsatisfactory...

Is there any better solution to this simple problem?

Body:
With ansible 2.7+ only

Ansible file module provide a way to touch file without modifying its time.

- name: touch a file, but do not change access time, making this task idempotent
  file:
    path: /etc/foo.conf
    state: touch
    mode: u+rw,g-wx,o-rwx
    modification_time: preserve
    access_time: preserve

Reference:
https://docs.ansible.com/ansible/latest/modules/file_module.html


问:
Check html syntax in string
I can not find a solution.

How to check string with the html code.

example

```<code><p><o:p></o:p></p>
<p> <br /> </p>
<p><b style=\"font-weight: bold;\"><b>Desc: </b>AnyText.</p>
 <br /> </p>
<p><b>Color:</b> green<
<p> <b>Param 2: AU55688</p>
<p><b>Param 3: </b>420 x 562</p>
<p><b>Height: </b>1425</p>
</code>```

If there are unclosed tags or undiscovered, then return string if all is well, then skip.

I found and modified function. But it does not work properly

```<code>function closetag($html)
{
    $ignore_tags = array('img', 'br', 'hr');

    preg_match_all ( "#<([a-z]+)( .*)?(?!/)>#iU", mb_strtolower($html), $result1);
    preg_match_all ( "#</([a-z]+)>#iU", mb_strtolower($html), $result2);
    $results_start = $result1[1];
    $results_end = $result2[1];

    $result = array();
    foreach($results_start AS $startag)
    {
        if (!in_array($startag, $results_end) && !in_array($startag, $ignore_tags))
        {
            $result['start_tags'][] = $startag;
        }
    }
    foreach($results_end AS $endtag)
    {
        if (!in_array($endtag, $results_start) && !in_array($endtag, $ignore_tags))
        {
            $result['end_tags'][] = $endtag;
        }
    }

    return ($result) ? $result : false;
}
</code>```

I do not need to correct the code, I need only determine that the syntax is not correct.

An example of what I want to get a result

```<code>$getTexts = $this->getTexts();

$no_valid = array();
foreach($getTexts AS $text)
{
    $_valid = check_html_systax_function($text);
    if (!$_valid)
    {
        $no_valid[] = $text;
    }
}
</code>```

check_html_systax_function checks texts for correct html syntax

$no_valid array of texts in which errors in html syntax

P.S. Sorry for my English!

答:
You can check html is valid  or not by following code : </p>

```<code>function closetags($html) {
    preg_match_all('#<(?!meta|img|br|hr|input\b)\b([a-z]+)(?: .*)?(?<![/|/ ])>#iU', $html, $result);
    $openedtags = $result[1];
    preg_match_all('#</([a-z]+)>#iU', $html, $result);
    $closedtags = $result[1];
    $len_opened = count($openedtags);
    if (count($closedtags) == $len_opened) {
        echo 'valid html';
    } else {
        echo 'invalid html';
    }
}

$html = '<p>This is some text and here is a <strong>bold text then the post stop here....</p>';
closetags($html);
</code>```

Title: Check html syntax in string

Body:
I can not find a solution.

How to check string with the html code.

example

<o:p></o:p>

Desc: AnyText.

Color: green<

 Param 2: AU55688

Param 3: 420 x 562

Height: 1425

If there are unclosed tags or undiscovered, then return string if all is well, then skip.

I found and modified function. But it does not work properly

function closetag($html)
{
    $ignore_tags = array('img', 'br', 'hr');

    preg_match_all ( "#<([a-z]+)( .*)?(?!/)>#iU", mb_strtolower($html), $result1);
    preg_match_all ( "#</([a-z]+)>#iU", mb_strtolower($html), $result2);
    $results_start = $result1[1];
    $results_end = $result2[1];

    $result = array();
    foreach($results_start AS $startag)
    {
        if (!in_array($startag, $results_end) && !in_array($startag, $ignore_tags))
        {
            $result['start_tags'][] = $startag;
        }
    }
    foreach($results_end AS $endtag)
    {
        if (!in_array($endtag, $results_start) && !in_array($endtag, $ignore_tags))
        {
            $result['end_tags'][] = $endtag;
        }
    }

    return ($result) ? $result : false;
}

I do not need to correct the code, I need only determine that the syntax is not correct.

An example of what I want to get a result

$getTexts = $this->getTexts();

$no_valid = array();
foreach($getTexts AS $text)
{
    $_valid = check_html_systax_function($text);
    if (!$_valid)
    {
        $no_valid[] = $text;
    }
}

check_html_systax_function checks texts for correct html syntax

$no_valid array of texts in which errors in html syntax

P.S. Sorry for my English!

Body:
You can check html is valid  or not by following code :

function closetags($html) {
    preg_match_all('#<(?!meta|img|br|hr|input\b)\b([a-z]+)(?: .*)?(?<![/|/ ])>#iU', $html, $result);
    $openedtags = $result[1];
    preg_match_all('#</([a-z]+)>#iU', $html, $result);
    $closedtags = $result[1];
    $len_opened = count($openedtags);
    if (count($closedtags) == $len_opened) {
        echo 'valid html';
    } else {
        echo 'invalid html';
    }
}

$html = '<p>This is some text and here is a <strong>bold text then the post stop here....</p>';
closetags($html);


问:
Hows Work Rewrite rules in mod_rewrite
i made a lot of changes in my webapp and the urls were like that..

http://miwebapp.com/public/module/action

But now i changed the directory structure and the public folder is now the webroot folder it's means that does not exists more.

now my urls looks at

http://miwebapp.com/module/action

I want to make a Apache Rewrite to catch the URLS that come with the public word..

Y try this..

```<code>RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^public/(.+)$ /$i [NC,L]
RewriteRule ^.*$ /index.php [NC,L]
</code>```

:D Thanks a lot :D

答:
Drop the first RewriteRule. All existing file (size not null + link) and all directories url are caught by your RewriteCondition and you set it to do nothing and be the last rule ([L]).
So everything goes through that only rule.

BTW: I'm not sure if $i does exists, but we use to get $1 instead.

Edit 1:

Yap I saw it too!
But I got the solution:

```<code>RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^public/(.+)$ /$1 [NC,L]

RewriteCond %{REQUEST_FILENAME} !-s
RewriteCond %{REQUEST_FILENAME} !-l
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ /index.php [NC,L]
</code>```

this should avoid rewriting all file to index.php in loops! (Note that when you do a redirect, the .htaccess is reprocessed with the new values, [L] just stop the rewrite for the current request)

Title: Hows Work Rewrite rules in mod_rewrite

Body:
i made a lot of changes in my webapp and the urls were like that..

http://miwebapp.com/public/module/action

But now i changed the directory structure and the public folder is now the webroot folder it's means that does not exists more.

now my urls looks at

http://miwebapp.com/module/action

I want to make a Apache Rewrite to catch the URLS that come with the public word..

Y try this..

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^public/(.+)$ /$i [NC,L]
RewriteRule ^.*$ /index.php [NC,L]

:D Thanks a lot :D

Body:
Drop the first RewriteRule. All existing file (size not null + link) and all directories url are caught by your RewriteCondition and you set it to do nothing and be the last rule ([L]).
So everything goes through that only rule.

BTW: I'm not sure if $i does exists, but we use to get $1 instead.

Edit 1:

Yap I saw it too!
But I got the solution:

RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^public/(.+)$ /$1 [NC,L]

RewriteCond %{REQUEST_FILENAME} !-s
RewriteCond %{REQUEST_FILENAME} !-l
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ /index.php [NC,L]

this should avoid rewriting all file to index.php in loops! (Note that when you do a redirect, the .htaccess is reprocessed with the new values, [L] just stop the rewrite for the current request)