问:
How does firestore's optimistic locking in transactions handle concurrent updates that cause a violation of a security rule?
Firestore documentation does not seem to specify when or how security rules are evaluated in a transaction and how that interacts with retries and optimistic locking.

My use case is straightforward, I have a lastUpdatedAt field on my documents and I'm using a transaction to ensure that I grab the latest document and check that the lastUpdatedAt field so I can resolve any conflicts before issuing an update.

In pseudocode the pattern is this

async function saveDocument(data: MyType, docRef: DocumentReference)
    await firebase.firestore().runTransaction(async (transaction) => {
        const latestDocRef = await transaction.get(docRef)
        const latestDoc = latestDocRef.data()

        if(latestDoc.lastUpdatedAt > data.lastUpdatedAt){
            data = resolveConflicts(data, latestDoc)
            data.lastUpdatedAt = latestDoc.lastUpdatedAt
        }

        await transaction.update(docRef, data)
    }
}
```
<p>Then in security rules I check to ensure that only updates with the latest or later lastUpdatedAt are allowed</p>
``` function hasNoLastUpdatedAtConflict(){
      return (!("lastUpdatedAt" in resource.data) ||
      resource.data.lastUpdatedAt == null ||
      request.resource.data.lastUpdatedAt >= resource.data.lastUpdatedAt);
 }

//in individualRules
  allow update: if  hasNoLastUpdatedAtConflict() && someOtherConditionsEtc();
```

The docs say

In the Mobile/Web SDKs, a transaction keeps track of all the documents you read inside the transaction. The transaction completes its write operations only if none of those documents changed during the transaction's execution. If any document did change, the transaction handler retries the transaction. If the transaction can't get a clean result after a few retries, the transaction fails due to data contention.

However they don't specify how that behavior interacts with security rules. My transaction above is failing somtimes with a security rule violation. It only fails on a live Firestore environment, I haven't been able to make it fail in the emulator. I suspect what's happening is:

Transaction starts, sends doc to client

A concurrent write happens which changes lastUpdatedAt

The client does not see the new write so it can't resolve the conflict and it issues the update as-is

The security rule now fails because of the concurrent write when it would have otherwise succeeded

Firestore fails the whole transaction with permission-denied instead of retrying due to dirty data

I suppose I could implement client side retry in the case a transaction is rejected by a security rule violation but it's very surprising behavior if this is indeed what is happening.

Does anybody have insight into the actual behavior of security rules and Firestore transactions with optimistic locking?

答:
As per the documentation and code sample, you can ensure that related documents are always updated atomically and always as part of a transaction or batch write using the getAfter() security rule function. It can be used to access and validate the state of a document after a set of operations completes but before Cloud Firestore commits the operations. Like get(), the getAfter() function takes a fully specified document path. You can use getAfter() to define sets of writes that must take place together as a transaction or batch.

These are some access call limits, which you may want to have a look at.

The documentation suggests that getAfter is useful to examine the contents of the database after the entire transaction's state would be recorded (in a sort of "staging" environment in memory), but before the transaction actually changes the database, visible to everyone. This is different from get(), because get() only looks at the actual contents of the database, before the transaction is finally committed. In short, getAfter() uses the entire staged write of the entire transaction or batch, while get uses the actual existing contents of the database.

getAfter() is useful when you need to examine other documents that may have been changed in the transaction or batch, and still have a chance to reject the entire transaction or batch by failing the rule. So, for example, if two documents being written in a single transaction must have some field value in common in order to be consistent, you need to use getAfter() to verify the equality between the two.

Point of note : The security rules for writes kick in before anything in the database has been changed by that write. That's how the security rules are able to safely and efficiently reject access, without having to roll back any writes that already happened.

Body:
Firestore documentation does not seem to specify when or how security rules are evaluated in a transaction and how that interacts with retries and optimistic locking.

My use case is straightforward, I have a lastUpdatedAt field on my documents and I'm using a transaction to ensure that I grab the latest document and check that the lastUpdatedAt field so I can resolve any conflicts before issuing an update.

In pseudocode the pattern is this

async function saveDocument(data: MyType, docRef: DocumentReference)
    await firebase.firestore().runTransaction(async (transaction) => {
        const latestDocRef = await transaction.get(docRef)
        const latestDoc = latestDocRef.data()

        if(latestDoc.lastUpdatedAt > data.lastUpdatedAt){
            data = resolveConflicts(data, latestDoc)
            data.lastUpdatedAt = latestDoc.lastUpdatedAt
        }

        await transaction.update(docRef, data)
    }
}

Then in security rules I check to ensure that only updates with the latest or later lastUpdatedAt are allowed

 function hasNoLastUpdatedAtConflict(){
      return (!("lastUpdatedAt" in resource.data) ||
      resource.data.lastUpdatedAt == null ||
      request.resource.data.lastUpdatedAt >= resource.data.lastUpdatedAt);
 }

//in individualRules
  allow update: if  hasNoLastUpdatedAtConflict() && someOtherConditionsEtc();

The docs say

In the Mobile/Web SDKs, a transaction keeps track of all the documents you read inside the transaction. The transaction completes its write operations only if none of those documents changed during the transaction's execution. If any document did change, the transaction handler retries the transaction. If the transaction can't get a clean result after a few retries, the transaction fails due to data contention.

However they don't specify how that behavior interacts with security rules. My transaction above is failing somtimes with a security rule violation. It only fails on a live Firestore environment, I haven't been able to make it fail in the emulator. I suspect what's happening is:

Transaction starts, sends doc to client

A concurrent write happens which changes lastUpdatedAt

The client does not see the new write so it can't resolve the conflict and it issues the update as-is

The security rule now fails because of the concurrent write when it would have otherwise succeeded

Firestore fails the whole transaction with permission-denied instead of retrying due to dirty data

I suppose I could implement client side retry in the case a transaction is rejected by a security rule violation but it's very surprising behavior if this is indeed what is happening.

Does anybody have insight into the actual behavior of security rules and Firestore transactions with optimistic locking?


来源: stackexchange

问:
Protect Deployments from manual deletion
We have an Azure-Kubernetes and use a helm chart to manage a list of deployments.

I would like to somehow block manual removal of the deployments. Deletion of the pods is fine, actually wanted to be able to "restart" the services inside to clean up cache and so on.

I'm sorry for the short question, am searching for a while but so far found nothing promising.

答:
You can configure the RBAC into the K8s cluster.

Role for the deployment manager

```<code>kind: Role
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
  name: deployment-manager
rules:
- apiGroups: ["*"]
  resources: ["deployments", "replicasets", "pods"]
  verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]
</code>```

Role for developer

```<code>kind: Role
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
  name: developer
rules:
- apiGroups: ["", "extensions", "apps"]
  resources: ["pods"]
  verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]
</code>```

Role binding deployment manager

```<code>kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
  name: deployment-manager-binding
subjects:
- kind: User
  name: admin
  apiGroup: ""
roleRef:
  kind: Role
  name: deployment-manager
  apiGroup: ""
</code>```

Role binding developer

```<code>kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
  name: developer-manager-binding
subjects:
- kind: User
  name: dev
  apiGroup: ""
roleRef:
  kind: Role
  name: developer
  apiGroup: ""
</code>```

You can create two new K8s contexts and using that check

```<code>kubectl --context=dev-context get pods
</code>```

You can read more at : https://docs.bitnami.com/tutorials/configure-rbac-in-your-kubernetes-cluster/

ContentLicense: CC BY-SA 4.0

Body:
You can configure the RBAC into the K8s cluster.

Role for the deployment manager

kind: Role
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
  name: deployment-manager
rules:
- apiGroups: ["*"]
  resources: ["deployments", "replicasets", "pods"]
  verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]

Role for developer

kind: Role
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
  name: developer
rules:
- apiGroups: ["", "extensions", "apps"]
  resources: ["pods"]
  verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]

Role binding deployment manager

kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
  name: deployment-manager-binding
subjects:
- kind: User
  name: admin
  apiGroup: ""
roleRef:
  kind: Role
  name: deployment-manager
  apiGroup: ""

Role binding developer

kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
  name: developer-manager-binding
subjects:
- kind: User
  name: dev
  apiGroup: ""
roleRef:
  kind: Role
  name: developer
  apiGroup: ""

You can create two new K8s contexts and using that check

kubectl --context=dev-context get pods

You can read more at : https://docs.bitnami.com/tutorials/configure-rbac-in-your-kubernetes-cluster/


问:
How to build regex to match values if they exists
I have a requirement to match the complete string if some part of value exists or not

For example :- Here are the list of strings that should be matched

en.key.value
fr.key.value
es.key.value
pt.key.value
key.value

So, length of string before first . can only be >=2.

Below are some values which should not be accepted

.key.value
z.key.value

Could someone please help ?
Thanks in advance

答:
You don't need to use regular expressions. You can split the string on the dots and check the length of the first part.

String[] strings = {"en.key.value",
                    "fr.key.value",
                    "es.key.value",
                    "pt.key.value",
                    "key.value",
                    ".key.value",
                    "z.key.value"};
for (String string : strings) {
    String[] parts = string.split("\\.");
    System.out.printf("[%b] %s%n", (parts[0].length() >= 2), string);
}
```
<p>Above code produces following output.</p>
<pre class="lang-none prettyprint-override"><code>[true] en.key.value
[true] fr.key.value
[true] es.key.value
[true] pt.key.value
[true] key.value
[false] .key.value
[false] z.key.value
</code>```

However, if you insist on using regular expressions, consider the following.

String[] strings = {"en.key.value",
                    "fr.key.value",
                    "es.key.value",
                    "pt.key.value",
                    "key.value",
                    ".key.value",
                    "z.key.value"};
Pattern pattern = Pattern.compile("^[a-z]{2,}\\.");
for (String string : strings) {
    Matcher matcher = pattern.matcher(string);
    System.out.printf("[%b] %s%n", matcher.find(), string);
}
```

Explanation of regular expression ^[a-z]{2,}\\.

^ start of string

[a-z] any lower-case letter of the English alphabet

{2,} two or more occurrences of the preceding

\\. literal dot

In other words, the above pattern matches strings that start with two or more lower-case characters followed by a single dot.

Body:
You don't need to use regular expressions. You can split the string on the dots and check the length of the first part.

String[] strings = {"en.key.value",
                    "fr.key.value",
                    "es.key.value",
                    "pt.key.value",
                    "key.value",
                    ".key.value",
                    "z.key.value"};
for (String string : strings) {
    String[] parts = string.split("\\.");
    System.out.printf("[%b] %s%n", (parts[0].length() >= 2), string);
}

Above code produces following output.

[true] en.key.value
[true] fr.key.value
[true] es.key.value
[true] pt.key.value
[true] key.value
[false] .key.value
[false] z.key.value

However, if you insist on using regular expressions, consider the following.

String[] strings = {"en.key.value",
                    "fr.key.value",
                    "es.key.value",
                    "pt.key.value",
                    "key.value",
                    ".key.value",
                    "z.key.value"};
Pattern pattern = Pattern.compile("^[a-z]{2,}\\.");
for (String string : strings) {
    Matcher matcher = pattern.matcher(string);
    System.out.printf("[%b] %s%n", matcher.find(), string);
}

Explanation of regular expression ^[a-z]{2,}\\.

^ start of string

[a-z] any lower-case letter of the English alphabet

{2,} two or more occurrences of the preceding

\\. literal dot

In other words, the above pattern matches strings that start with two or more lower-case characters followed by a single dot.


问:
calva - how to stop the repl?
I'm using vs code with calva on Ubuntu. My clojure app listens on a port and I find that if I exit vs code, it leaves a java process bound to that port which I have to locate and kill before I can start again.

Is there any calva command to stop the repl?, or better still, a way of stopping the repl automatically when I exit vs code?

答:
From the comments I've figured out that I was really asking the wrong question. I was under the impression that the repl was "owned by" to the vs code process that started it and that not terminating it when you quit vs code was a bug, but really my understanding wasn't right.

So to solve my original problem of leaving a process bound to the port, there are 3 options:

Terminate the repl using clojure (System/exit 0)

Use the calva command to reconnect to the existing repl after restarting vs code

Use calva to disconnect from the repl, then you have the choice of
starting a new one (which automatically will kill the old one) or re-connecting later

Title: calva - how to stop the repl?


问:
JQuery duplicate HTML div and edit its content before appending to html body
I have a  that contains some input fields like so:

```<code> <div class="px-4 py-6 mb-4 border rounded-lg border-gray-400" id="datarow"

<div class="flex flex-row space-x-4 pb-5">
    <div class="relative z-0 w-full mb-5">
        <input type="text" id="f_name" name="f_name" placeholder="Enter Name here"
            required class="pt-3 pb-2 block w-full px-4 mt-0 rounded bg-white border-0 border-b appearance-none" />
        <label for="f_name" class="absolute duration-300 pl-2 text-lg top-3 z-1 origin-0 text-gray-500">Name</label>
    </div>

    <div class="flex z-0 w-full justify-end">
        <input type="text" id="f_dest" name="f_dest" placeholder="Enter Destination here"
            required class="pt-3 pb-2 block w-full px-4 mt-0 rounded bg-white border-0 border-b appearance-none" />
        <label for="f_dest" class="absolute duration-300 pl-2 text-lg top-3 z-1 origin-0 text-gray-500">Destination</label>
    </div>
</div>
</code>```

And in jQuery I am duplicating the above div (on button click) and just appending to the main html body which would be displayed just below the original #datarow div. Heres the full snippet as how I have in my program.

$("#btn_addsector").click(function () {
    var div = document.getElementById("datarow"),
        clone = div.cloneNode(true);

     //neither of the lines work
     $(clone).find("#f_name").text = "Tisha";
    $("#maincontent").append(clone);
    $(clone).find("#f_name").text = "Tisha";
    $(clone).find("#f_name").text("Tisha");
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="maincontent" >
<button id="btn_addsector"
        class="bg-transparent hover:bg-secondary-dark text-secondary-dark font-semibold hover:text-white py-2 px-4 border border-secondary-dark hover:border-transparent rounded">
        Add Sector
    </button>

 <div class="px-4 py-6 mb-4 border rounded-lg border-gray-400" id="datarow">

    <div class="flex flex-row space-x-4 pb-5">
        <div class="relative z-0 w-full mb-5">
            <input type="text" id="f_name" name="f_name" placeholder="Enter Name here" value="Hannah"
                required class="pt-3 pb-2 block w-full px-4 mt-0 rounded bg-white border-0 border-b appearance-none" />
            <label for="f_name" class="absolute duration-300 pl-2 text-lg top-3 z-1 origin-0 text-gray-500">Name</label>
        </div>

        <div class="flex z-0 w-full justify-end">
            <input type="text" id="f_dest" name="f_dest" placeholder="Enter Destination here" value="Smallville"
                required class="pt-3 pb-2 block w-full px-4 mt-0 rounded bg-white border-0 border-b appearance-none" />
            <label for="f_dest" class="absolute duration-300 pl-2 text-lg top-3 z-1 origin-0 text-gray-500">Destination</label>
        </div>
    </div>
</div>

</div></code>```

I can get the cloned div to appended properly but it does not alter the text of the input field.

答:
There is multiple problem with your code:

1: You can't have multiple elements with the same ID, use class for this. So I've removed the id="f_name" and added it to the class selector class="the previous classes f_name"

2: To set the value of an input, you have to use .val() and not .text()

```<code>$(clone).find(".f_name").val("Tisha");
</code>```

Demo

$("#btn_addsector").click(function() {
  var div = document.getElementById("datarow"),
    clone = div.cloneNode(true);

  //neither of the lines work
  $(clone).find(".f_name").val("Tisha");
  $("#maincontent").append(clone);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="maincontent">
  <button id="btn_addsector" class="bg-transparent hover:bg-secondary-dark text-secondary-dark font-semibold hover:text-white py-2 px-4 border border-secondary-dark hover:border-transparent rounded">
        Add Sector
    </button>

  <div class="px-4 py-6 mb-4 border rounded-lg border-gray-400" id="datarow">

    <div class="flex flex-row space-x-4 pb-5">
      <div class="relative z-0 w-full mb-5">
        <input type="text" name="f_name" placeholder="Enter Name here" value="Hannah" required class="pt-3 pb-2 block w-full px-4 mt-0 rounded bg-white border-0 border-b appearance-none f_name" />
        <label for="f_name" class="absolute duration-300 pl-2 text-lg top-3 z-1 origin-0 text-gray-500">Name</label>
      </div>

      <div class="flex z-0 w-full justify-end">
        <input type="text" name="f_dest" placeholder="Enter Destination here" value="Smallville" required class="pt-3 pb-2 block w-full px-4 mt-0 rounded bg-white border-0 border-b appearance-none f_dest" />
        <label for="f_dest" class="absolute duration-300 pl-2 text-lg top-3 z-1 origin-0 text-gray-500">Destination</label>
      </div>
    </div>
  </div>

</div></code>```

Body:
I have a  that contains some input fields like so:

 <div class="px-4 py-6 mb-4 border rounded-lg border-gray-400" id="datarow"

        <input type="text" id="f_name" name="f_name" placeholder="Enter Name here"
            required class="pt-3 pb-2 block w-full px-4 mt-0 rounded bg-white border-0 border-b appearance-none" />
        Name

        <input type="text" id="f_dest" name="f_dest" placeholder="Enter Destination here"
            required class="pt-3 pb-2 block w-full px-4 mt-0 rounded bg-white border-0 border-b appearance-none" />
        Destination

And in jQuery I am duplicating the above div (on button click) and just appending to the main html body which would be displayed just below the original #datarow div. Heres the full snippet as how I have in my program.

$("#btn_addsector").click(function () {
    var div = document.getElementById("datarow"),
        clone = div.cloneNode(true);

     //neither of the lines work
     $(clone).find("#f_name").text = "Tisha";
    $("#maincontent").append(clone);
    $(clone).find("#f_name").text = "Tisha";
    $(clone).find("#f_name").text("Tisha");
    });

<button id="btn_addsector"
        class="bg-transparent hover:bg-secondary-dark text-secondary-dark font-semibold hover:text-white py-2 px-4 border border-secondary-dark hover:border-transparent rounded">
        Add Sector
    </button>

            <input type="text" id="f_name" name="f_name" placeholder="Enter Name here" value="Hannah"
                required class="pt-3 pb-2 block w-full px-4 mt-0 rounded bg-white border-0 border-b appearance-none" />
            Name

            <input type="text" id="f_dest" name="f_dest" placeholder="Enter Destination here" value="Smallville"
                required class="pt-3 pb-2 block w-full px-4 mt-0 rounded bg-white border-0 border-b appearance-none" />
            Destination

I can get the cloned div to appended properly but it does not alter the text of the input field.

Body:
There is multiple problem with your code:

1: You can't have multiple elements with the same ID, use class for this. So I've removed the id="f_name" and added it to the class selector class="the previous classes f_name"

2: To set the value of an input, you have to use .val() and not .text()

$(clone).find(".f_name").val("Tisha");

Demo

$("#btn_addsector").click(function() {
  var div = document.getElementById("datarow"),
    clone = div.cloneNode(true);

  //neither of the lines work
  $(clone).find(".f_name").val("Tisha");
  $("#maincontent").append(clone);
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="maincontent">
  <button id="btn_addsector" class="bg-transparent hover:bg-secondary-dark text-secondary-dark font-semibold hover:text-white py-2 px-4 border border-secondary-dark hover:border-transparent rounded">
        Add Sector
    </button>

  <div class="px-4 py-6 mb-4 border rounded-lg border-gray-400" id="datarow">

    <div class="flex flex-row space-x-4 pb-5">
      <div class="relative z-0 w-full mb-5">
        <input type="text" name="f_name" placeholder="Enter Name here" value="Hannah" required class="pt-3 pb-2 block w-full px-4 mt-0 rounded bg-white border-0 border-b appearance-none f_name" />
        <label for="f_name" class="absolute duration-300 pl-2 text-lg top-3 z-1 origin-0 text-gray-500">Name</label>
      </div>

      <div class="flex z-0 w-full justify-end">
        <input type="text" name="f_dest" placeholder="Enter Destination here" value="Smallville" required class="pt-3 pb-2 block w-full px-4 mt-0 rounded bg-white border-0 border-b appearance-none f_dest" />
        <label for="f_dest" class="absolute duration-300 pl-2 text-lg top-3 z-1 origin-0 text-gray-500">Destination</label>
      </div>
    </div>
  </div>

</div>


问:
Translating excel formula into power query language
Could someone please assist with helping me create a formula using Power Query that performs the same as the following Excel formula?

```<code>=iferror(iferror(if(value(left([Qualifications],1))>0,right([Qualifications],len([Qualifications])-7),""),left([Qualifications],find("/",[Qualifications])-4)),[Qualifications])
</code>```

Essentially I am trying to strip out expiration dates from a column which contains the qualification title and expiration date (if any) at the end of the title, ideally to just show the qualification title. As some of the qualifications use () in the title, I need to search for the presence of / in the title and remove characters around these.

As I'm new to using Power Query, it's proving a little time consuming trying to learn and understand the different language to Excel!

EDIT - This is the Token Eof error I receive when pasting the provided code:

enter image description here

EDIT 2 - This is the error that is showing in multiple rows, including the row with the date at the end

enter image description here

答:
A powerquery solution .. Assuming you want to remove (##/##/####) then

Paste below into a blank query in home ... advanced editor ... name it RegExReplace and then file .. close and load

```<code>/*
https://www.mathscinotes.com/2020/02/power-query-regular-expression-hack/
Mark Biegert
Modified version of regex routine documented by Imke Feldman at
https://www.thebiccountant.com/2018/04/25/regex-in-power-bi-and-power-query-in-excel-with-java-script/
Input Parameter:
x : String to be searched
y : Search regex
z : Replacement regex
*/
(x,y,z)=>
let Source = Web.Page(
"<script>var x="&"'"&x&"'"&";var z="&"'"&z&
"'"&";var y=new RegExp('"&y&"','g');
var b=x.replace(y,z);document.write(b);</script>")
[Data]{0}[Children]{0}[Children]{1}[Text]{0}
in Source
</code>```

Then in your data to clean, Add column .. custom column .. with formula

```<code>= RegExReplace([YourColumnName],"\\(\\d{2}\/\\d{2}\/\\d{4}\\)","")
</code>```

Body:
Could someone please assist with helping me create a formula using Power Query that performs the same as the following Excel formula?

=iferror(iferror(if(value(left([Qualifications],1))>0,right([Qualifications],len([Qualifications])-7),""),left([Qualifications],find("/",[Qualifications])-4)),[Qualifications])

Essentially I am trying to strip out expiration dates from a column which contains the qualification title and expiration date (if any) at the end of the title, ideally to just show the qualification title. As some of the qualifications use () in the title, I need to search for the presence of / in the title and remove characters around these.

As I'm new to using Power Query, it's proving a little time consuming trying to learn and understand the different language to Excel!

EDIT - This is the Token Eof error I receive when pasting the provided code:

enter image description here

EDIT 2 - This is the error that is showing in multiple rows, including the row with the date at the end

enter image description here

Body:
A powerquery solution .. Assuming you want to remove (##/##/####) then

Paste below into a blank query in home ... advanced editor ... name it RegExReplace and then file .. close and load

/*
https://www.mathscinotes.com/2020/02/power-query-regular-expression-hack/
Mark Biegert
Modified version of regex routine documented by Imke Feldman at
https://www.thebiccountant.com/2018/04/25/regex-in-power-bi-and-power-query-in-excel-with-java-script/
Input Parameter:
x : String to be searched
y : Search regex
z : Replacement regex
*/
(x,y,z)=>
let Source = Web.Page(
"<script>var x="&"'"&x&"'"&";var z="&"'"&z&
"'"&";var y=new RegExp('"&y&"','g');
var b=x.replace(y,z);document.write(b);</script>")
[Data]{0}[Children]{0}[Children]{1}[Text]{0}
in Source

Then in your data to clean, Add column .. custom column .. with formula

= RegExReplace([YourColumnName],"\\(\\d{2}\/\\d{2}\/\\d{4}\\)","")


问:
Confused when I should and shouldn't use "const" in C
I have a dictionary that goes like this:

```<code>typedef struct dictNode {
    int key;
    char *value;
    struct dictNode *next;
} Dict;
</code>```

And a get() function that goes like this:

```<code>char *get(const Dict *dict, int key) {
    if(!dict) return NULL;

    Dict *currPtr = dict;

    while(currPtr) {
        if(currPtr->key == key) {
            return currPtr->value;
        }

        currPtr = currPtr->next;
    }
}
</code>```

Compiling this code produces the following error:

dict.c:85: warning: initialization discards qualifiers from pointer target type

This warning refers to the line:

```<code>Dict *currPtr = dict;
</code>```

If I add a "const" before that line like this:

```<code>const Dict *currPtr = dict;
</code>```

The warning goes away...

1) First thing I don't understand is this: I added "const" to the dict argument in get() so that the compiler warns me if I try to change the address dict is pointing to, otherwise I won't be able to access the dictionary in the main program cause I lost the address I was pointing too. Now, I'm creating a new pointer, currPtr, that points to the same place as dict. This way, I use this pointer instead, to traverse the dictionary and keep dict pointer intact. Why do I also need to have const for currPtr?

2) Second thing I don't understand is this: The line currPtr = currPtr->next; is changing the currPtr pointer, so, why doesn't the compile warn me about that if I added a const to currPtr?

Then I have a del() function that goes like this:

```<code>Dict *del(const Dict *dict, int key) {
    if(!dict) return NULL;

    Dict *currPtr = dict;
    Dict *prevPtr = dict;

    while(currPtr) {
        if(currPtr->key == key) {
            prevPtr->next = currPtr->next;
            free(currPtr);
        }

        prevPtr = currPtr;
        currPtr = currPtr->next;
    }

    return dict;
}
</code>```

Please note that I'm aware that this delete function code is not complete, it does not correctly work if I want to delete the first element for instance. It doesn't matter, I'll finish later, it suffices to demonstrate my problem...

3) So, in the get() function I needed to add const to currPtr but in this del() function, I don't need to add const to currPtr nor prevPtr? In both functions I am changing the currPtr pointer and in the case of the del() function I'm changing the prevPtr pointer too. Why does the get() function require me to add a const before currPtr and the del() function does not require me to add a const before currPtr and prevPtr?

I can basically resume this whole post to: When and where exactly in my get() and del() functions should I use const and why, and, when and where I shouldn't?

答:
I get most of the things you people are saying, what I don't get now, is this...

Consider the following list() function:

```<code>void list(Dict *dict) {
    if(!dict) return;

    while(dict) {
        printf("KEY: %d\n", dict->key);
        printf("VALUE: %s\n", dict->value);

        dict = dict->next;
    }
}
</code>```

(it's simpler to use this one instead of the get() one)

In my main I have two calls to this function, like:

```<code>list(dict);
list(dict);
</code>```

Of course, dict has some entries inserted...

To my understanding, only the first list() should output something because the dict pointer is being changed in the list() function and will eventually point to NULL (otherwise we would be in an infinite while loop in the list() call). What's happening is that the second list() call is also outputting the same dictionary, when I think it shouldn't output anything because dict should be NULL, no?

OwnerDisplayName: Nazgulled

ContentLicense: CC BY-SA 2.5

Body:
I have a dictionary that goes like this:

typedef struct dictNode {
    int key;
    char *value;
    struct dictNode *next;
} Dict;

And a get() function that goes like this:

char *get(const Dict *dict, int key) {
    if(!dict) return NULL;

    Dict *currPtr = dict;

    while(currPtr) {
        if(currPtr->key == key) {
            return currPtr->value;
        }

        currPtr = currPtr->next;
    }
}

Compiling this code produces the following error:

dict.c:85: warning: initialization discards qualifiers from pointer target type

This warning refers to the line:

Dict *currPtr = dict;

If I add a "const" before that line like this:

const Dict *currPtr = dict;

The warning goes away...

1) First thing I don't understand is this: I added "const" to the dict argument in get() so that the compiler warns me if I try to change the address dict is pointing to, otherwise I won't be able to access the dictionary in the main program cause I lost the address I was pointing too. Now, I'm creating a new pointer, currPtr, that points to the same place as dict. This way, I use this pointer instead, to traverse the dictionary and keep dict pointer intact. Why do I also need to have const for currPtr?

2) Second thing I don't understand is this: The line currPtr = currPtr->next; is changing the currPtr pointer, so, why doesn't the compile warn me about that if I added a const to currPtr?

Then I have a del() function that goes like this:

Dict *del(const Dict *dict, int key) {
    if(!dict) return NULL;

    Dict *currPtr = dict;
    Dict *prevPtr = dict;

    while(currPtr) {
        if(currPtr->key == key) {
            prevPtr->next = currPtr->next;
            free(currPtr);
        }

        prevPtr = currPtr;
        currPtr = currPtr->next;
    }

    return dict;
}

Please note that I'm aware that this delete function code is not complete, it does not correctly work if I want to delete the first element for instance. It doesn't matter, I'll finish later, it suffices to demonstrate my problem...

3) So, in the get() function I needed to add const to currPtr but in this del() function, I don't need to add const to currPtr nor prevPtr? In both functions I am changing the currPtr pointer and in the case of the del() function I'm changing the prevPtr pointer too. Why does the get() function require me to add a const before currPtr and the del() function does not require me to add a const before currPtr and prevPtr?

I can basically resume this whole post to: When and where exactly in my get() and del() functions should I use const and why, and, when and where I shouldn't?

Body:
I get most of the things you people are saying, what I don't get now, is this...

Consider the following list() function:

void list(Dict *dict) {
    if(!dict) return;

    while(dict) {
        printf("KEY: %d\n", dict->key);
        printf("VALUE: %s\n", dict->value);

        dict = dict->next;
    }
}

(it's simpler to use this one instead of the get() one)

In my main I have two calls to this function, like:

list(dict);
list(dict);

Of course, dict has some entries inserted...

To my understanding, only the first list() should output something because the dict pointer is being changed in the list() function and will eventually point to NULL (otherwise we would be in an infinite while loop in the list() call). What's happening is that the second list() call is also outputting the same dictionary, when I think it shouldn't output anything because dict should be NULL, no?


问:
CSS checking if input is checked and chaining elements
I cannot make this work, guys. The problem is I no longer have idea how to (try to) make it work.

#5starcheckbox:checked+label[for="5starcheckbox"]>.col-lg-10>.progress>.progress-bar {
  opacity: 1 !important;
}

input#5starcheckbox:checked+span#5starpercentage {
  color: #0060df !important;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label for="5starcheckbox" class="row filterlabel">
    <div class="col-lg-1 col-1">
        <div class="checkboxes text-end">

                <input type="checkbox" id="5starcheckbox" name="stars[]" value="5">
                <span class="checkmark"></span>

        </div>
    </div>
    <div class="col-lg-10 col-9 pt-1">
        <div class="progress">
            <div class="progress-bar progress5" role="progressbar" style="width: {{ $scoreInfo['percent_5_star'] }}%;opacity:0.6;" aria-valuenow="{{ $scoreInfo['percent_5_star'] }}" aria-valuemin="0" aria-valuemax="100"></div>
        </div>
    </div>
    <div class="col-lg-1 col-2 text-end text-secondary" id="5starpercentage"><strong>{{ $scoreInfo['percent_5_star'] }}%</strong></div>
</label></code>```

Is there something wrong in my code? Why it isn't working?

答:
I resorted to jQuery to do this.

$("#form").on('change', function() {
    for(i = 1; i <= 5; i++) {
        checkbox = $("#" + i + "starcheckbox");
        checked = checkbox.is(":checked");
        if(checked == true) {
            $("#" + i + "starpercentage").removeClass('text-secondary').addClass('text-primary');
            $(".progress" + i).css('opacity', '1.0');
        } else {
            $("#" + i + "starpercentage").removeClass('text-primary').addClass('text-secondary');
            $(".progress" + i).css('opacity', '0.4');
        }
    }
});
```

Body:
I cannot make this work, guys. The problem is I no longer have idea how to (try to) make it work.

#5starcheckbox:checked+label[for="5starcheckbox"]>.col-lg-10>.progress>.progress-bar {
  opacity: 1 !important;
}

input#5starcheckbox:checked+span#5starpercentage {
  color: #0060df !important;
}

                <input type="checkbox" id="5starcheckbox" name="stars[]" value="5">

{{ $scoreInfo['percent_5_star'] }}%

Is there something wrong in my code? Why it isn't working?


问:
Excel INDEX MATCH COUNTIF
I know this is very simple, but I'm quite stuck on that. I have a very simple file with the following columns:

I need to count how many people have chosen the fruit specified in column C.
I tried to do something like

```<code>=INDEX($B$1:$B$8,MATCH("*"&$C1&"*",$A$1:$A$8,0))
</code>```

And it correctly finds the first person corresponding to a given fruit, but how to make it count the total number of people?
I've tried using countif, but I'm missing something...

答:
```<code>=COUNTIF(A1:A8,"*apple*")
</code>```

and if you want to use the cell as a reference

```<code>=COUNTIF($A$1:$A$8,"*"&C1&"*")
</code>```

Title: Excel INDEX MATCH COUNTIF

Body:
I know this is very simple, but I'm quite stuck on that. I have a very simple file with the following columns:

I need to count how many people have chosen the fruit specified in column C.
I tried to do something like

=INDEX($B$1:$B$8,MATCH("*"&$C1&"*",$A$1:$A$8,0))

And it correctly finds the first person corresponding to a given fruit, but how to make it count the total number of people?
I've tried using countif, but I'm missing something...

Body:
=COUNTIF(A1:A8,"*apple*")

and if you want to use the cell as a reference

=COUNTIF($A$1:$A$8,"*"&C1&"*")


问:
ForEach-Object -Parallel How to use it
I'm starting to use ForEach-Object -Parallel with PowerShell 7. I'm testing following code:

```<code>$MyArr = @()
$MyArr = (
    ('v1ne','rgNE'),`
    ('v1we','rgWE')
)

$MyArr | ForEach-Object -Parallel  {
    Start-AzVM -Name $MyArr[0]  -ResourceGroupName $MyArr[1]
} -ThrottleLimit 10
</code>```

To start up some virtual machine on azure in different Resource Groups. My idea is to get variable from array or from Azure automation variables. But I don't know how to pass different Resource Group Names in ForEach-Object -Parallel.

Any help is really appreciate.

答:
As Mathias explained in comments, when using ForEach-Object -Parallel, you would need to use $_ (also known as $PSItem) to reference the current object from pipeline (same applies for ForEach-Object). If you want to reference a variable that is not coming from pipeline you would use the $using: keyworkd.

Example:

```<code>$notFromPipeline = 'Hello'

0..5 | ForEach-Object -Parallel {
    "$using:notFromPipeline $_"
}
</code>```

As for, how you could approach your script, I think splatting with $_ seems fit for this, suppose you had a CSV with the VM Names and their corresponding Resource Groups, something like:

VMs.csv

```<code>Name,ResourceGroupName
v1ne,rgNE
v1we,rgwE
</code>```

You could do something like this, note, below example is using a function (TestSplat) just to show you how the parameters are bound using splatting with a hash table, in your case, you would replace this function for Start-AzVM.

First you can create an array of hash tables like this:

```<code>$myParams = Import-Csv ./VMs.csv | ForEach-Object {
    $z = @{}
    foreach($prop in $_.PSObject.Properties) {
        $z[$prop.Name] = $prop.Value
    }
    $z
}
</code>```

$myParams would be something like this:

```<code>Name                           Value
----                           -----
Name                           v1ne
ResourceGroupName              rgNE
Name                           v1we
ResourceGroupName              rgwE
</code>```

The column names of your CSV must match with the Parameter Names of Start-VM (Name and ResourceGroupName).

Now you can iterate over $myParams using ForEach-Object -Parallel:

```<code>$myParams | ForEach-Object -Parallel  {
    function TestSplat {
        param($Name, $ResourceGroupName)
        Write-Host "Name: $Name - ResourceGroup: $ResourceGroupName"
    }

    TestSplat @_
} -ThrottleLimit 10
</code>```

Which should result in:

```<code>Name: v1ne - ResourceGroup: rgNE
Name: v1we - ResourceGroup: rgwE
</code>```

Title: ForEach-Object -Parallel How to use it

Body:
I'm starting to use ForEach-Object -Parallel with PowerShell 7. I'm testing following code:

$MyArr = @()
$MyArr = (
    ('v1ne','rgNE'),`
    ('v1we','rgWE')
)

$MyArr | ForEach-Object -Parallel  {
    Start-AzVM -Name $MyArr[0]  -ResourceGroupName $MyArr[1]
} -ThrottleLimit 10

To start up some virtual machine on azure in different Resource Groups. My idea is to get variable from array or from Azure automation variables. But I don't know how to pass different Resource Group Names in ForEach-Object -Parallel.

Any help is really appreciate.

Body:
As Mathias explained in comments, when using ForEach-Object -Parallel, you would need to use $_ (also known as $PSItem) to reference the current object from pipeline (same applies for ForEach-Object). If you want to reference a variable that is not coming from pipeline you would use the $using: keyworkd.

Example:

$notFromPipeline = 'Hello'

0..5 | ForEach-Object -Parallel {
    "$using:notFromPipeline $_"
}

As for, how you could approach your script, I think splatting with $_ seems fit for this, suppose you had a CSV with the VM Names and their corresponding Resource Groups, something like:

VMs.csv

Name,ResourceGroupName
v1ne,rgNE
v1we,rgwE

You could do something like this, note, below example is using a function (TestSplat) just to show you how the parameters are bound using splatting with a hash table, in your case, you would replace this function for Start-AzVM.

First you can create an array of hash tables like this:

$myParams = Import-Csv ./VMs.csv | ForEach-Object {
    $z = @{}
    foreach($prop in $_.PSObject.Properties) {
        $z[$prop.Name] = $prop.Value
    }
    $z
}

$myParams would be something like this:

Name                           Value
----                           -----
Name                           v1ne
ResourceGroupName              rgNE
Name                           v1we
ResourceGroupName              rgwE

The column names of your CSV must match with the Parameter Names of Start-VM (Name and ResourceGroupName).

Now you can iterate over $myParams using ForEach-Object -Parallel:

$myParams | ForEach-Object -Parallel  {
    function TestSplat {
        param($Name, $ResourceGroupName)
        Write-Host "Name: $Name - ResourceGroup: $ResourceGroupName"
    }

    TestSplat @_
} -ThrottleLimit 10

Which should result in:

Name: v1ne - ResourceGroup: rgNE
Name: v1we - ResourceGroup: rgwE


问:
Traversing through TBXML on iphone / xcode SDK help?
I've got an xml file which i'm struggling to traverse through. I'll let you know from the off i'm new to xcode. I tried following another guide on here:

iPhone TBXML Looping And Parsing Data but for some reason it doesn't seem to work for me.

Here's my XML File:

```<code><Locations action="Request" version="1.0">
     <location>
       <CompanyID>44502</CompanyID>
       <CompanyName>Holiday Inn</CompanyName>
       <Distance>3.58km/2.23miles</Distance>
         <tabs>
           <tab>General Information</tab>
           <tab>Add Review</tab>
         </tabs>
       <Address>
           <Address1>Holiday Inn Reading - South</Address1>
           <Address2>500 Basingstoke Road</Address2>
           <Address3/>
           <PostTown>Reading</PostTown>
           <County/>
           <PostCode>RG2 0SL</PostCode>
       </Address>
     </location>
</Locations>
</code>```

I'm trying to traverse through this with TBXML to grab each of the items (I managed to do it with one, but couldn't loop through).

The .h file is:

```<code>@interface LoadXML : UIViewController {

    IBOutlet UITableView *tblLoadXML;
    NSMutableArray *records;
    }
@property(nonatomic,retain)NSMutableArray *records;

-(void)loadRecords:(NSString *)records;
-(void)traverseElement:(TBXMLElement *)element;

@end
</code>```

However I'm getting 2 errors on that saying: `Expected a type and Expected ')' before TBXMLElement.

My .M file has the following:

```<code>-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *Cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (Cell == nil) {
        Cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
    }

    Cell.text = [records objectAtIndex:indexPath.row];

}

- (void)loadRecords:(NSString *)records {
    NSString *someXML = @"http://de0937/directenquirieswebapplicationv3.0/mobilesearch/what/0/49424/342/0/Reading/Hotels%20and%20Inns/0/0/0/0/0/search.aspx";
    TBXML *tbxml = [[TBXML tbxmlWithURL:[NSURL URLWithString:someXML]] retain];

    records = [NSMutableArray array];
    [records retain];

    if (tbxml.rootXMLElement)
        [self traverseElement:tbxml.rootXMLElement];
    [tbxml release];
}

- (void) traverseElement:(TBXMLElement *)element {
    do {
        if (element->firstChild)
            [self traverseElement:element->firstChild];

        if ([[TBXML elementName:element] isEqualToString:@"location"]) {
            TBXMLElement *name = [TBXML childElementNamed:@"CompanyName" parentElement:element];
            TBXMLElement *distance = [TBXML childElementNamed:@"Distance" parentElement:element];

            TBXMLElement *id = [TBXML childElementNamed:@"ID" parentElement:element];

            [records addObject:[NSArray arrayWithObjects:
                                [TBXML textForElement:name],
                                [TBXML textForElement:distance],
                                [TBXML textForElement:id],nil]];
        }
    } while ((element = element->nextSibling));
}
</code>```

I'm probably doing something very stupid, but it's driving me insane! Any help will be much appreciated.

--- This is what I had before, and it works perfectly but only for one record. Basically what i'm trying to do is convert this so I can put each item as an array and pull it out at will:

```<code>-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *Cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (Cell == nil) {
        Cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
    }

    TBXML * XML = [[TBXML tbxmlWithURL:[NSURL URLWithString:@"http://www.tomstest.info/ios/results.xml"]] retain];

    TBXMLElement *rootXML = XML.rootXMLElement;
    TBXMLElement *results = [TBXML childElementNamed:@"location" parentElement:rootXML];
    TBXMLElement *WOEID = [TBXML childElementNamed:@"CompanyName" parentElement:results];
    NSString *woeid = [TBXML textForElement:WOEID];

    Cell.text = woeid;
    return Cell;

}
</code>```

答: Based on the error, are you #including TBXML.h from the .h file?  Alternatively, you could @class TBXMLElement; in the .h file and an import in the .m file.

ContentLicense: CC BY-SA 3.0

Body:
I've got an xml file which i'm struggling to traverse through. I'll let you know from the off i'm new to xcode. I tried following another guide on here:

iPhone TBXML Looping And Parsing Data but for some reason it doesn't seem to work for me.

Here's my XML File:

<Locations action="Request" version="1.0">
     <location>
       <CompanyID>44502</CompanyID>
       <CompanyName>Holiday Inn</CompanyName>
       <Distance>3.58km/2.23miles</Distance>
         <tabs>
           <tab>General Information</tab>
           <tab>Add Review</tab>
         </tabs>
       <Address>
           <Address1>Holiday Inn Reading - South</Address1>
           <Address2>500 Basingstoke Road</Address2>
           <Address3/>
           <PostTown>Reading</PostTown>
           <County/>
           <PostCode>RG2 0SL</PostCode>
       </Address>
     </location>
</Locations>

I'm trying to traverse through this with TBXML to grab each of the items (I managed to do it with one, but couldn't loop through).

The .h file is:

@interface LoadXML : UIViewController {

    IBOutlet UITableView *tblLoadXML;
    NSMutableArray *records;
    }
@property(nonatomic,retain)NSMutableArray *records;

-(void)loadRecords:(NSString *)records;
-(void)traverseElement:(TBXMLElement *)element;

@end

However I'm getting 2 errors on that saying: `Expected a type and Expected ')' before TBXMLElement.

My .M file has the following:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *Cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (Cell == nil) {
        Cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
    }

    Cell.text = [records objectAtIndex:indexPath.row];

}

- (void)loadRecords:(NSString *)records {
    NSString *someXML = @"http://de0937/directenquirieswebapplicationv3.0/mobilesearch/what/0/49424/342/0/Reading/Hotels%20and%20Inns/0/0/0/0/0/search.aspx";
    TBXML *tbxml = [[TBXML tbxmlWithURL:[NSURL URLWithString:someXML]] retain];

    records = [NSMutableArray array];
    [records retain];

    if (tbxml.rootXMLElement)
        [self traverseElement:tbxml.rootXMLElement];
    [tbxml release];
}

- (void) traverseElement:(TBXMLElement *)element {
    do {
        if (element->firstChild)
            [self traverseElement:element->firstChild];

        if ([[TBXML elementName:element] isEqualToString:@"location"]) {
            TBXMLElement *name = [TBXML childElementNamed:@"CompanyName" parentElement:element];
            TBXMLElement *distance = [TBXML childElementNamed:@"Distance" parentElement:element];

            TBXMLElement *id = [TBXML childElementNamed:@"ID" parentElement:element];

            [records addObject:[NSArray arrayWithObjects:
                                [TBXML textForElement:name],
                                [TBXML textForElement:distance],
                                [TBXML textForElement:id],nil]];
        }
    } while ((element = element->nextSibling));
}

I'm probably doing something very stupid, but it's driving me insane! Any help will be much appreciated.

--- This is what I had before, and it works perfectly but only for one record. Basically what i'm trying to do is convert this so I can put each item as an array and pull it out at will:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *Cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (Cell == nil) {
        Cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
    }

    TBXML * XML = [[TBXML tbxmlWithURL:[NSURL URLWithString:@"http://www.tomstest.info/ios/results.xml"]] retain];

    TBXMLElement *rootXML = XML.rootXMLElement;
    TBXMLElement *results = [TBXML childElementNamed:@"location" parentElement:rootXML];
    TBXMLElement *WOEID = [TBXML childElementNamed:@"CompanyName" parentElement:results];
    NSString *woeid = [TBXML textForElement:WOEID];

    Cell.text = woeid;
    return Cell;

}


问:
Comparing two files with respective fields and output required in a specific format
I am comparing two files

food1.txt file  and compares food2.txt file, like this

```<code># cat food1.txt
pizza=1ea
chicken=5ea
tooboo=4ea
orange=2ea
</code>```
```<code># cat food2.txt
pizza=2ea
chicken=5ea
grape=3ea
tooboo=4ea
melon=1ea
</code>```

my work...

```<code>FOOD1=`cat ./food1.txt`
FOOD2=`cat ./food2.txt`

echo "$FOOD1" | while read ACCOUNT
do
grep -w $ACCOUNT ./food2.txt  >/dev/null 2>&1
if [ $? -eq 0 ] ; then
echo "-----[  OK  ] : $ACCOUNT"
else
echo "-----[ WARN ] : $ACCOUNT"
fi
done
</code>```

output.. but i don't like it

```<code>-----[ WARN ] : pizza=1ea
-----[  OK  ] : chicken=5ea
-----[  OK  ] : tooboo=4ea
-----[ WARN ] : orange=2ea
</code>```

I want to print the comparison target together

I want output, like this

```<code>food2.txt                   food1.txt
pizza=2ea   : [ NotMatch ] : pizza=1ea
            : [    OK    ] : chicken=5ea
            : [    OK    ] : tooboo=4ea
            : [ NotExist ] : orange=2ea
grape=3ea   : [ NotExist ] :
melon=1ea   : [ NotExist ] :
</code>```

Is it possible? please help me.

答:
With your shown samples, please try following awk program. Written and tested in GNU awk.

```<code>awk '
BEGIN{
  FS="="
  print ARGV[1]"                   "ARGV[2]
}
FNR==NR{
  arr1[$1]=$2
  next
}
($1 in arr1){
  if($2==arr1[$1]){
     print  "           :[    OK     ] : " $0
  }
  else if($2!=arr1[$1]){
     print $1 FS arr1[$1]"  :[ NotMatch  ] : "$0
  }
  arr2[$1]
  next
}
{
  print $0"  :[ NotExist  ] : "
}
END{
  for(i in arr1){
     if(!(i in arr2)){
        print "           :[ NotExist  ] : "i FS arr1[i]
     }
  }
}
' food1.txt food2.txt
</code>```

With your shown samples, following will be output:

```<code>food1.txt                   food2.txt
pizza=1ea  :[ NotMatch  ] : pizza=2ea
           :[    OK     ] : chicken=5ea
grape=3ea  :[ NotExist  ] :
           :[    OK     ] : tooboo=4ea
melon=1ea  :[ NotExist  ] :
           :[ NotExist  ] : orange=2ea
</code>```

Explanation: Adding detailed explanation for above code.

```<code>awk '                                                        ##Starting awk program from here.
BEGIN{                                                       ##Starting BEGIN section from here.
  FS="="                                                     ##Setting field separator as = here.
  print ARGV[1]"                   "ARGV[2]                  ##Printing passed Input_file names here.
}
FNR==NR{                                                     ##Checking condition FNR==NR which will be TRUE when food1.txt is being read.
  arr1[$1]=$2                                                ##Creating array named arr1 with index of 1st field and value is $2.
  next                                                       ##next will skip all further statements from here.
}
($1 in arr1){                                                ##Checking condition if $1 is present in arr1 then do following.
  if($2==arr1[$1]){                                          ##Checking condition if 2nd field is equal to arr1 value.
     print  "           :[    OK     ] : " $0                ##Printing ok message with current line of food2.txt here.
  }
  else if($2!=arr1[$1]){                                     ##Else(in case 2nd field is NOT equal to arr1 value) then do following.
     print $1 FS arr1[$1]"  :[ NotMatch  ] : "$0             ##Printing first field FS value of arr1 followed by NotMatch followed by current line from food2.txt.
  }
  arr2[$1]                                                   ##Making an entry of current $1 for arr2 array here.
  next                                                       ##next will skip all further statements from here.
}
{
  print $0"  :[ NotExist  ] : "                              ##printing current line followed by NotExist statement.
}
END{                                                         ##Starting END block for this program from here.
  for(i in arr1){                                            ##Traversing through arr1 elements here.
     if(!(i in arr2)){                                       ##Checking condition if key i is NOT present in arr2 then do following.
        print "           :[ NotExist  ] : "i FS arr1[i]     ##printing NOtExist statements followed by i FS and arr1 value.
     }
  }
}
' food1.txt food2.txt                                        ##Mentioning Input_file names here.
</code>```

Body:
I am comparing two files

food1.txt file  and compares food2.txt file, like this

# cat food1.txt
pizza=1ea
chicken=5ea
tooboo=4ea
orange=2ea

# cat food2.txt
pizza=2ea
chicken=5ea
grape=3ea
tooboo=4ea
melon=1ea

my work...

FOOD1=`cat ./food1.txt`
FOOD2=`cat ./food2.txt`

echo "$FOOD1" | while read ACCOUNT
do
grep -w $ACCOUNT ./food2.txt  >/dev/null 2>&1
if [ $? -eq 0 ] ; then
echo "-----[  OK  ] : $ACCOUNT"
else
echo "-----[ WARN ] : $ACCOUNT"
fi
done

output.. but i don't like it

-----[ WARN ] : pizza=1ea
-----[  OK  ] : chicken=5ea
-----[  OK  ] : tooboo=4ea
-----[ WARN ] : orange=2ea

I want to print the comparison target together

I want output, like this

food2.txt                   food1.txt
pizza=2ea   : [ NotMatch ] : pizza=1ea
            : [    OK    ] : chicken=5ea
            : [    OK    ] : tooboo=4ea
            : [ NotExist ] : orange=2ea
grape=3ea   : [ NotExist ] :
melon=1ea   : [ NotExist ] :

Is it possible? please help me.

Body:
With your shown samples, please try following awk program. Written and tested in GNU awk.

awk '
BEGIN{
  FS="="
  print ARGV[1]"                   "ARGV[2]
}
FNR==NR{
  arr1[$1]=$2
  next
}
($1 in arr1){
  if($2==arr1[$1]){
     print  "           :[    OK     ] : " $0
  }
  else if($2!=arr1[$1]){
     print $1 FS arr1[$1]"  :[ NotMatch  ] : "$0
  }
  arr2[$1]
  next
}
{
  print $0"  :[ NotExist  ] : "
}
END{
  for(i in arr1){
     if(!(i in arr2)){
        print "           :[ NotExist  ] : "i FS arr1[i]
     }
  }
}
' food1.txt food2.txt

With your shown samples, following will be output:

food1.txt                   food2.txt
pizza=1ea  :[ NotMatch  ] : pizza=2ea
           :[    OK     ] : chicken=5ea
grape=3ea  :[ NotExist  ] :
           :[    OK     ] : tooboo=4ea
melon=1ea  :[ NotExist  ] :
           :[ NotExist  ] : orange=2ea

Explanation: Adding detailed explanation for above code.

awk '                                                        ##Starting awk program from here.
BEGIN{                                                       ##Starting BEGIN section from here.
  FS="="                                                     ##Setting field separator as = here.
  print ARGV[1]"                   "ARGV[2]                  ##Printing passed Input_file names here.
}
FNR==NR{                                                     ##Checking condition FNR==NR which will be TRUE when food1.txt is being read.
  arr1[$1]=$2                                                ##Creating array named arr1 with index of 1st field and value is $2.
  next                                                       ##next will skip all further statements from here.
}
($1 in arr1){                                                ##Checking condition if $1 is present in arr1 then do following.
  if($2==arr1[$1]){                                          ##Checking condition if 2nd field is equal to arr1 value.
     print  "           :[    OK     ] : " $0                ##Printing ok message with current line of food2.txt here.
  }
  else if($2!=arr1[$1]){                                     ##Else(in case 2nd field is NOT equal to arr1 value) then do following.
     print $1 FS arr1[$1]"  :[ NotMatch  ] : "$0             ##Printing first field FS value of arr1 followed by NotMatch followed by current line from food2.txt.
  }
  arr2[$1]                                                   ##Making an entry of current $1 for arr2 array here.
  next                                                       ##next will skip all further statements from here.
}
{
  print $0"  :[ NotExist  ] : "                              ##printing current line followed by NotExist statement.
}
END{                                                         ##Starting END block for this program from here.
  for(i in arr1){                                            ##Traversing through arr1 elements here.
     if(!(i in arr2)){                                       ##Checking condition if key i is NOT present in arr2 then do following.
        print "           :[ NotExist  ] : "i FS arr1[i]     ##printing NOtExist statements followed by i FS and arr1 value.
     }
  }
}
' food1.txt food2.txt                                        ##Mentioning Input_file names here.


问:
How do I save null values that I didn't specify in the database?
welcome
In my program I import data from excel file and the method worked for me, but I have a simple problem, I choose the data I want to recover from the dropdown list and then I import it, but maybe the user doesn't want to select all the data, so I want if he doesn't choose some data, it is saved as blank .
Example:

I want if I leave these values blank and don't select a column for them from the excel sheet, they will be saved as blank.
It's already saved blank but this message pops up for me.

I know the cure for this message, but when I solve it, I can't save empty values, so this message appears

This is my code:

```<code>for (int i = 0; i < DgvSearch.Rows.Count; i++)
                {
                    if (Con.State == ConnectionState.Closed)
                    {
                        Con.Open();
                    }
                    tbl3 = db3.readData("select max (Sup_ID) from Suppliers", "");
                    Cmd3 = new SqlCommand("insert into Suppliers (Sup_ID,Sup_Name,Compny_Name,Sup_Adderss,Sup_Phone,Notes) Values (@Sup_ID,@Sup_Name,@Compny_Name,@Sup_Adderss,@Sup_Phone,@Notes)", Con);

                    if ((Convert.ToInt32(tbl3.Rows[0][0]) + 1).ToString() == null)
                    {
                        Cmd3.Parameters.Add(new SqlParameter("@Sup_ID", SqlDbType.Int)).Value = DBNull.Value;
                    }
                    else
                    {
                        Cmd3.Parameters.Add(new SqlParameter("@Sup_ID", SqlDbType.Int)).Value = (Convert.ToInt32(tbl3.Rows[0][0]) + 1).ToString();

                    }
                    if (cbx2.SelectedIndex <= -1)
                    {
                        Cmd3.Parameters.Add(new SqlParameter("@Sup_Name", SqlDbType.VarChar)).Value = DBNull.Value ;
                    }
                    else
                    {
                         Cmd3.Parameters.Add(new SqlParameter("@Sup_Name", SqlDbType.VarChar)).Value = DgvSearch.Rows[i].Cells[cbx2.SelectedIndex].Value;
                    }
                    if (cbx3.SelectedIndex <= -1)
                    {
                        Cmd3.Parameters.Add(new SqlParameter("@Compny_Name", SqlDbType.VarChar)).Value = DBNull.Value;
                    }
                    else
                    {
                        Cmd3.Parameters.Add(new SqlParameter("@Compny_Name", SqlDbType.VarChar)).Value = DgvSearch.Rows[i].Cells[cbx3.SelectedIndex].Value;

                    }
                    if (cbx4.SelectedIndex <= -1)
                    {
                        Cmd3.Parameters.Add(new SqlParameter("@Sup_Adderss", SqlDbType.VarChar)).Value = DBNull.Value;
                    }
                    else
                    {
                        Cmd3.Parameters.Add(new SqlParameter("@Sup_Adderss", SqlDbType.VarChar)).Value = DgvSearch.Rows[i].Cells[cbx4.SelectedIndex].Value;

                    }
                    if (cbx5.SelectedIndex <= -1)
                    {
                        Cmd3.Parameters.Add(new SqlParameter("@Sup_Phone", SqlDbType.VarChar)).Value = DBNull.Value;
                    }
                    else
                    {
                        Cmd3.Parameters.Add(new SqlParameter("@Sup_Phone", SqlDbType.VarChar)).Value = DgvSearch.Rows[i].Cells[cbx5.SelectedIndex].Value;

                    }
                    if (cbx6.SelectedIndex <= -1)
                    {
                        Cmd3.Parameters.Add(new SqlParameter("@Notes", SqlDbType.VarChar)).Value = DBNull.Value;
                    }
                    else
                    {
                        Cmd3.Parameters.Add(new SqlParameter("@Notes", SqlDbType.VarChar)).Value = DgvSearch.Rows[i].Cells[cbx6.SelectedIndex].Value;
                    }

                    Cmd3.ExecuteNonQuery();
                    Con.Close();
                }
                XtraMessageBox.Show("تم إستيراد بيانات الموردين بنجاح ", "حفظ", MessageBoxButtons.OK, MessageBoxIcon.Information);
                SelectAll_Table3();
            }
</code>```

The previous code is saved with null values, but it shows the first message
When I modify it like this:
Does not save empty values

```<code> if (DgvSearch.Rows[i].Cells[cbx5.SelectedIndex].Value == null)
                    {
                        Cmd3.Parameters.Add(new SqlParameter { ParameterName = "@Notes", Value = DBNull.Value });
                    }
                    else
                    {
                        Cmd3.Parameters.Add(new SqlParameter { ParameterName = "@Notes", Value = DgvSearch.Rows[i].Cells[cbx5.SelectedIndex].Value });
                    }
</code>```

Is there any solution? Thank you very much

答:
Like Richard describes

if "tbl3.Rows[0][0]" is NULL

```<code>Convert.ToInt32(null) // 0
Convert.ToInt32(null) + 1 // 1
(Convert.ToInt32(null) + 1).ToString() // "1"
</code>```

if "tbl3.Rows[0][0]" is "10"

```<code>Convert.ToInt32("10") // 10
Convert.ToInt32("10") + 1 // 11
(Convert.ToInt32("10") + 1).ToString() // "11"
</code>```

if "tbl3.Rows[0][0]" is "abc"

```<code>Convert.ToInt32("abc") // system format exception
</code>```

either do: if (tbl3.Rows[0][0] == null) {assign null} else {assign parsed value} and do exception handling if input is not numeric

or try to parse it and handle non-numeric input as null

if (Int32.TryParse(tbl3.Rows[0][0], out var parsedValue)) {assign parsed value} else {assign null}

Body:
welcome
In my program I import data from excel file and the method worked for me, but I have a simple problem, I choose the data I want to recover from the dropdown list and then I import it, but maybe the user doesn't want to select all the data, so I want if he doesn't choose some data, it is saved as blank .
Example:

I want if I leave these values blank and don't select a column for them from the excel sheet, they will be saved as blank.
It's already saved blank but this message pops up for me.

I know the cure for this message, but when I solve it, I can't save empty values, so this message appears

This is my code:

for (int i = 0; i < DgvSearch.Rows.Count; i++)
                {
                    if (Con.State == ConnectionState.Closed)
                    {
                        Con.Open();
                    }
                    tbl3 = db3.readData("select max (Sup_ID) from Suppliers", "");
                    Cmd3 = new SqlCommand("insert into Suppliers (Sup_ID,Sup_Name,Compny_Name,Sup_Adderss,Sup_Phone,Notes) Values (@Sup_ID,@Sup_Name,@Compny_Name,@Sup_Adderss,@Sup_Phone,@Notes)", Con);

                    if ((Convert.ToInt32(tbl3.Rows[0][0]) + 1).ToString() == null)
                    {
                        Cmd3.Parameters.Add(new SqlParameter("@Sup_ID", SqlDbType.Int)).Value = DBNull.Value;
                    }
                    else
                    {
                        Cmd3.Parameters.Add(new SqlParameter("@Sup_ID", SqlDbType.Int)).Value = (Convert.ToInt32(tbl3.Rows[0][0]) + 1).ToString();

                    }
                    if (cbx2.SelectedIndex <= -1)
                    {
                        Cmd3.Parameters.Add(new SqlParameter("@Sup_Name", SqlDbType.VarChar)).Value = DBNull.Value ;
                    }
                    else
                    {
                         Cmd3.Parameters.Add(new SqlParameter("@Sup_Name", SqlDbType.VarChar)).Value = DgvSearch.Rows[i].Cells[cbx2.SelectedIndex].Value;
                    }
                    if (cbx3.SelectedIndex <= -1)
                    {
                        Cmd3.Parameters.Add(new SqlParameter("@Compny_Name", SqlDbType.VarChar)).Value = DBNull.Value;
                    }
                    else
                    {
                        Cmd3.Parameters.Add(new SqlParameter("@Compny_Name", SqlDbType.VarChar)).Value = DgvSearch.Rows[i].Cells[cbx3.SelectedIndex].Value;

                    }
                    if (cbx4.SelectedIndex <= -1)
                    {
                        Cmd3.Parameters.Add(new SqlParameter("@Sup_Adderss", SqlDbType.VarChar)).Value = DBNull.Value;
                    }
                    else
                    {
                        Cmd3.Parameters.Add(new SqlParameter("@Sup_Adderss", SqlDbType.VarChar)).Value = DgvSearch.Rows[i].Cells[cbx4.SelectedIndex].Value;

                    }
                    if (cbx5.SelectedIndex <= -1)
                    {
                        Cmd3.Parameters.Add(new SqlParameter("@Sup_Phone", SqlDbType.VarChar)).Value = DBNull.Value;
                    }
                    else
                    {
                        Cmd3.Parameters.Add(new SqlParameter("@Sup_Phone", SqlDbType.VarChar)).Value = DgvSearch.Rows[i].Cells[cbx5.SelectedIndex].Value;

                    }
                    if (cbx6.SelectedIndex <= -1)
                    {
                        Cmd3.Parameters.Add(new SqlParameter("@Notes", SqlDbType.VarChar)).Value = DBNull.Value;
                    }
                    else
                    {
                        Cmd3.Parameters.Add(new SqlParameter("@Notes", SqlDbType.VarChar)).Value = DgvSearch.Rows[i].Cells[cbx6.SelectedIndex].Value;
                    }

                    Cmd3.ExecuteNonQuery();
                    Con.Close();
                }
                XtraMessageBox.Show("تم إستيراد بيانات الموردين بنجاح ", "حفظ", MessageBoxButtons.OK, MessageBoxIcon.Information);
                SelectAll_Table3();
            }

The previous code is saved with null values, but it shows the first message
When I modify it like this:
Does not save empty values

 if (DgvSearch.Rows[i].Cells[cbx5.SelectedIndex].Value == null)
                    {
                        Cmd3.Parameters.Add(new SqlParameter { ParameterName = "@Notes", Value = DBNull.Value });
                    }
                    else
                    {
                        Cmd3.Parameters.Add(new SqlParameter { ParameterName = "@Notes", Value = DgvSearch.Rows[i].Cells[cbx5.SelectedIndex].Value });
                    }

Is there any solution? Thank you very much

Body:
Like Richard describes

if "tbl3.Rows[0][0]" is NULL

Convert.ToInt32(null) // 0
Convert.ToInt32(null) + 1 // 1
(Convert.ToInt32(null) + 1).ToString() // "1"

if "tbl3.Rows[0][0]" is "10"

Convert.ToInt32("10") // 10
Convert.ToInt32("10") + 1 // 11
(Convert.ToInt32("10") + 1).ToString() // "11"

if "tbl3.Rows[0][0]" is "abc"

Convert.ToInt32("abc") // system format exception

either do: if (tbl3.Rows[0][0] == null) {assign null} else {assign parsed value} and do exception handling if input is not numeric

or try to parse it and handle non-numeric input as null

if (Int32.TryParse(tbl3.Rows[0][0], out var parsedValue)) {assign parsed value} else {assign null}


问:
Loop through cells and place specific values onto them
So I want to create a table like this

I want those specific numbers on the cells.

I had an idea of how to do it where I check the value of the cell above the one I'm filling in.

Something like this

```<code>if cell_above.value = 2 then
current_cell.value = -2

if cell_above.value = -2 then
current_cell.value = 4
</code>```

and on and on like that.

This just seems like a lot of work and there is probably an easier way to do this. Can somebody help me think of another way to solve this? Thank you

答:
Still not clear what your problem is. Define a const Array of values and write them to the sheet. Following three variations to get you the idea:</p>
```<code>Sub fillMe1()
    Dim MyValues
    MyValues = Array(2, -2, 4, -4, 6, -6, 3, -3, 5, -5, 7, -7)
    With ThisWorkbook.Sheets(1)
        .Range("A1").Resize(UBound(MyValues) + 1, 1).Value = Application.Transpose(MyValues)
    End With
End Sub

Sub fillMe2()
    Dim MyValues
    MyValues = Array(2, -2, 4, -4, 6, -6, 3, -3, 5, -5, 7, -7)
    Dim i As Long

    For i = 0 To UBound(MyValues)
        With ThisWorkbook.Sheets(1)
            .Range("B1").Offset(i, 0).Value = MyValues(i)
        End With
    Next i
End Sub

Sub fillMe3()
    Dim MyValues
    MyValues = Array(2, 4, 6, 3, 5, 7)
    Dim i As Long

    For i = 0 To UBound(MyValues)
        With ThisWorkbook.Sheets(1)
            .Range("C1").Offset(i * 2, 0).Value = MyValues(i)
            .Range("C1").Offset(i * 2 + 1, 0).Value = MyValues(i) * -1
        End With
    Next i
End Sub
</code>```

Body:
So I want to create a table like this

I want those specific numbers on the cells.

I had an idea of how to do it where I check the value of the cell above the one I'm filling in.

Something like this

if cell_above.value = 2 then
current_cell.value = -2

if cell_above.value = -2 then
current_cell.value = 4

and on and on like that.

This just seems like a lot of work and there is probably an easier way to do this. Can somebody help me think of another way to solve this? Thank you

Body:
Still not clear what your problem is. Define a const Array of values and write them to the sheet. Following three variations to get you the idea:

Sub fillMe1()
    Dim MyValues
    MyValues = Array(2, -2, 4, -4, 6, -6, 3, -3, 5, -5, 7, -7)
    With ThisWorkbook.Sheets(1)
        .Range("A1").Resize(UBound(MyValues) + 1, 1).Value = Application.Transpose(MyValues)
    End With
End Sub

Sub fillMe2()
    Dim MyValues
    MyValues = Array(2, -2, 4, -4, 6, -6, 3, -3, 5, -5, 7, -7)
    Dim i As Long

    For i = 0 To UBound(MyValues)
        With ThisWorkbook.Sheets(1)
            .Range("B1").Offset(i, 0).Value = MyValues(i)
        End With
    Next i
End Sub

Sub fillMe3()
    Dim MyValues
    MyValues = Array(2, 4, 6, 3, 5, 7)
    Dim i As Long

    For i = 0 To UBound(MyValues)
        With ThisWorkbook.Sheets(1)
            .Range("C1").Offset(i * 2, 0).Value = MyValues(i)
            .Range("C1").Offset(i * 2 + 1, 0).Value = MyValues(i) * -1
        End With
    Next i
End Sub


问:
Select last N rows from MySQL
I want to select last 50 rows from MySQL database within column named id which is primary key. Goal is that the rows should be sorted by id in ASC order, that’s why this query isn’t working

```<code>SELECT
    *
FROM
    `table`
ORDER BY id DESC
LIMIT 50;
</code>```

Also it’s remarkable that rows could be manipulated (deleted) and that’s why following query isn’t working either

```<code>SELECT
    *
FROM
    `table`
WHERE
    id > ((SELECT
            MAX(id)
        FROM
            chat) - 50)
ORDER BY id ASC;
</code>```

Question: How is it possible to retrieve last N rows from MySQL database that can be manipulated and be in ASC order ?

答:
Use it to retrieve last n rows from mysql

Select * from tbl order by id desc limit 10;

use limit according to N value.

Title: Select last N rows from MySQL

Body:
I want to select last 50 rows from MySQL database within column named id which is primary key. Goal is that the rows should be sorted by id in ASC order, that’s why this query isn’t working

SELECT
    *
FROM
    `table`
ORDER BY id DESC
LIMIT 50;

Also it’s remarkable that rows could be manipulated (deleted) and that’s why following query isn’t working either

SELECT
    *
FROM
    `table`
WHERE
    id > ((SELECT
            MAX(id)
        FROM
            chat) - 50)
ORDER BY id ASC;

Question: How is it possible to retrieve last N rows from MySQL database that can be manipulated and be in ASC order ?


问:
How to find the cumulative sum of numbers in a list?
```<code>time_interval = [4, 6, 12]
</code>```

I want to sum up the numbers like [4, 4+6, 4+6+12] in order to get the list t = [4, 10, 22].

I tried the following:

```<code>t1 = time_interval[0]
t2 = time_interval[1] + t1
t3 = time_interval[2] + t2
print(t1, t2, t3)  # -> 4 10 22
</code>```

答:
I think the below code is the easiest:</p>
```<code>a=[1,1,2,1,2]
b=[a[0]]+[sum(a[0:i]) for i in range(2,len(a)+1)]
</code>```

Body:
time_interval = [4, 6, 12]

I want to sum up the numbers like [4, 4+6, 4+6+12] in order to get the list t = [4, 10, 22].

I tried the following:

t1 = time_interval[0]
t2 = time_interval[1] + t1
t3 = time_interval[2] + t2
print(t1, t2, t3)  # -> 4 10 22

Body:
I think the below code is the easiest:

a=[1,1,2,1,2]
b=[a[0]]+[sum(a[0:i]) for i in range(2,len(a)+1)]


问:
How to specify a different port with the RequireHttps attribute in MVC3
I am just learning ASP.NET MVC, and I have recently found the [RequireHttps] attribute to automatically redirect a GET request to use SSL, like so...

```<code>[RequireHttps] //apply to all actions in controller
public class SomeController
{
    [RequireHttps] //apply to this action only
    public ActionResult SomeAction()
    {
        ...
    }
}
</code>```

When using IIS Express as the development server, this successfully redirects the request from http://localhost:55945/...  to https://localhost/....

However on my development system, my project is using HTTPS on port 44300 (this was configured automatically by Visual Studio 2010), and I have not yet found any way to tell MVC to use that port number in the redirection, so that it goes to the required https://localhost:43300/... instead.

I really expected this to be automatic, given the SSL port number was set automatically by Visual Studio, and as far as I can tell, this must be effecting all developers using the [RequireHttps] attribute in MVC3. In my searching for a solution, I have seen a few patchy "work around" solutions, but nothing that appears to be definitively "the right way" to fix it.

So doing things "the right way", what do I change (either in the source code, or in my project configuration) to tell the [RequireHttps] attribute in MVC3 to use the HTTPS port that my project is configured to be using?

Or alternatively, is there some other completely different and better "right way" to set up SSL support in an MVC3 project, that does not have this problem?

答:
The RequireHttpsAttribute is quite simple and it cannot be parametrized to redirect to a specific port. If you really need this you could create a subclass and override the HandleNonHttpsRequest method to compose the redirect url differently. </p>

```<code>protected override void HandleNonHttpsRequest(AuthorizationContext filterContext) {
    base.HandleNonHttpsRequest(filterContext);

    // redirect to HTTPS version of page
    string url = "https://" + filterContext.HttpContext.Request.Url.Host + ":" + MyConfig.SslPort + filterContext.HttpContext.Request.RawUrl;
    filterContext.Result = new RedirectResult(url);
}
</code>```

<p>However, if your entire site runs with HTTPS you could just configure in VS in the web project properties (Web -> Start Action -> Start URL) to open the correct HTTPS url with your port and not use the redirect feature for local testing. </p>

Body:
I am just learning ASP.NET MVC, and I have recently found the [RequireHttps] attribute to automatically redirect a GET request to use SSL, like so...

[RequireHttps] //apply to all actions in controller
public class SomeController
{
    [RequireHttps] //apply to this action only
    public ActionResult SomeAction()
    {
        ...
    }
}

When using IIS Express as the development server, this successfully redirects the request from http://localhost:55945/...  to https://localhost/....

However on my development system, my project is using HTTPS on port 44300 (this was configured automatically by Visual Studio 2010), and I have not yet found any way to tell MVC to use that port number in the redirection, so that it goes to the required https://localhost:43300/... instead.

I really expected this to be automatic, given the SSL port number was set automatically by Visual Studio, and as far as I can tell, this must be effecting all developers using the [RequireHttps] attribute in MVC3. In my searching for a solution, I have seen a few patchy "work around" solutions, but nothing that appears to be definitively "the right way" to fix it.

So doing things "the right way", what do I change (either in the source code, or in my project configuration) to tell the [RequireHttps] attribute in MVC3 to use the HTTPS port that my project is configured to be using?

Or alternatively, is there some other completely different and better "right way" to set up SSL support in an MVC3 project, that does not have this problem?

Body:
The RequireHttpsAttribute is quite simple and it cannot be parametrized to redirect to a specific port. If you really need this you could create a subclass and override the HandleNonHttpsRequest method to compose the redirect url differently.

protected override void HandleNonHttpsRequest(AuthorizationContext filterContext) {
    base.HandleNonHttpsRequest(filterContext);

    // redirect to HTTPS version of page
    string url = "https://" + filterContext.HttpContext.Request.Url.Host + ":" + MyConfig.SslPort + filterContext.HttpContext.Request.RawUrl;
    filterContext.Result = new RedirectResult(url);
}

However, if your entire site runs with HTTPS you could just configure in VS in the web project properties (Web -> Start Action -> Start URL) to open the correct HTTPS url with your port and not use the redirect feature for local testing.


问:
Unable to programmatically open input selector dialog in Angular
I have an Angular app which has a stylized input box so I keep another actual  element which I call .click() on to open the dialog

This used to work great but for some reason stopped working recently? Anyway I can't make it work even though this all should be quite simple to do...

I've tried every way I can think to access my input and click it all to no avail

```<code>  <input type="file" id="fileInputRef">
  <button (click)="fileInputRef.click()">open</button>
</code>```

this produces the error "Cannot read properties of undefined (reading 'click')"

```<code>  <input type="file" #fileInputRef>
  <button (click)="fileInputRef.click()">open</button>
</code>```

this produces no effect at all, no error in console even

so I tried moving it to my component's code like so

```<code>  <input type="file" #fileInputRef>
  <button (click)="doClick()">open</button>
</code>```

and in my typescript

```<code>  @ViewChild('fileInputRef') fileInputRef: HTMLInputElement;

  public doClick() {
    this.fileInputRef.click();
  }
</code>```

but then this errors with "this.fileInputRef.click is not a function"

If I print out this.fileInputRef it looks like "ElementRef {nativeElement: input}"

So lastly I tried

```<code>  public doClick() {
    this.fileInputRef.nativeElement.click();
  }
</code>```

which produces no effect

I'm not sure why this feature used to be working and stopped but I'm sure I'm missing something basic

How can I programmatically fire of a click for a file input element in my html

答:
You can use ElementRef to click file type from html. See below code implemented properly and it works fine.

```<code><input type="file" (change)="handleFileInput($event.target.files)" #fileInput style="display:none" multiple>
<button type="button"(click)="fileInput.click()" > Open </button>

@ViewChild('fileInput') myFileInputVariable: ElementRef;
</code>```

And when you want to reset input field.

```<code>this.myFileInputVariable.nativeElement.value = "";
</code>```

Body:
I have an Angular app which has a stylized input box so I keep another actual  element which I call .click() on to open the dialog

This used to work great but for some reason stopped working recently? Anyway I can't make it work even though this all should be quite simple to do...

I've tried every way I can think to access my input and click it all to no avail

  <input type="file" id="fileInputRef">
  <button (click)="fileInputRef.click()">open</button>

this produces the error "Cannot read properties of undefined (reading 'click')"

  <input type="file" #fileInputRef>
  <button (click)="fileInputRef.click()">open</button>

this produces no effect at all, no error in console even

so I tried moving it to my component's code like so

  <input type="file" #fileInputRef>
  <button (click)="doClick()">open</button>

and in my typescript

  @ViewChild('fileInputRef') fileInputRef: HTMLInputElement;

  public doClick() {
    this.fileInputRef.click();
  }

but then this errors with "this.fileInputRef.click is not a function"

If I print out this.fileInputRef it looks like "ElementRef {nativeElement: input}"

So lastly I tried

  public doClick() {
    this.fileInputRef.nativeElement.click();
  }

which produces no effect

I'm not sure why this feature used to be working and stopped but I'm sure I'm missing something basic

How can I programmatically fire of a click for a file input element in my html

Body:
You can use ElementRef to click file type from html. See below code implemented properly and it works fine.

<input type="file" (change)="handleFileInput($event.target.files)" #fileInput style="display:none" multiple>
<button type="button"(click)="fileInput.click()" > Open </button>

@ViewChild('fileInput') myFileInputVariable: ElementRef;

And when you want to reset input field.

this.myFileInputVariable.nativeElement.value = "";


问:
MSIX packaged WPF app that prevent multiple instances of windows?
I developed a WPF application with .NET 5.0, and wrap it with a MSIX Windows Application Packaging Project.

The question is that how can I prevent opening multiple instances of the application?

My requirement is: each time when the users go to Windows Start menu and open the application, the existing application window should become active instead of opening a new application window.

答:
You could define a custom Main method that uses a Mutex to ensure that only one instance of your app is created:

```<code>class Program
{
    const string AppUniqueGuid = "FB3808FB-57B7-4E38-B437-0F4E6EC3E4E2";

    [STAThread]
    static void Main(string[] args)
    {
        using (Mutex mutex = new Mutex(false, AppUniqueGuid))
        {
            if (mutex.WaitOne(0, false))
            {
                App application = new App();
                application.InitializeComponent();
                application.Run();
            }
        }
    }
}
</code>```

Select Program as the "Startup object" under Project->Properties of the WPF application project in Visual Studio.

Body:
You could define a custom Main method that uses a Mutex to ensure that only one instance of your app is created:

class Program
{
    const string AppUniqueGuid = "FB3808FB-57B7-4E38-B437-0F4E6EC3E4E2";

    [STAThread]
    static void Main(string[] args)
    {
        using (Mutex mutex = new Mutex(false, AppUniqueGuid))
        {
            if (mutex.WaitOne(0, false))
            {
                App application = new App();
                application.InitializeComponent();
                application.Run();
            }
        }
    }
}

Select Program as the "Startup object" under Project->Properties of the WPF application project in Visual Studio.


问:
Pass Single Instance of Model to Multiple View Models in same Module for different views
I am working on a project using PRISM where I have left navigation implemented as Tree View and any click event happens raise event using event aggergation to Enrolment Module which has multiple view model for multiple views (like Wizard Applicaiton where you can go through many views to collect data). I want to have a common or shared or singleton model which can be passed across this view models and save at the end.... users can click on any link any navigation at any time and it should save data in to this singleton model expsosed through different view model. Do you have any samples which are doing something like this... or can you type up a quick one on how to do it? OR it is not possible to do it at all. I am following all patterns from Brian Lagunas's Pluralsight Video for PRISM so try to use that way....</p>

答:
I would have a MasterViewModel which controls the "wizard" pages and current state

It would contain the following properties:

List<ViewModelBase> Pages

int CurrentPageIndex

ViewModelBase CurrentPage, which returns Pages[CurrentPageIndex]

MyClass DataObject

The MasterView that goes with the MasterViewModel would be nothing more than a ContentControl with it's Content bound to CurrentPage. I would probably also define DataTemplates in the MasterView which tells WPF which View to draw with which Page

Your MasterViewModel would be in charge of handling the pages, and passing each page a reference to the data it needs. For example in the constructor it might say,

```<code>public MasterViewModel(MyClass dataObject)
{
    DataObject = dataObject;

    Pages.Add(new InfoPage(DataObject));
    Pages.Add(new AddressPage(DataObject.Addresses));
    Pages.Add(new PhonePage(DataObject.Phones));
    Pages.Add(new SaveMyClassPage(DataObject));

    CurrentPageIndex = 0;
}
</code>```

I have an example here if you're interested

Body:
I would have a MasterViewModel which controls the "wizard" pages and current state

It would contain the following properties:

List<ViewModelBase> Pages

int CurrentPageIndex

ViewModelBase CurrentPage, which returns Pages[CurrentPageIndex]

MyClass DataObject

The MasterView that goes with the MasterViewModel would be nothing more than a ContentControl with it's Content bound to CurrentPage. I would probably also define DataTemplates in the MasterView which tells WPF which View to draw with which Page

Your MasterViewModel would be in charge of handling the pages, and passing each page a reference to the data it needs. For example in the constructor it might say,

public MasterViewModel(MyClass dataObject)
{
    DataObject = dataObject;

    Pages.Add(new InfoPage(DataObject));
    Pages.Add(new AddressPage(DataObject.Addresses));
    Pages.Add(new PhonePage(DataObject.Phones));
    Pages.Add(new SaveMyClassPage(DataObject));

    CurrentPageIndex = 0;
}

I have an example here if you're interested