问:
How to run function after an api call has been complete in swift
I want my function openDoor to return true, if the API call has given us doorStatus "OPENED" However, I run into a problem, where this function returns before the API call has been made, making it return false every time, because it has been initialised so. My question is how do I make api request first, so that I can assign doorStatusL true or false based on that API call to return it at the end?

```<code>                func openDoor(requesto: URLRequest) ->Bool {
                 var doorstatusL = false;

                func sendRequest() -> Bool {
                NSURLConnection.sendAsynchronousRequest(requesto, queue: OperationQueue.main) {(response, data, error) in

                    guard let data = data else {
                        return
                    }
                    print(String(data: data, encoding: .utf8)!)
                    do {

                        let json = try JSONDecoder().decode([WelcomeElement].self, from: data )
                        //try JSONSerialization.jsonObject(with: data!, options: [])
                        print(json[0].doorstatus)
                        if(json[0].doorstatus == "OPENED"){
                            doorstatusL = true;
                            print(doorstatusL)
                            print("assigned TRUE")
                        }
                    } catch {
                        print("Status Error during JSON serialization: \(error.localizedDescription)")
                    }
                    }
                    return true
                }
                if(sendRequest()==true){
                    print(doorstatusL)
                    print("=======+++++++")
                    return doorstatusL
                } else {
                    print("returned false at the end")
                    return false
                }
               return true;
            }
</code>```

Output from a terminal is

```<code>false
=======+++++++
[{"message":"OPEN, ENTER ","doorstatus":"OPENED"}]
OPENED
true
assigned TRUE
</code>```

Thank you

SOLVED

```<code>                        func sendRequest(requesto: URLRequest, success:Bool, completionHandler: @escaping (Bool)->Void) {
                        var doorStatusL = false

                        NSURLConnection.sendAsynchronousRequest(requesto, queue: OperationQueue.main) { (response, data, error) in
                            guard let data = data else { return }

                            do {
                                let json = try JSONDecoder().decode([WelcomeElement].self, from: data )

                                if(json[0].doorstatus == "OPENED") {
                                    doorStatusL = true
                                    completionHandler(doorStatusL)
                                }
                            } catch {
                                print("Status Error during JSON serialization: \(error.localizedDescription)")
                            }
                        }
                    }

                    let completionhandler:(Bool)->Void = { (success) in
                        if success {
                                sendNotifications()
                        }
                    }

                    sendRequest(requesto: request2, success: true, completionHandler: completionhandler)
</code>```

答:
```<code>func openDoor(requesto: URLRequest,completionHandler:@escaping (Bool) -> ()) {
    func sendRequest() -> Bool {
            NSURLConnection.sendAsynchronousRequest(requesto, queue: OperationQueue.main) {(response, data, error) in

                guard let data = data else {
                    return
                }
                print(String(data: data, encoding: .utf8)!)
                do {

                    let json = try JSONDecoder().decode([WelcomeElement].self, from: data )
                    //try JSONSerialization.jsonObject(with: data!, options: [])
                    print(json[0].doorstatus)
                    if(json[0].doorstatus == "OPENED"){
                        doorstatusL = true;
                        print(doorstatusL)
                        print("assigned TRUE")
                    }
                } catch {
                    print("Status Error during JSON serialization: \(error.localizedDescription)")
                }
                }
                completionHandler(true)
            }
            if(sendRequest()==true){
                print(doorstatusL)
                print("=======+++++++")
                completionHandler(doorstatusL)
            } else {
                print("returned false at the end")
                completionHandler(false)
            }
    })
}
</code>```

Usage:

```<code>openDoor() { requesto: urlHere,success in
   print(success)
}
</code>```

Escaping Closure : An escaping closure is a closure that’s called after the function it was passed to returns. In other words, it outlives the function it was passed to.

Non-escaping closure : A closure that’s called within the function it was passed into, i.e. before it returns.

You can read more about it in this question:
Swift @escaping and Completion Handler

Body:
I want my function openDoor to return true, if the API call has given us doorStatus "OPENED" However, I run into a problem, where this function returns before the API call has been made, making it return false every time, because it has been initialised so. My question is how do I make api request first, so that I can assign doorStatusL true or false based on that API call to return it at the end?

                func openDoor(requesto: URLRequest) ->Bool {
                 var doorstatusL = false;

                func sendRequest() -> Bool {
                NSURLConnection.sendAsynchronousRequest(requesto, queue: OperationQueue.main) {(response, data, error) in

                    guard let data = data else {
                        return
                    }
                    print(String(data: data, encoding: .utf8)!)
                    do {

                        let json = try JSONDecoder().decode([WelcomeElement].self, from: data )
                        //try JSONSerialization.jsonObject(with: data!, options: [])
                        print(json[0].doorstatus)
                        if(json[0].doorstatus == "OPENED"){
                            doorstatusL = true;
                            print(doorstatusL)
                            print("assigned TRUE")
                        }
                    } catch {
                        print("Status Error during JSON serialization: \(error.localizedDescription)")
                    }
                    }
                    return true
                }
                if(sendRequest()==true){
                    print(doorstatusL)
                    print("=======+++++++")
                    return doorstatusL
                } else {
                    print("returned false at the end")
                    return false
                }
               return true;
            }

Output from a terminal is

false
=======+++++++
[{"message":"OPEN, ENTER ","doorstatus":"OPENED"}]
OPENED
true
assigned TRUE

Thank you

SOLVED

                        func sendRequest(requesto: URLRequest, success:Bool, completionHandler: @escaping (Bool)->Void) {
                        var doorStatusL = false

                        NSURLConnection.sendAsynchronousRequest(requesto, queue: OperationQueue.main) { (response, data, error) in
                            guard let data = data else { return }

                            do {
                                let json = try JSONDecoder().decode([WelcomeElement].self, from: data )

                                if(json[0].doorstatus == "OPENED") {
                                    doorStatusL = true
                                    completionHandler(doorStatusL)
                                }
                            } catch {
                                print("Status Error during JSON serialization: \(error.localizedDescription)")
                            }
                        }
                    }

                    let completionhandler:(Bool)->Void = { (success) in
                        if success {
                                sendNotifications()
                        }
                    }

                    sendRequest(requesto: request2, success: true, completionHandler: completionhandler)

Body:
func openDoor(requesto: URLRequest,completionHandler:@escaping (Bool) -> ()) {
    func sendRequest() -> Bool {
            NSURLConnection.sendAsynchronousRequest(requesto, queue: OperationQueue.main) {(response, data, error) in

                guard let data = data else {
                    return
                }
                print(String(data: data, encoding: .utf8)!)
                do {

                    let json = try JSONDecoder().decode([WelcomeElement].self, from: data )
                    //try JSONSerialization.jsonObject(with: data!, options: [])
                    print(json[0].doorstatus)
                    if(json[0].doorstatus == "OPENED"){
                        doorstatusL = true;
                        print(doorstatusL)
                        print("assigned TRUE")
                    }
                } catch {
                    print("Status Error during JSON serialization: \(error.localizedDescription)")
                }
                }
                completionHandler(true)
            }
            if(sendRequest()==true){
                print(doorstatusL)
                print("=======+++++++")
                completionHandler(doorstatusL)
            } else {
                print("returned false at the end")
                completionHandler(false)
            }
    })
}

Usage:

openDoor() { requesto: urlHere,success in
   print(success)
}

Escaping Closure : An escaping closure is a closure that’s called after the function it was passed to returns. In other words, it outlives the function it was passed to.

Non-escaping closure : A closure that’s called within the function it was passed into, i.e. before it returns.

You can read more about it in this question:
Swift @escaping and Completion Handler


来源: stackexchange

问:
How to calculate a Forward Pass with matrix operations in PyTorch?
I have got an input x, layer 1 weight matrix, and layer 2 weight matrix.

Now I want to calculate the output of this pre-trained neural network via hand:

x * weights1 * weights2

While doing this I receive a RuntimeError: The size of tensor a (6) must match the size of tensor b (4) at non-singleton dimension 1

```<code>class Net(nn.Module):

def __init__(self):
    super().__init__()
    self.fc1 = nn.Linear(4,6)
    self.fc2 = nn.Linear(6,2)
    self.fc3 = nn.Linear(2,1)

def forward(self, x):
    x = F.relu(self.fc1(x))
    x = F.relu(self.fc2(x))
    x = F.relu(self.fc3(x))
    return x

net = Net()
X = torch.randn(1000,4)
net.fc2.weight*(net.fc1.weight * X[0])
</code>```

答:
You are confusing element-wise multiplication (* operator) with matrix multiplication (@ operator).

Try:

net.fc2.weight @ (net.fc1.weight @ X[0])
```

ContentLicense: CC BY-SA 4.0

Body:
I have got an input x, layer 1 weight matrix, and layer 2 weight matrix.

Now I want to calculate the output of this pre-trained neural network via hand:

x * weights1 * weights2

While doing this I receive a RuntimeError: The size of tensor a (6) must match the size of tensor b (4) at non-singleton dimension 1

class Net(nn.Module):

def __init__(self):
    super().__init__()
    self.fc1 = nn.Linear(4,6)
    self.fc2 = nn.Linear(6,2)
    self.fc3 = nn.Linear(2,1)

def forward(self, x):
    x = F.relu(self.fc1(x))
    x = F.relu(self.fc2(x))
    x = F.relu(self.fc3(x))
    return x

net = Net()
X = torch.randn(1000,4)
net.fc2.weight*(net.fc1.weight * X[0])


问:
SQL Server - unused LEFT JOIN impacts execution plan
I have a query like this

```<code>SELECT TableA.Id FROM TableA
LEFT JOIN TableB ON TableA.Id = TableB.TableAId
</code>```

In this case columns from table B are actually not used and could not affect the result because it's not an INNER JOIN. But the execution plan clearly shows that it's being used and it affects the performance. Shouldn't SQL Server optimize it to eliminate unused operations? Is there a way to set some execution hints to do that or rewrite the query to only use this join when it's actually present in SELECT or WHERE clause?

Unfortunately, I can't just remove the unused join from query. In real life it's a more complex view that joins many tables and it's always used with different SELECT list or WHERE condition

答:
A LEFT JOIN can alter the result even if their columns are not in the result set.

See how these two querys return different results :

```<code>create table TableA (TableAId int)
create table TableB (TableBId int, TableAId int)

insert into TableA (TableAId) values (100), (200), (300)
insert into TableB (TableBId, TableAId) values (1, 100), (1, 200), (2, 100), (3, 300)

select TableA.TableAId
from TableA

select TableA.TableAId
from TableA
     left join TableB on TableB.TableAId = TableA.TableAId
</code>```

That's because if multiple rows match the join condition then all the rows will be joined.

Body:
I have a query like this

SELECT TableA.Id FROM TableA
LEFT JOIN TableB ON TableA.Id = TableB.TableAId

In this case columns from table B are actually not used and could not affect the result because it's not an INNER JOIN. But the execution plan clearly shows that it's being used and it affects the performance. Shouldn't SQL Server optimize it to eliminate unused operations? Is there a way to set some execution hints to do that or rewrite the query to only use this join when it's actually present in SELECT or WHERE clause?

Unfortunately, I can't just remove the unused join from query. In real life it's a more complex view that joins many tables and it's always used with different SELECT list or WHERE condition

Body:
A LEFT JOIN can alter the result even if their columns are not in the result set.

See how these two querys return different results :

create table TableA (TableAId int)
create table TableB (TableBId int, TableAId int)

insert into TableA (TableAId) values (100), (200), (300)
insert into TableB (TableBId, TableAId) values (1, 100), (1, 200), (2, 100), (3, 300)

select TableA.TableAId
from TableA

select TableA.TableAId
from TableA
     left join TableB on TableB.TableAId = TableA.TableAId

That's because if multiple rows match the join condition then all the rows will be joined.


问:
Method inside "When" actually being called
When I am testing a class A (TestNG) which uses some methods from some other class Helper Class
I am mocking the helper class(Mockito) for testing class A.
but when(helper.methodUsedByClassA(value)).thenReturn(new HashMap>())
this line of code is actually calling helper.methodUsedByClassA and a null pointer exception is thrown (because of data I am using for testing is not valid)

why is this happening? Why would the method name inside mockito "when" actually be called ?

```<code>class ATest{

@Mock
private Helper helper;

private A target;

@BeforeTest
public void setUp() {
        MockitoAnnotations.initMocks(this);
        this.target = new UpdateDigicatKdpAsinUtil(helper);
}

@Test(dataProvider = "data")
public void testMethod(List<String> value) {

    when(helper.methodUsedByClassA(value)).thenReturn(new HashMap<String, List<String>>({{put("test", new ArrayList<>())}}));

}

@DataProvider
public Object[][] data(){
List<String> list = new ArrayList<>();
   return new Object[][]
   {

     {list}

   }

}

</code>```

```<code>class Helper{

     public Map<String, List<String>> methoUsedByClassA(int value) {
          //This method is being executed because it is mentioned inside "when"
}

}

</code>```

答:
I guess you get an NPE because helper is NULL.

The problem is that the @Mock annotation isn't processed and because of that, the variable helper isn't initialized.

You have to annotate the test class with @RunWith(MockitoJUnitRunner.class). MockitoJUnitRunner will process the @Mock annotation and create the mock.

Body:
When I am testing a class A (TestNG) which uses some methods from some other class Helper Class
I am mocking the helper class(Mockito) for testing class A.
but when(helper.methodUsedByClassA(value)).thenReturn(new HashMap>())
this line of code is actually calling helper.methodUsedByClassA and a null pointer exception is thrown (because of data I am using for testing is not valid)

why is this happening? Why would the method name inside mockito "when" actually be called ?

class ATest{

@Mock
private Helper helper;

private A target;

@BeforeTest
public void setUp() {
        MockitoAnnotations.initMocks(this);
        this.target = new UpdateDigicatKdpAsinUtil(helper);
}

@Test(dataProvider = "data")
public void testMethod(List<String> value) {

    when(helper.methodUsedByClassA(value)).thenReturn(new HashMap<String, List<String>>({{put("test", new ArrayList<>())}}));

}

@DataProvider
public Object[][] data(){
List<String> list = new ArrayList<>();
   return new Object[][]
   {

     {list}

   }

}

class Helper{

     public Map<String, List<String>> methoUsedByClassA(int value) {
          //This method is being executed because it is mentioned inside "when"
}

}


问:
Play Adobe media server in Asp.net core 2.2 web Application
I have web application with asp.net core 2.2. this application is a client for a Api server

i'm using adobe media server 5 for video streaming and my stream urls is like

this:http://localhost/hls-vod/sample1_150kbps.f4v.m3u8

I play that link with hls.js

but i get this Error

Access to XMLHttpRequest at
  'http://localhost/hls-vod/sample1_150kbps.f4vFrag1Num0.ts' from origin
  'null' has been blocked by CORS policy: No
  'Access-Control-Allow-Origin' header is present on the requested
  resource.

follow solutions are not working for me :

https://community.adobe.com/t5/media-server/how-to-allow-cors-request-from-javascript/td-p/8691655

How to allow CORS request from Javascript in Adobe Media Server

is there better solution for playing media server stream in asp.net core web applications?

答:
the problem was about my urls i will change slash or backslash

this work for some videos but other still not working and i found that

other video must be converted

ffmpeg-20190709-5a481b1-win64-static


问:
how to check 2D array for duplicates
I am trying to remove duplicates from my 2D array but no success.

Here is what I am doing any idea where am making mistake?

function Remove_duplicates_from_2d_array(data_array) {
  if (data_array.length > 0) {
    let unique_index_counter = 0;
    // loop on target array
    for (var a = 0; a < data_array.length; a++) {
      var unique_array = data_array[unique_index_counter];

      if (a === unique_index_counter) {
        continue;
      }
      console.log('comparing index: ' + a + ' ( ' + data_array[a] + ' ) -- index: ' + a + ' ( ' + data_array[a] + ' )');
      if (data_array[a].sort().join(',') === unique_array.sort().join(',')) {
        console.log('match it index ' + a + ' - ' + unique_index_counter);
        // same arrays
        data_array.splice(a, 1);
        a = 0; // reset for loop as splice will rebuilt array
      }
      // a will be equal to data_array length incase there is no match found
      if (a === data_array.length) {
        unique_index_counter++;
      }
   if(unique_index_counter != data_array.length) {
  a = 0; // reset for loop because we have not checked all items
   }
    }

    return data_array;
  } else {
    return [];
  }
}

var a1 = [1, 2, 3];
b1 = [4, 4, 5];
c1 = [3, 4, 5];
d1 = [4, 4, 5];
var data_array = [];
data_array.push(a1);
data_array.push(b1);
data_array.push(c1);
data_array.push(d1);
console.log('original array.');
console.log(data_array);

var r = Remove_duplicates_from_2d_array(data_array);
console.log('unique array.');
console.log(r);  // [[1,2,3],[4,4,5],[3,4,5]]```

答:
You may Array.prototype.reduce() source array doing Array.prototype.find()'ing duplicates along the way:

const src = [[1,2,3],[4,4,5],[3,4,5],[4,4,5]],
      arrsAreEqual = (a1,a2) => a1.sort().join('|') === a2.sort().join('|'),
      dedupe = src.reduce((r,a) =>
        (!r.find(ra => arrsAreEqual(a,ra)) && r.push(a), r), [])

console.log(JSON.stringify(dedupe))```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper{min-height:100%;}</code>```

Title: how to check 2D array for duplicates

Body:
You may Array.prototype.reduce() source array doing Array.prototype.find()'ing duplicates along the way:

const src = [[1,2,3],[4,4,5],[3,4,5],[4,4,5]],
      arrsAreEqual = (a1,a2) => a1.sort().join('|') === a2.sort().join('|'),
      dedupe = src.reduce((r,a) =>
        (!r.find(ra => arrsAreEqual(a,ra)) && r.push(a), r), [])

console.log(JSON.stringify(dedupe))

.as-console-wrapper{min-height:100%;}


问:
Resolution problem in C# .NET Winform application
I have developed my winform application without caring about the resolution. Now am stuck up on PCs with a lower resolution. What to do now? Is there any way of conversion? I mean can the application get the resolution of the PC on which it is running, and set itself accordingly? Is there not any code or variable of Resolution in Windows which can be used ?</p>

答:
You could use

```<code> Screen.PrimaryScreen.WorkingArea.Size;
</code>```

and play with control anchoring. This is how I did it.
Problem also discussed: fit windows form to any screen resolution

ContentLicense: CC BY-SA 3.0

Body:
You could use

 Screen.PrimaryScreen.WorkingArea.Size;

and play with control anchoring. This is how I did it.
Problem also discussed: fit windows form to any screen resolution


问:
TypeError: readImpl(...) is not a function
I'm getting

```<code>TypeError: readImpl(...) is not a function
</code>```

from compiled code, and I'm not using FFI nor unsafeCoerce, which usually lead to these issues.

答: Solution: rm -rf output, sometimes the incremental compilation is faulty.

Body:
I'm getting

TypeError: readImpl(...) is not a function

from compiled code, and I'm not using FFI nor unsafeCoerce, which usually lead to these issues.


问:
How to construct a database driven Jquery dropdown menu in asp.net
I am trying to build a fancy jquery dropdown menu ,while making the menu items dynamic by bringing the values of menu items from database. I am using asp.net and sql server 2005 as my database,Is their any simple article to work this? </p>

答:
```<code>$.ajax({
     url: yoururl,
     data: { yourfunctiondatavariable},
     cache: false,
     type: "POST",
     success: function (data) {
     var markup = "<option value='0'>----Select----</option>";
     for (var x = 0; x < data.length; x++)
     {
     debugger
     markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
      }
      $("#dropdownname").html(markup).show();
    },
   error: function (reponse) {
   alert("error : " + reponse);
   }
});
</code>```


问:
I authenticated a user from IdS4, how do I use this info in my MVC client?
I've got a user authenticated via IdS4, along with a few claims and a role, now I'm lost about what to with it. The general flow for the user is: Go to my site, log in redirects to IdS4 server. They enter their username/password, and redirect back to my site, along with cookies set.

I've not seen much beyond authentication in the tutorials I've found.
Should/How do I persist the user? Should I set up Identity on my MVC site? I'm just looking for a general idea, I think I can figure out the specifics, at this point my general Googling hasn't turned up much.

Thank you.

答:
You can add ASP.Net Identity to manage users in your client MVC application , or directly use EF Core to store users in database without ASP.Net Identity .

But the problem is why you want to perisit or manage users in your client application ? You are using Identity Server to do authentication and IDS will connect the database/configration file  to validate user and fill user claims , if you want to manage users/roles , you can add apis(CURD operations to user database) as protected resource , and your client app acquire access token to access that apis to perform user management . So that user management operations are share to clients which have permission to get api's access token . But if you want to manage specific users which only available to one client , you can mix asp.net identity and IDS4 authentication in client app .


问:
Recursion function to return the path of the differences during a deep comparison
I have the below recursion function:

```<code>const getDiff = (object, base) => {
  const changes = (object, base, path = "") => {
    return _.transform(object, function(result, value, key) {
      if (!_.isEqual(value, base[key])) {
        if (_.isObject(value) && _.isObject(base[key])) {
          if (!path) {
            path += `${key}`;
          } else {
            path += `.${key}`;
          }

          result[key] = changes(value, base[key], path);
        } else {
          if (!path) {
            path = key;
          }
          result[key] = { value, path };
        }
      }
    });
  };
  return changes(object, base);
};
</code>```

I'm trying to make sure that it returns not just the properties that are different, but also the direct path of that property.

For instance, if I have,

```<code>const objA = {
  filter: {
    tag: 1
  },
  name: 'a'
}

const objB = { name: 'b' };
</code>```

Then getting the diff should yield:

```<code>{
  filter: {
    value: { tag: 1 },
    path: 'filter.tag'
  },
  name: {
    value: 'a',
    path: 'name'
  }
}
</code>```

But right now it returns path: 'filter' always. What am I doing wrong?

Below link for quick access to lodash for the console:

```<code>fetch('https://cdn.jsdelivr.net/npm/lodash@4.17.4/lodash.min.js')
    .then(response => response.text())
    .then(text => eval(text))
</code>```

答:
Your current path is scoped outside of _.transform thus it will apply to all branches.

Scope it within the result of _.transform and everything is ok.

E.g.:

```<code>const getDiff = (object, base) => {
                                //changed
  const changes = (object, base, _path = "") => {
    return _.transform(object, function(result, value, key) {
      // changed
      let path = _path;
      if (!_.isEqual(value, base[key])) {
        if (_.isObject(value) && _.isObject(base[key])) {
          if (!path) {
            path += `${key}`;
          } else {
            path += `.${key}`;
          }

          result[key] = changes(value, base[key], path);
        } else {
          if (!path) {
            path = key;
          } else { // changed
            path += `.${key}`;
          }
          result[key] = { value, path };
        }
      }
    });
  };
  return changes(object, base);
};
</code>```

Body:
I have the below recursion function:

const getDiff = (object, base) => {
  const changes = (object, base, path = "") => {
    return _.transform(object, function(result, value, key) {
      if (!_.isEqual(value, base[key])) {
        if (_.isObject(value) && _.isObject(base[key])) {
          if (!path) {
            path += `${key}`;
          } else {
            path += `.${key}`;
          }

          result[key] = changes(value, base[key], path);
        } else {
          if (!path) {
            path = key;
          }
          result[key] = { value, path };
        }
      }
    });
  };
  return changes(object, base);
};

I'm trying to make sure that it returns not just the properties that are different, but also the direct path of that property.

For instance, if I have,

const objA = {
  filter: {
    tag: 1
  },
  name: 'a'
}

const objB = { name: 'b' };

Then getting the diff should yield:

{
  filter: {
    value: { tag: 1 },
    path: 'filter.tag'
  },
  name: {
    value: 'a',
    path: 'name'
  }
}

But right now it returns path: 'filter' always. What am I doing wrong?

Below link for quick access to lodash for the console:

fetch('https://cdn.jsdelivr.net/npm/lodash@4.17.4/lodash.min.js')
    .then(response => response.text())
    .then(text => eval(text))

Body:
Your current path is scoped outside of _.transform thus it will apply to all branches.

Scope it within the result of _.transform and everything is ok.

E.g.:

const getDiff = (object, base) => {
                                //changed
  const changes = (object, base, _path = "") => {
    return _.transform(object, function(result, value, key) {
      // changed
      let path = _path;
      if (!_.isEqual(value, base[key])) {
        if (_.isObject(value) && _.isObject(base[key])) {
          if (!path) {
            path += `${key}`;
          } else {
            path += `.${key}`;
          }

          result[key] = changes(value, base[key], path);
        } else {
          if (!path) {
            path = key;
          } else { // changed
            path += `.${key}`;
          }
          result[key] = { value, path };
        }
      }
    });
  };
  return changes(object, base);
};


问:
'ScriptServiceAttribute' is ambiguous in the namespace 'System.Web.Script.Services'
I'm currently working on an existing ASP.NET project. At the moment I have to integrate
a new componant so for that purpose I had to change the framework target from 2.0 to 3.5. After regenerating the solution, I'm now dealing with a strange issue.

Here's the code :

```<code><WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
<System.Web.Script.Services.ScriptService()> _
</code>```

And the last line returns that error :

```<code>'ScriptServiceAttribute' is ambiguous in the namespace 'System.Web.Script.Services'
</code>```

I have definitely no clue what's going on in my code ?! Is it an internal error of the ScriptService constructor ?

Thanks in advance for your help !

答: I checked my reference and it seems everything is alright ! I also checked the web.config and I cannot figure out any issues. Concerning a @Register statement, I don't really where could I find any as this is not my own project and I don't know where this service could be used.</p>

Body:
I'm currently working on an existing ASP.NET project. At the moment I have to integrate
a new componant so for that purpose I had to change the framework target from 2.0 to 3.5. After regenerating the solution, I'm now dealing with a strange issue.

Here's the code :

<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
<System.Web.Script.Services.ScriptService()> _

And the last line returns that error :

'ScriptServiceAttribute' is ambiguous in the namespace 'System.Web.Script.Services'

I have definitely no clue what's going on in my code ?! Is it an internal error of the ScriptService constructor ?

Thanks in advance for your help !


问:
Select * from table with NodeJS // ERROR: { error: relation "mytable" does not exist
I get the following error during my SELECT query from PostgreSQL DB

```<code>ERROR: { error: relation "free_subnets" does not exist
    at Connection.parseE (/home/ec2-user/environment/node_modules/pg/lib/connection.js:604:11)
    at Connection.parseMessage (/home/ec2-user/environment/node_modules/pg/lib/connection.js:401:19)
    at Socket.<anonymous> (/home/ec2-user/environment/node_modules/pg/lib/connection.js:121:22)
    at Socket.emit (events.js:198:13)
    at addChunk (_stream_readable.js:288:12)
    at readableAddChunk (_stream_readable.js:269:11)
    at Socket.Readable.push (_stream_readable.js:224:10)
    at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)
  name: 'error',
  length: 103,
  severity: 'ERROR',
  code: '42P01',
  detail: undefined,
  hint: undefined,
  position: '15',
  internalPosition: undefined,
  internalQuery: undefined,
  where: undefined,
  schema: undefined,
  table: undefined,
  column: undefined,
  dataType: undefined,
  constraint: undefined,
  file: 'parse_relation.c',
  line: '874',
  routine: 'parserOpenTable' }
</code>```

If I use psql command and do a select there, it works.

\dt provides me the relation:

```<code>
   Schema    |     Name     | Type  |  Owner
-------------+--------------+-------+----------
 subnet_calc | free_subnets | table | postgres
</code>```

Search_path has been set to: subnet_calc, public

I've created the table with user postgres, so I am the owner of the schema subnet_calc and the table free_subnets.

My dummy nodejs code is the following:

const pg = require('pg');

const cs = 'postgres://postgres:password@anydb.rds.amazonaws.com:5432/subnet_calculator';

const client = new pg.Client(cs);
client.connect();

client.query('SELECT * FROM subnet_calc.free_subnets', function(result) {
  console.log(result);
});
```

What could be the issue?

Thanks for your help in advance!

答:
I could resolve the issue. It was my failure, the tables were created in DB postgres not in subnet_calculator.

I will close this question.

Body:
I get the following error during my SELECT query from PostgreSQL DB

ERROR: { error: relation "free_subnets" does not exist
    at Connection.parseE (/home/ec2-user/environment/node_modules/pg/lib/connection.js:604:11)
    at Connection.parseMessage (/home/ec2-user/environment/node_modules/pg/lib/connection.js:401:19)
    at Socket.<anonymous> (/home/ec2-user/environment/node_modules/pg/lib/connection.js:121:22)
    at Socket.emit (events.js:198:13)
    at addChunk (_stream_readable.js:288:12)
    at readableAddChunk (_stream_readable.js:269:11)
    at Socket.Readable.push (_stream_readable.js:224:10)
    at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)
  name: 'error',
  length: 103,
  severity: 'ERROR',
  code: '42P01',
  detail: undefined,
  hint: undefined,
  position: '15',
  internalPosition: undefined,
  internalQuery: undefined,
  where: undefined,
  schema: undefined,
  table: undefined,
  column: undefined,
  dataType: undefined,
  constraint: undefined,
  file: 'parse_relation.c',
  line: '874',
  routine: 'parserOpenTable' }

If I use psql command and do a select there, it works.

\dt provides me the relation:

   Schema    |     Name     | Type  |  Owner
-------------+--------------+-------+----------
 subnet_calc | free_subnets | table | postgres

Search_path has been set to: subnet_calc, public

I've created the table with user postgres, so I am the owner of the schema subnet_calc and the table free_subnets.

My dummy nodejs code is the following:

const pg = require('pg');

const cs = 'postgres://postgres:password@anydb.rds.amazonaws.com:5432/subnet_calculator';

const client = new pg.Client(cs);
client.connect();

client.query('SELECT * FROM subnet_calc.free_subnets', function(result) {
  console.log(result);
});

What could be the issue?

Thanks for your help in advance!


问:
How to code: if (e.ChangeType == 'Created') do something, when using FileSystemWatcher?
My goal is to code the following.. If change type is created do this, if it is deleted do that. How is this done?

This is what I have tried..

```<code>private static void directoryChange(object source, System.IO.FileSystemEventArgs e)
{
    Console.WriteLine($"{e.ChangeType} - {e.FullPath} - {System.Environment.NewLine}");

    if (e.ChangeType == "Created")
    {
        //do something
    }
}
</code>```

But an error shows up:

Operator == cannot be applied to operands of type WatcherChangeTypes and string

I have also tried

```<code>if (e.ChangeTypeEquals("Created"){
}
</code>```

答: Please replace "Created" by System.IO.WatcherChangeTypes.Created

Body:
My goal is to code the following.. If change type is created do this, if it is deleted do that. How is this done?

This is what I have tried..

private static void directoryChange(object source, System.IO.FileSystemEventArgs e)
{
    Console.WriteLine($"{e.ChangeType} - {e.FullPath} - {System.Environment.NewLine}");

    if (e.ChangeType == "Created")
    {
        //do something
    }
}

But an error shows up:

Operator == cannot be applied to operands of type WatcherChangeTypes and string

I have also tried

if (e.ChangeTypeEquals("Created"){
}


问:
Filtering SQL rows based on values from other rows
Using a SQL Server 2016 SP1 database I have this data in table name AgentsTable:

SELECT * FROM AgentsTable;

```<code>user_id         first_name  last_name   agent_id   agent_status  agent_code
2003015038088   John        Brown       22307      Retired       12345
2003015038088   John        Brown       22307      Death         12399
4432442556456   Mary        Jane        24667      Active        32133
7746234737464   Harry       Smith       29981      Retired       42354
3455555657677   Mark        Aguy        29654      Active        34655
5436546674465   Sally       Sam         22584      Retired       45464
</code>```

The second row shows that 'John Brown' is dead (agent_status = 'Death'), so I would like to exclude all rows for that agent_id who is dead. (Note that John Brown has two different agent_codes, so there's one row for each agent_code. That's how the source data is...)

This query:

SELECT * FROM AgentsTable WHERE agent_status = 'Retired';

Will return this:

```<code>user_id          first_name   last_name    agent_id   agent_status  agent_code
2003015038088    John         Brown        22307      Retired       12345
7746234737464    Harry        Smith        29981      Retired       42354
5436546674465    Sally        Sam          22584      Retired       45464
</code>```

The result I want, where John Brown (22307) is excluded, is:

```<code>user_id          first_name   last_name    agent_id   agent_status  agent_code
7746234737464    Harry        Smith        29981      Retired       42354
5436546674465    Sally        Sam          22584      Retired       45464
</code>```

How can I achieve that? In other words, how can I exclude one row based on a value in another related row?

答: SELECT * FROM AgentsTable t1 WHERE agent_status = 'Retired' where NOT EXISTS (SELECT 1 FROM AgentsTable t2 WHERE t2.agent_status = 'Death' and t2.agent_code = t1. agent_code );</p>

Body:
Using a SQL Server 2016 SP1 database I have this data in table name AgentsTable:

SELECT * FROM AgentsTable;

user_id         first_name  last_name   agent_id   agent_status  agent_code
2003015038088   John        Brown       22307      Retired       12345
2003015038088   John        Brown       22307      Death         12399
4432442556456   Mary        Jane        24667      Active        32133
7746234737464   Harry       Smith       29981      Retired       42354
3455555657677   Mark        Aguy        29654      Active        34655
5436546674465   Sally       Sam         22584      Retired       45464

The second row shows that 'John Brown' is dead (agent_status = 'Death'), so I would like to exclude all rows for that agent_id who is dead. (Note that John Brown has two different agent_codes, so there's one row for each agent_code. That's how the source data is...)

This query:

SELECT * FROM AgentsTable WHERE agent_status = 'Retired';

Will return this:

user_id          first_name   last_name    agent_id   agent_status  agent_code
2003015038088    John         Brown        22307      Retired       12345
7746234737464    Harry        Smith        29981      Retired       42354
5436546674465    Sally        Sam          22584      Retired       45464

The result I want, where John Brown (22307) is excluded, is:

user_id          first_name   last_name    agent_id   agent_status  agent_code
7746234737464    Harry        Smith        29981      Retired       42354
5436546674465    Sally        Sam          22584      Retired       45464

How can I achieve that? In other words, how can I exclude one row based on a value in another related row?


问:
How to start container depent on other container's services in Docker Compose?

 My Docker Compose file have 4 service is web, mongodb, redis, and rabbitmq. The web service can work only if three other service work(container started and service in container also started).

 I had try to use depends_on code on docker-compose.yaml but it only check the other container status, not their service. So it still not work.

So is there any way to start container form other container's service status??

答:
Your problem is the way you developed your service (same problem my devs had when we started building microservices :P).

You need to control, in the app code, whether all the dependencies are up and running, and if that's not the case, exit the program so that the container can fail and restart again automatically.

If you don't do this, the container will keep running, but the dependency was not satisfied, so the outcome is that the service will not be running as expected.


问:
Visual Studio 2017 doesn't resolve a specific reference correctly
There are several projects in my solution which are referencing System.ValueTuple.dll via nuget. The path to the assembly is defined as the same for all of these projects, but however Visual Studio 2017 is resolving it differently. This leads it to build most of the projects over and over again, although there are no changes.

Here's a sample of how the reference is defined in the project file (again, it's the same for all of the projects):

```<code><Reference Include="System.ValueTuple, Version=4.0.2.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
  <HintPath>..\..\..\..\packages\System.ValueTuple.4.4.0\lib\net461\System.ValueTuple.dll</HintPath>
  <Private>True</Private>
</Reference>
</code>```

And here's the message I get, when Visual Studio wrongly resolves the reference for a project and thus builds it again, whether there are changes or not:

Project 'XXX' is not up to date. CopyLocal reference source 'C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\Microsoft\Microsoft.NET.Build.Extensions\net461\lib\System.ValueTuple.dll' is more recent than 'C:\Src\Current.Release\Bin\Debug\System.ValueTuple.dll'.

Why doesn't Visual Studio take the reference I have defined or just fails, if it's not there? It's also showing the wrong path in the references property window.

I can reproduce this behavior on multiple machines. If I check out one of the problematic project files, add a empty line and reload it, it's afterwards resolving the reference correctly. But I mean, there's not really a change I made. If I remap the workspace, the problem comes back.

Hope you guys can help me. Thanks in advance!

答:
if you encounter this problem i suggest you to check if both projects use same .Net Framework version.

I fixed same problem that i had with downgrading .Net Framework of my DAL project from 4.5.2 to 4.5.

Body:
There are several projects in my solution which are referencing System.ValueTuple.dll via nuget. The path to the assembly is defined as the same for all of these projects, but however Visual Studio 2017 is resolving it differently. This leads it to build most of the projects over and over again, although there are no changes.

Here's a sample of how the reference is defined in the project file (again, it's the same for all of the projects):

<Reference Include="System.ValueTuple, Version=4.0.2.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
  <HintPath>..\..\..\..\packages\System.ValueTuple.4.4.0\lib\net461\System.ValueTuple.dll</HintPath>
  <Private>True</Private>
</Reference>

And here's the message I get, when Visual Studio wrongly resolves the reference for a project and thus builds it again, whether there are changes or not:

Project 'XXX' is not up to date. CopyLocal reference source 'C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\Microsoft\Microsoft.NET.Build.Extensions\net461\lib\System.ValueTuple.dll' is more recent than 'C:\Src\Current.Release\Bin\Debug\System.ValueTuple.dll'.

Why doesn't Visual Studio take the reference I have defined or just fails, if it's not there? It's also showing the wrong path in the references property window.

I can reproduce this behavior on multiple machines. If I check out one of the problematic project files, add a empty line and reload it, it's afterwards resolving the reference correctly. But I mean, there's not really a change I made. If I remap the workspace, the problem comes back.

Hope you guys can help me. Thanks in advance!


问:
can't understand systemc '<<' operation
im looking 'risc-cpu' code which is in systemc library(specifically 'example' folder) but i can't understand what << operation in main.cpp is.
   in main.cpp they instantiate each module and do << operation with many sc_signal variable.
i think it's something like binding operation but i want to know exactly.

below is some code from main.cpp

```<code>fetch   IFU("FETCH_BLOCK");      //instiate module fetch
    IFU.init_param(delay_cycles);  //module fetch delay for delay_cycles
    IFU << ram_dataout << branch_target_address << next_pc << branch_valid
        << stall_fetch << intreq << vectno << bios_valid << icache_valid
        << pred_fetch << pred_branch_address << pred_branch_valid << ram_cs << ram_we
        << addr << ram_datain << instruction << instruction_valid << program_counter
        << intack_cpu << branch_clear << pred_fetch_valid << reset << clk;

decode  IDU("DECODE_BLOCK");   //instanciate module decode as IDU
    IDU << reset << instruction << pred_instruction << instruction_valid
        << pred_inst_valid << out_valid << destout << dout << dram_dataout
        << dram_rd_valid << destout << fdout << fout_valid << fdestout
        << branch_clear << dsp_data_valid << program_counter << pred_on
        << branch_instruction_address << next_pc << branch_valid
        << branch_target_address << mem_access << mem_address << alu_op
        << mem_write << alu_src << reg_write << src_A << src_B << forward_A
        << forward_B << stall_fetch << decode_valid << float_valid << mmx_valid
        << pid_valid << pid_data << clk;
</code>```

答: << is the standard left shift operator which in C++ is overloaded to also function as a put-to-stream. It appears to me they're simply writing a lot of values to IFU and IDU.

Title: can't understand systemc '<<' operation

Body:
im looking 'risc-cpu' code which is in systemc library(specifically 'example' folder) but i can't understand what << operation in main.cpp is.
   in main.cpp they instantiate each module and do << operation with many sc_signal variable.
i think it's something like binding operation but i want to know exactly.

below is some code from main.cpp

fetch   IFU("FETCH_BLOCK");      //instiate module fetch
    IFU.init_param(delay_cycles);  //module fetch delay for delay_cycles
    IFU << ram_dataout << branch_target_address << next_pc << branch_valid
        << stall_fetch << intreq << vectno << bios_valid << icache_valid
        << pred_fetch << pred_branch_address << pred_branch_valid << ram_cs << ram_we
        << addr << ram_datain << instruction << instruction_valid << program_counter
        << intack_cpu << branch_clear << pred_fetch_valid << reset << clk;

decode  IDU("DECODE_BLOCK");   //instanciate module decode as IDU
    IDU << reset << instruction << pred_instruction << instruction_valid
        << pred_inst_valid << out_valid << destout << dout << dram_dataout
        << dram_rd_valid << destout << fdout << fout_valid << fdestout
        << branch_clear << dsp_data_valid << program_counter << pred_on
        << branch_instruction_address << next_pc << branch_valid
        << branch_target_address << mem_access << mem_address << alu_op
        << mem_write << alu_src << reg_write << src_A << src_B << forward_A
        << forward_B << stall_fetch << decode_valid << float_valid << mmx_valid
        << pid_valid << pid_data << clk;


问:
How to parse complex logical operations in java?
Is there any way to parse strings which include logical and/or operators and get result as true or false in java? For example

```<code>    (1 OR 0 AND 1 AND 0 OR(0 AND 0))
</code>```

I couldn't find any library. Actually I have some ideas but they are so complex. Maybe some easier way?

答:
You could use already mentioned script engine:

```<code>String expression = "(1 || 0 && 1 && 0 ||(0 && 0))";
Object result = new ScriptEngineManager().getEngineByName("JavaScript").eval(expression);
System.out.println(result);
</code>```

or spring expression language:

```<code>String data = "(true OR false AND true AND false OR(false AND false))";
ExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression(data);
result = exp.getValue();
System.out.println(result);
</code>```

Please note, that in both cases there was needed to modify original expression by replacing eighter lofical operators or logical constants.

Body:
Is there any way to parse strings which include logical and/or operators and get result as true or false in java? For example

    (1 OR 0 AND 1 AND 0 OR(0 AND 0))

I couldn't find any library. Actually I have some ideas but they are so complex. Maybe some easier way?

Body:
You could use already mentioned script engine:

String expression = "(1 || 0 && 1 && 0 ||(0 && 0))";
Object result = new ScriptEngineManager().getEngineByName("JavaScript").eval(expression);
System.out.println(result);

or spring expression language:

String data = "(true OR false AND true AND false OR(false AND false))";
ExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression(data);
result = exp.getValue();
System.out.println(result);

Please note, that in both cases there was needed to modify original expression by replacing eighter lofical operators or logical constants.


问:
How to check if the form has been submitted on localhost
I'm trying to check if the form has been submitted. If I press the submit button, the success message will appear but when I check my mailbox I don't see any message. I'm using WampServer. I followed a YouTube tutorial where the guy has the exact same code but for some reason, it doesn't work for me.

<form action="contact.php" method="post" id="myForm">

    <input type="text" required name="name" id="form_name" class="form-control" />
    Your name

    <input type="email" required name="email" id="form_email" class="form-control" />
    Your email

    <input type="text" name="subject" required id="form-Subject" class="form-control" />
    Subject

    <textarea id="form_text" name="message" class="form-control md-textarea" rows="3"></textarea>
    Your message

    <button class="btn contact-button text-white" type="submit" name="submit">Submit</button>

</form>

<?php
if(isset($_POST['submit']))
{

    $name = $_POST['name'];
    $subject = $_POST['subject'];
    $mailFrom = $_POST['email'];
    $message = $_POST['message'];

    $mailTo = "patriciushorny@gmail.com";
    $headers = "From: ".$mailFrom;
    $txt = "You have recieved an e-mail from ".$name.".\n\n".$message;

    mail($mailFrom, $subject, $txt, $headers);
    header("Location: index.php?mailsend");

}

?>```

答:
```<code><form class="form-area contact-form text-right" action="mail.php" method="post">
    <div class="row">
        <div class="col-lg-6 form-group">
            <input name="name" id="name"  placeholder="Enter your name" class="common-input mb-20 form-control"  type="text">
            <input name="email" id="email" placeholder="Enter email address"   class="common-input mb-20 form-control"  type="email">
            <input name="sub" id="sub" placeholder="Enter subject"  class="common-input mb-20 form-control"  type="text">
        </div>
        <div class="col-lg-6 form-group">
            <textarea class="common-textarea form-control" name="desc" id="desc" placeholder="Enter Messege" ></textarea>
        </div>
        <div class="col-lg-12">
            <button class="genric-btn primary" value="submit" id="submit" name="submit" style="float: right;">Send Message</button>
        </div>
    </div>
</code>```

More Details view this link VIEW FULL CODE

Body:
<form class="form-area contact-form text-right" action="mail.php" method="post">
    <div class="row">
        <div class="col-lg-6 form-group">
            <input name="name" id="name"  placeholder="Enter your name" class="common-input mb-20 form-control"  type="text">
            <input name="email" id="email" placeholder="Enter email address"   class="common-input mb-20 form-control"  type="email">
            <input name="sub" id="sub" placeholder="Enter subject"  class="common-input mb-20 form-control"  type="text">
        </div>
        <div class="col-lg-6 form-group">
            <textarea class="common-textarea form-control" name="desc" id="desc" placeholder="Enter Messege" ></textarea>
        </div>
        <div class="col-lg-12">
            <button class="genric-btn primary" value="submit" id="submit" name="submit" style="float: right;">Send Message</button>
        </div>
    </div>

More Details view this link VIEW FULL CODE


问:
Where does the Azure DevOps/TFS cache extensions data
I have developed Azure DevOps extension and published it to marketplace. Recently I have came across mandatory UI changes. While performing dev testing, I have noticed that once I install new extension (with UI changes) it still showing old UI components.
For example, let’s say I have string input named “Name” and I have replaced it with “Full Name”. I still see my old input which is “Name”.

Old :

```<code>{
            "name": "name",
            "type": "string",
            "label": "Name",
            "required": true
}
</code>```

New:

```<code>{
            "name": "fullName",
            "type": "string",
            "label": "Full Name",
            "required": true
}
</code>```

I removed temp files under below locations, but issue persists.

C:\Users\<< User Name >>\AppData\Local\Microsoft\Team Foundation\

<< Agent Folder >> \ _Work\

Windows Temp folder

I have changed the task id (GUID) and it seems resolving this issue. But this is not viable solution as I cannot issue new task id for already published extension.

Due to this reason I believe best option to resolve this issue is deleting cached data. Please let me know, Where does the Azure DevOps / TFS cache it’s extension data?

Thanks in Advance!

答:
Try to clean the browser cache, and check whether you have increase the version number in the task.json.

Also, try to Delete task -- Save definition -- add task again, which should help.

Body:
I have developed Azure DevOps extension and published it to marketplace. Recently I have came across mandatory UI changes. While performing dev testing, I have noticed that once I install new extension (with UI changes) it still showing old UI components.
For example, let’s say I have string input named “Name” and I have replaced it with “Full Name”. I still see my old input which is “Name”.

Old :

{
            "name": "name",
            "type": "string",
            "label": "Name",
            "required": true
}

New:

{
            "name": "fullName",
            "type": "string",
            "label": "Full Name",
            "required": true
}

I removed temp files under below locations, but issue persists.

C:\Users\<< User Name >>\AppData\Local\Microsoft\Team Foundation\

<< Agent Folder >> \ _Work\

Windows Temp folder

I have changed the task id (GUID) and it seems resolving this issue. But this is not viable solution as I cannot issue new task id for already published extension.

Due to this reason I believe best option to resolve this issue is deleting cached data. Please let me know, Where does the Azure DevOps / TFS cache it’s extension data?

Thanks in Advance!


问:
Why is my child SwiftUI view not updating?
I have a Swift ui view with a child witch gets values from a @State variable. When i update my @State variable the view rebuilds but the child stays the same.</p>

```<code>struct ContentView: View {
  @State var msg: String = ""
  var body: some View {
    VStack {
      Button(action: {
        self.msg = "Hallo World"
      }, label: { Text("Say Hallo")})

      ChildView(msg: msg).padding().background(Color.orange)
      Text(msg).padding().background(Color.green)
    }.frame(maxWidth: .infinity, maxHeight: .infinity)
  }
}

struct ChildView: View {
  @State var msg: String

  var body: some View {
    Text(msg)
  }
}
</code>```

答:
```<code>import SwiftUI

struct ContentView: View {
  @State var msg: String = ""
  var body: some View {
    VStack {
      Button(action: {
        self.msg += "Hallo World "
      }, label: { Text("Say Hallo")})

      ChildView(msg: msg).padding().background(Color.orange)
      Text(msg).padding().background(Color.green)
    }.frame(maxWidth: .infinity, maxHeight: .infinity)
  }
}

struct ChildView: View {
  var msg: String

  var body: some View {
    Text(msg)
  }
}
</code>```

You don't need any state property wrapper in your ChildView. Once msg changed, SwiftUI know, that every View depending on its value should be "reloaded".

In your example, you "fixed" it by wrapping initial value to its state property wrapper. SwiftUI will not reload it, because @State property wrapper means, the value is stored outside of the ChildView. @State property wrapper in not part of View state. It is the opposite, once the @State wrapped property change, SwiftUI will reevaluate View's body computed property. To "reset" @State property wrapped value, you need "recreate" it, which means the state property will be reset to its initial value too.

Body:
I have a Swift ui view with a child witch gets values from a @State variable. When i update my @State variable the view rebuilds but the child stays the same.

struct ContentView: View {
  @State var msg: String = ""
  var body: some View {
    VStack {
      Button(action: {
        self.msg = "Hallo World"
      }, label: { Text("Say Hallo")})

      ChildView(msg: msg).padding().background(Color.orange)
      Text(msg).padding().background(Color.green)
    }.frame(maxWidth: .infinity, maxHeight: .infinity)
  }
}

struct ChildView: View {
  @State var msg: String

  var body: some View {
    Text(msg)
  }
}

Body:
import SwiftUI

struct ContentView: View {
  @State var msg: String = ""
  var body: some View {
    VStack {
      Button(action: {
        self.msg += "Hallo World "
      }, label: { Text("Say Hallo")})

      ChildView(msg: msg).padding().background(Color.orange)
      Text(msg).padding().background(Color.green)
    }.frame(maxWidth: .infinity, maxHeight: .infinity)
  }
}

struct ChildView: View {
  var msg: String

  var body: some View {
    Text(msg)
  }
}

You don't need any state property wrapper in your ChildView. Once msg changed, SwiftUI know, that every View depending on its value should be "reloaded".

In your example, you "fixed" it by wrapping initial value to its state property wrapper. SwiftUI will not reload it, because @State property wrapper means, the value is stored outside of the ChildView. @State property wrapper in not part of View state. It is the opposite, once the @State wrapped property change, SwiftUI will reevaluate View's body computed property. To "reset" @State property wrapped value, you need "recreate" it, which means the state property will be reset to its initial value too.


问:
How do i call a dictionary value from user input
I am new to programming, this is also my first post.

The problem is;

Ask the user how their weight is from a 1 to 4 scale.

```<code>1 = 0.5, 2 = 1.2, 3 = 1.7, 4 = 2.4.
</code>```

I set up my dictionary like this.

So when the user inputs 2

When I execute print, it prints 2 and not 1.2.
how do I update the new value?

答:
I think what you are doing is printing the value of the input instead of value of the
key in the dict. In dict there is a mapping between key and value.
So if you want to print the value of the key 2 you need to ask the dict for the value of key 2.That is done by calling the dict with that particular key .So if we suppose you made a dict called weights like this
`

```<code>weights ={1:0.5,2:1.2,3:1.7,4:2.4}
</code>```

then to get the value for key 2, we need to call the weights with the following syntax.

```<code>value = weights[2]
</code>```

Please check this code and run it to have a better understanding of the problem.

```<code>weights ={1:0.5,2:1.2,3:1.7,4:2.4}
user_input = 0
while user_input not in (weights.keys()):
    user_input = input("Please input the value for weight between 1 to 4: ")
print("Value of weight = %s"%weights[user_input])
</code>```

Body:
I am new to programming, this is also my first post.

The problem is;

Ask the user how their weight is from a 1 to 4 scale.

1 = 0.5, 2 = 1.2, 3 = 1.7, 4 = 2.4.

I set up my dictionary like this.

So when the user inputs 2

When I execute print, it prints 2 and not 1.2.
how do I update the new value?

Body:
I think what you are doing is printing the value of the input instead of value of the
key in the dict. In dict there is a mapping between key and value.
So if you want to print the value of the key 2 you need to ask the dict for the value of key 2.That is done by calling the dict with that particular key .So if we suppose you made a dict called weights like this
`

weights ={1:0.5,2:1.2,3:1.7,4:2.4}

then to get the value for key 2, we need to call the weights with the following syntax.

value = weights[2]

Please check this code and run it to have a better understanding of the problem.

weights ={1:0.5,2:1.2,3:1.7,4:2.4}
user_input = 0
while user_input not in (weights.keys()):
    user_input = input("Please input the value for weight between 1 to 4: ")
print("Value of weight = %s"%weights[user_input])


问:
Laraver DB Query
I am new in Laravel, and I don't know what is happening here. I made a simple join query with two tables, but I get the triple result. I tried with distinct(), orderBy()(getting an error)... Can someone tell me what is happening here

Laravel Query:

```<code>    public function getArtForCom($id) {
    $articles = Article::select('kup_art.rbr as id', 'kup_art.sifra as article_id', 'kup_art.naziv as article_name', 'kup_art.grupa as group_id', 'kup_art.grupa_naziv as group_name', 'ro_stanje.koli as count',  'ro_stanje.v_cije as price')
        ->join('ro_stanje', 'kup_art.sifra', 'ro_stanje.sifra')
        ->where('kupac', $id)
        ->get();
    return response()->json($articles);
}
</code>```

and result is:

```<code>[
  {
    "id": 1,
    "article_id": "000140",
    "article_name": "KECAP BF",
    "group_id": "04",
    "group_name": "KECEPI  ",
    "count": "130.000",
    "price": "3.590"
  },
  {
    "id": 2,
    "article_id": "000407",
    "article_name": "SWISS ROLS",
    "group_id": "13",
    "group_name": "INDUSTRIJSKI ROLAT",
    "count": "485.000",
    "price": ".790"
  },
  {
    "id": 1,
    "article_id": "000140",
    "article_name": "KECAP BF",
    "group_id": "04",
    "group_name": "KECEPI",
    "count": "266.000",
    "price": "3.050"
  },
  {
    "id": 2,
    "article_id": "000407",
    "article_name": "SWISS ROLS",
    "group_id": "13",
    "group_name": "INDUSTRIJSKI ROLAT",
    "count": "7204.000",
    "price": ".490"
  },
  {
    "id": 1,
    "article_id": "000140",
    "article_name": "KECAP BF",
    "group_id": "04",
    "group_name": "KECEPI  ",
    "count": "3.000",
    "price": "3.215"
  },
  {
    "id": 2,
    "article_id": "000407",
    "article_name": "SWISS ROLS",
    "group_id": "13",
    "group_name": "INDUSTRIJSKI ROLAT",
    "count": "17.000",
    "price": ".490"
  },
  {
    "id": 1,
    "article_id": "000140",
    "article_name": "KECAP BF",
    "group_id": "04",
    "group_name": "KECEPI  ",
    "count": ".000",
    "price": "3.215"
  },
  {
    "id": 2,
    "article_id": "000407",
    "article_name": "SWISS ROLS",
    "group_id": "13",
    "group_name": "INDUSTRIJSKI ROLAT",
    "count": "69.000",
    "price": ".490"
  },
  {
    "id": 1,
    "article_id": "000140",
    "article_name": "KECAP BF",
    "group_id": "04",
    "group_name": "KECEPI  ",
    "count": "2.000",
    "price": "3.215"
  },
  {
    "id": 2,
    "article_id": "000407",
    "article_name": "SWISS ROLS",
    "group_id": "13",
    "group_name": "INDUSTRIJSKI ROLAT",
    "count": "48.000",
    "price": ".490"
  },
  {
    "id": 2,
    "article_id": "000407",
    "article_name": "SWISS ROLS",
    "group_id": "13",
    "group_name": "INDUSTRIJSKI ROLAT",
    "count": "30.000",
    "price": ".488"
  }
]
</code>```

答:
You are not getting duplicate results. The results return the same products, but the variety of price and count:

```<code> {
     "id": 1,
     "article_id": "000140",
     "article_name": "KECAP BF",
     "group_id": "04",
     "group_name": "KECEPI  ",
     "count": "130.000",
     "price": "3.590"
  }
</code>```

Count and Price are different:

```<code> {
    "id": 1,
    "article_id": "000140",
    "article_name": "KECAP BF",
    "group_id": "04",
    "group_name": "KECEPI",
    "count": "266.000",
    "price": "3.050"
  },
</code>```

You could add groupBy('kup_art.sifra'), but results won't be accurate, so it is better to check in the DB why are there multiple data for price and stock for the same SKU.

Title: Laraver DB Query

Body:
I am new in Laravel, and I don't know what is happening here. I made a simple join query with two tables, but I get the triple result. I tried with distinct(), orderBy()(getting an error)... Can someone tell me what is happening here

Laravel Query:

    public function getArtForCom($id) {
    $articles = Article::select('kup_art.rbr as id', 'kup_art.sifra as article_id', 'kup_art.naziv as article_name', 'kup_art.grupa as group_id', 'kup_art.grupa_naziv as group_name', 'ro_stanje.koli as count',  'ro_stanje.v_cije as price')
        ->join('ro_stanje', 'kup_art.sifra', 'ro_stanje.sifra')
        ->where('kupac', $id)
        ->get();
    return response()->json($articles);
}

and result is:

[
  {
    "id": 1,
    "article_id": "000140",
    "article_name": "KECAP BF",
    "group_id": "04",
    "group_name": "KECEPI  ",
    "count": "130.000",
    "price": "3.590"
  },
  {
    "id": 2,
    "article_id": "000407",
    "article_name": "SWISS ROLS",
    "group_id": "13",
    "group_name": "INDUSTRIJSKI ROLAT",
    "count": "485.000",
    "price": ".790"
  },
  {
    "id": 1,
    "article_id": "000140",
    "article_name": "KECAP BF",
    "group_id": "04",
    "group_name": "KECEPI",
    "count": "266.000",
    "price": "3.050"
  },
  {
    "id": 2,
    "article_id": "000407",
    "article_name": "SWISS ROLS",
    "group_id": "13",
    "group_name": "INDUSTRIJSKI ROLAT",
    "count": "7204.000",
    "price": ".490"
  },
  {
    "id": 1,
    "article_id": "000140",
    "article_name": "KECAP BF",
    "group_id": "04",
    "group_name": "KECEPI  ",
    "count": "3.000",
    "price": "3.215"
  },
  {
    "id": 2,
    "article_id": "000407",
    "article_name": "SWISS ROLS",
    "group_id": "13",
    "group_name": "INDUSTRIJSKI ROLAT",
    "count": "17.000",
    "price": ".490"
  },
  {
    "id": 1,
    "article_id": "000140",
    "article_name": "KECAP BF",
    "group_id": "04",
    "group_name": "KECEPI  ",
    "count": ".000",
    "price": "3.215"
  },
  {
    "id": 2,
    "article_id": "000407",
    "article_name": "SWISS ROLS",
    "group_id": "13",
    "group_name": "INDUSTRIJSKI ROLAT",
    "count": "69.000",
    "price": ".490"
  },
  {
    "id": 1,
    "article_id": "000140",
    "article_name": "KECAP BF",
    "group_id": "04",
    "group_name": "KECEPI  ",
    "count": "2.000",
    "price": "3.215"
  },
  {
    "id": 2,
    "article_id": "000407",
    "article_name": "SWISS ROLS",
    "group_id": "13",
    "group_name": "INDUSTRIJSKI ROLAT",
    "count": "48.000",
    "price": ".490"
  },
  {
    "id": 2,
    "article_id": "000407",
    "article_name": "SWISS ROLS",
    "group_id": "13",
    "group_name": "INDUSTRIJSKI ROLAT",
    "count": "30.000",
    "price": ".488"
  }
]

Body:
You are not getting duplicate results. The results return the same products, but the variety of price and count:

 {
     "id": 1,
     "article_id": "000140",
     "article_name": "KECAP BF",
     "group_id": "04",
     "group_name": "KECEPI  ",
     "count": "130.000",
     "price": "3.590"
  }

Count and Price are different:

 {
    "id": 1,
    "article_id": "000140",
    "article_name": "KECAP BF",
    "group_id": "04",
    "group_name": "KECEPI",
    "count": "266.000",
    "price": "3.050"
  },

You could add groupBy('kup_art.sifra'), but results won't be accurate, so it is better to check in the DB why are there multiple data for price and stock for the same SKU.


问:
Avoid caching redirect from Special:Random in varnish
I'm using varnish to serve content from my MediaWiki installation to my users. Nearly every page is cached correctly, as defined in the vcl:

```<code>vcl 4.0;

backend default {
    .host = "xxxx";
    .port = "xxxx";
}

backend thumbor {
    .host = "xxxx";
    .port = "xxxx";
}

acl purge {
    "xxxx";
}

sub vcl_recv {
        set req.http.X-Forwarded-For = req.http.X-Forwarded-For + ", " + client.ip;
        set req.backend_hint= default;

        if (req.method == "PURGE") {
            if (!client.ip ~ purge) {
                return (synth(405, "Not allowed."));
            } else {
                return (purge);
            }
        }

        if (req.method != "GET" && req.method != "HEAD" &&
            req.method != "PUT" && req.method != "POST" &&
            req.method != "TRACE" && req.method != "OPTIONS" &&
            req.method != "DELETE") {
                return (pipe);
        }

        if (req.method != "GET" && req.method != "HEAD") {
            return (pass);
        }

    if (req.http.If-None-Match) {
        return (pass);
    }

    if (req.http.X-Debug-Server) {
        return (pass);
    }

    if (req.http.Cache-Control ~ "no-cache") {
        ban(req.url);
    }

        if (req.http.Accept-Encoding) {
          if (req.http.User-Agent ~ "MSIE 6") {
            unset req.http.Accept-Encoding;
          } elsif (req.http.Accept-Encoding ~ "gzip") {
            set req.http.Accept-Encoding = "gzip";
          } elsif (req.http.Accept-Encoding ~ "deflate") {
            set req.http.Accept-Encoding = "deflate";
          } else {
            unset req.http.Accept-Encoding;
          }
        }

    if (req.url ~ "(?i)\.(jpg|jpeg|jpe|png)$" && req.url ~ "(?i)/thumb/" && req.http.Accept ~ "(?i)image/webp" && req.http.x-no-thumbor != "yes") {
        set req.http.x-orig-url = req.url;
        set req.url = regsub(req.url,".*\/thumb\/(.*)","/unsafe/filters:format(webp)/thumb/\1");
        set req.backend_hint = thumbor;
    }

    if (req.url ~ "action=amp$") {
        unset req.http.Cookie;
        unset req.http.x-wap;
        return (hash);
    }

        if (req.http.Authorization || req.http.Cookie ~ "session" || req.http.Cookie ~ "Token") {
            return (pass);
        }

    if (req.http.Cookie ~ "droidwikiwikicookiewarning_dismissed=true") {
        set req.http.Cookie = "droidwikiwikicookiewarning_dismissed=true";
    } else {
        unset req.http.Cookie;
    }

    unset req.http.x-wap;
    if (req.http.User-Agent ~ "(?i)^(lg-|sie-|nec-|lge-|sgh-|pg-)|(mobi|240x240|240x320|320x320|alcatel|android|audiovox|bada|benq|blackberry|cdm-|compal-|docomo|ericsson|hiptop|htc[-_]|huawei|ipod|kddi-|kindle|meego|midp|mitsu|mmp\/|mot-|motor|ngm_|nintendo|opera.m|palm|panasonic|philips|phone|playstation|portalmmm|sagem-|samsung|sanyo|sec-|sendo|sharp|softbank|symbian|teleca|up.browser|webos)" && req.url !~ "(\?|&)(action=amp)") {
        set req.http.x-wap = "no";
    }

    if (req.http.Cookie ~ "mf_useformat=") {
        set req.http.x-wap = "no";
    }

        return (hash);
}

sub vcl_hash {
    hash_data(req.http.x-wap);
}

sub vcl_pipe {
        set req.http.connection = "close";
}

sub vcl_purge {
    if (req.url !~ "(\?|&)(action=amp)") {
        set req.http.X-Original = req.url;
        if (req.url ~ "&") {
            set req.url = req.url + "&action=amp";
        } else {
            set req.url = req.url + "?action=amp";
        }
        return (restart);
    }

    if (req.http.X-Original) {
        set req.url = req.http.X-Original;
    }

    if (!req.http.x-wap) {
        set req.http.x-wap = "no";
        return (restart);
    }
}

sub vcl_hit {
        if (req.method == "PURGE") {
            ban(req.url);
            return (synth(200, "Purged"));
        }

        if (!obj.ttl > 0s) {
            return (pass);
        }
}

sub vcl_miss {
        if (req.method == "PURGE")  {
            return (synth(200, "Not in cache"));
        }
}

sub vcl_deliver {
    if (resp.http.x-origin == "thumbor" && resp.status != 200) {
        set req.url = req.http.x-orig-url;
        set req.http.x-no-thumbor = "yes";
        return (restart);
    }

    if (obj.hits > 0) {
        set resp.http.X-Cache = "HIT";
    } else {
        set resp.http.X-Cache = "MISS";
    }
}

sub vcl_backend_error {
    set beresp.http.x-origin = beresp.backend.name;
}

sub vcl_backend_response {
        set beresp.grace = 120s;

        if (beresp.ttl < 48h) {
          set beresp.ttl = 48h;
        }

        if (!beresp.ttl > 0s) {
          set beresp.uncacheable = true;
          return (deliver);
        }

        if (beresp.http.Set-Cookie) {
          set beresp.uncacheable = true;
          return (deliver);
        }

        if (beresp.http.Authorization && !beresp.http.Cache-Control ~ "public") {
          set beresp.uncacheable = true;
          return (deliver);
        }

        return (deliver);
}
</code>```

However, the current configuration also results in redirects being cached. While this is a totally expected behaviour for usual redirecting pages (like article A redirecting to article B), it's unexpected for the Special:Random page. This page is expected to direct me to a random page on each time I open it. However, as the redirect is cached by varnish, I get redirected to the same page always.

What I thought about already:
1. Not caching 302 redirects at all, however, this might have negative impact to other redirects, which I usually would like to being cached
2. Having an url filter on Special:Random, however, doing this I would be required to do this excemption for all languages the wiki supports, in order to have it reliable. I'm not very happy about this

My question here would now be: Does anyone has an idea how this can be achieved with a rule, that doesn't need maintenance and also only covers Special:Random? Maybe a solution, which is also used by Wikimedia wikis? There, the Special:Random page redirects to always another page, however, I wasn't able to find the code block that achieves that in their code repo :(

答:
Varnish respects the conventional Cache-Control HTTP response header that can be sent from your application.

I'm no MediaWiki expert, but I noticed MediaWiki provides hooks to extends its behavior. If you can hook into the request/response flow of MediaWiki and detect the Special:Random case, you might be able to inject a Cache-Control: private, no-cache, no-store header that forces Varnish not to cache these pages.

This would be an ideal way of getting expected result, without having to write VCL.

In general it is good practice to leverage HTTP's caching headers to control the behavior of a reverse caching proxy like Varnish.

It makes the application more portable

It makes the application less dependent on specific caching technology

It empowers developers to think about caching from within the architecture of the application

Body:
I'm using varnish to serve content from my MediaWiki installation to my users. Nearly every page is cached correctly, as defined in the vcl:

vcl 4.0;

backend default {
    .host = "xxxx";
    .port = "xxxx";
}

backend thumbor {
    .host = "xxxx";
    .port = "xxxx";
}

acl purge {
    "xxxx";
}

sub vcl_recv {
        set req.http.X-Forwarded-For = req.http.X-Forwarded-For + ", " + client.ip;
        set req.backend_hint= default;

        if (req.method == "PURGE") {
            if (!client.ip ~ purge) {
                return (synth(405, "Not allowed."));
            } else {
                return (purge);
            }
        }

        if (req.method != "GET" && req.method != "HEAD" &&
            req.method != "PUT" && req.method != "POST" &&
            req.method != "TRACE" && req.method != "OPTIONS" &&
            req.method != "DELETE") {
                return (pipe);
        }

        if (req.method != "GET" && req.method != "HEAD") {
            return (pass);
        }

    if (req.http.If-None-Match) {
        return (pass);
    }

    if (req.http.X-Debug-Server) {
        return (pass);
    }

    if (req.http.Cache-Control ~ "no-cache") {
        ban(req.url);
    }

        if (req.http.Accept-Encoding) {
          if (req.http.User-Agent ~ "MSIE 6") {
            unset req.http.Accept-Encoding;
          } elsif (req.http.Accept-Encoding ~ "gzip") {
            set req.http.Accept-Encoding = "gzip";
          } elsif (req.http.Accept-Encoding ~ "deflate") {
            set req.http.Accept-Encoding = "deflate";
          } else {
            unset req.http.Accept-Encoding;
          }
        }

    if (req.url ~ "(?i)\.(jpg|jpeg|jpe|png)$" && req.url ~ "(?i)/thumb/" && req.http.Accept ~ "(?i)image/webp" && req.http.x-no-thumbor != "yes") {
        set req.http.x-orig-url = req.url;
        set req.url = regsub(req.url,".*\/thumb\/(.*)","/unsafe/filters:format(webp)/thumb/\1");
        set req.backend_hint = thumbor;
    }

    if (req.url ~ "action=amp$") {
        unset req.http.Cookie;
        unset req.http.x-wap;
        return (hash);
    }

        if (req.http.Authorization || req.http.Cookie ~ "session" || req.http.Cookie ~ "Token") {
            return (pass);
        }

    if (req.http.Cookie ~ "droidwikiwikicookiewarning_dismissed=true") {
        set req.http.Cookie = "droidwikiwikicookiewarning_dismissed=true";
    } else {
        unset req.http.Cookie;
    }

    unset req.http.x-wap;
    if (req.http.User-Agent ~ "(?i)^(lg-|sie-|nec-|lge-|sgh-|pg-)|(mobi|240x240|240x320|320x320|alcatel|android|audiovox|bada|benq|blackberry|cdm-|compal-|docomo|ericsson|hiptop|htc[-_]|huawei|ipod|kddi-|kindle|meego|midp|mitsu|mmp\/|mot-|motor|ngm_|nintendo|opera.m|palm|panasonic|philips|phone|playstation|portalmmm|sagem-|samsung|sanyo|sec-|sendo|sharp|softbank|symbian|teleca|up.browser|webos)" && req.url !~ "(\?|&)(action=amp)") {
        set req.http.x-wap = "no";
    }

    if (req.http.Cookie ~ "mf_useformat=") {
        set req.http.x-wap = "no";
    }

        return (hash);
}

sub vcl_hash {
    hash_data(req.http.x-wap);
}

sub vcl_pipe {
        set req.http.connection = "close";
}

sub vcl_purge {
    if (req.url !~ "(\?|&)(action=amp)") {
        set req.http.X-Original = req.url;
        if (req.url ~ "&") {
            set req.url = req.url + "&action=amp";
        } else {
            set req.url = req.url + "?action=amp";
        }
        return (restart);
    }

    if (req.http.X-Original) {
        set req.url = req.http.X-Original;
    }

    if (!req.http.x-wap) {
        set req.http.x-wap = "no";
        return (restart);
    }
}

sub vcl_hit {
        if (req.method == "PURGE") {
            ban(req.url);
            return (synth(200, "Purged"));
        }

        if (!obj.ttl > 0s) {
            return (pass);
        }
}

sub vcl_miss {
        if (req.method == "PURGE")  {
            return (synth(200, "Not in cache"));
        }
}

sub vcl_deliver {
    if (resp.http.x-origin == "thumbor" && resp.status != 200) {
        set req.url = req.http.x-orig-url;
        set req.http.x-no-thumbor = "yes";
        return (restart);
    }

    if (obj.hits > 0) {
        set resp.http.X-Cache = "HIT";
    } else {
        set resp.http.X-Cache = "MISS";
    }
}

sub vcl_backend_error {
    set beresp.http.x-origin = beresp.backend.name;
}

sub vcl_backend_response {
        set beresp.grace = 120s;

        if (beresp.ttl < 48h) {
          set beresp.ttl = 48h;
        }

        if (!beresp.ttl > 0s) {
          set beresp.uncacheable = true;
          return (deliver);
        }

        if (beresp.http.Set-Cookie) {
          set beresp.uncacheable = true;
          return (deliver);
        }

        if (beresp.http.Authorization && !beresp.http.Cache-Control ~ "public") {
          set beresp.uncacheable = true;
          return (deliver);
        }

        return (deliver);
}

However, the current configuration also results in redirects being cached. While this is a totally expected behaviour for usual redirecting pages (like article A redirecting to article B), it's unexpected for the Special:Random page. This page is expected to direct me to a random page on each time I open it. However, as the redirect is cached by varnish, I get redirected to the same page always.

What I thought about already:
1. Not caching 302 redirects at all, however, this might have negative impact to other redirects, which I usually would like to being cached
2. Having an url filter on Special:Random, however, doing this I would be required to do this excemption for all languages the wiki supports, in order to have it reliable. I'm not very happy about this

My question here would now be: Does anyone has an idea how this can be achieved with a rule, that doesn't need maintenance and also only covers Special:Random? Maybe a solution, which is also used by Wikimedia wikis? There, the Special:Random page redirects to always another page, however, I wasn't able to find the code block that achieves that in their code repo :(


问:
Regex for emails but with whitelists
I wanna find something that would work like:

Exclude all emails that are @aaa.*   like someone@aaa.com or someoneElse@aaa.net
But let NoEmail@aaa.com and Exception@aaa.com

I don't know how to combine to emphasize the first rule but have exceptions.

Also i would like to add a email pattern verification so it has an @ then a . (i have this rule, just need to combine all 3 items)

答:
Why not execute these conditions in separate statements? First check if it's email at all, then check if it's in whitelist. And finally reject any not allowed emails.

var emails = {
  'notEmailAtAlll': false,
  'someone@aaa.com': false,
  'someoneElse@aaa.net': false,
  'ExcludeEmail@aaa.com': false,
  'NoEmail@aaa.com': true,
  'Exception@aaa.com': true
};

var whitelist = [
  'NoEmail@aaa.com',
  'Exception@aaa.com'
];

for (let [email, condition] of Object.entries(emails)) {
  console.log(email, condition, validateEmail(email));
}

function validateEmail(email) {
  // Check if email. Replace regex with proper email checker regex
  if (!/\w+@\w+\./.test(email)) {
    return false;
  }

  if (whitelist.includes(email)) {
    return true;
  }

  if (email.indexOf('@aaa.') !== -1) {
    return false;
  }

  return true;
}```

Title: Regex for emails but with whitelists


问:
Descending with virtual sticks generate drift problems on Mavic 2 pro
I'm using virtual sticks to descend as fast as possible 4m/s but is getting a lot of drift from the wind. I don't know if is something related to the rotors spining at lower speed that can't counter cat the wind or the virtual stick are working in ATI mode. Also checking the apiI found that in the Android we have the option setVirtualStickAdvancedModeEnabled which say "advanced mode will allow aircraft to compensate for wind when hovering" but on iOS we only have setVirtualStickModeEnabled so I don't know if in iOS only works in ATI mode.

Any idea?

答:
Even though the documentation does not list the function to enable the advanced mode, you can check if you are able to set it in your code, maybe DJI just forgot to write the documentation for it.

Additionally you can enable VisionAssistedPositioning to stabilize the drone if you haven't done so yet.

If this doesn't help, try to set the upper cap for the velocity lower than 4m/s and see how the drone reacts to a reduced maxSpeed.


问:
Why can not pass "std" prefix when giving Predicate parameter
I have this code:

```<code>#include <cctype>
#include <algorithm>

int main()
{
    std::string str("ABCD");
    std::all_of(str.begin(), str.end(), ::isxdigit);
    return 0;
}
</code>```

std::all_of requires a Predicate as last argument. What I want to pass is std::isxdigit. When I pass it as ::isxdigit it works fine, but when I pass it with std, like std::isxdigit, I get this error:

```<code>12:58: error: no matching function for call to 'all_of(std::basic_string<char>::iterator, std::basic_string<char>::iterator, <unresolved overloaded function type>)'
12:58: note: candidate is:
In file included from /usr/include/c++/4.9/algorithm:62:0,
                 from 6:
/usr/include/c++/4.9/bits/stl_algo.h:508:5: note: template<class _IIter, class _Predicate> bool std::all_of(_IIter, _IIter, _Predicate)
     all_of(_InputIterator __first, _InputIterator __last, _Predicate __pred)
     ^
/usr/include/c++/4.9/bits/stl_algo.h:508:5: note:   template argument deduction/substitution failed:
12:58: note:   couldn't deduce template parameter '_Predicate'
</code>```

Why am I getting this error?
What is wrong with passing it with std prefix, if it DO is of std?

答:
In order to make it working with std::isxdigit you should write something like:

#include <cctype>
#include <string>
#include <algorithm>

int main()
{
    std::string str("ABCD");
    std::all_of(str.begin(), str.end(), [](unsigned char c){ return std::isxdigit(c); });
    return 0;
}
```

Demo

Body:
I have this code:

#include <cctype>
#include <algorithm>

int main()
{
    std::string str("ABCD");
    std::all_of(str.begin(), str.end(), ::isxdigit);
    return 0;
}

std::all_of requires a Predicate as last argument. What I want to pass is std::isxdigit. When I pass it as ::isxdigit it works fine, but when I pass it with std, like std::isxdigit, I get this error:

12:58: error: no matching function for call to 'all_of(std::basic_string<char>::iterator, std::basic_string<char>::iterator, <unresolved overloaded function type>)'
12:58: note: candidate is:
In file included from /usr/include/c++/4.9/algorithm:62:0,
                 from 6:
/usr/include/c++/4.9/bits/stl_algo.h:508:5: note: template<class _IIter, class _Predicate> bool std::all_of(_IIter, _IIter, _Predicate)
     all_of(_InputIterator __first, _InputIterator __last, _Predicate __pred)
     ^
/usr/include/c++/4.9/bits/stl_algo.h:508:5: note:   template argument deduction/substitution failed:
12:58: note:   couldn't deduce template parameter '_Predicate'

Why am I getting this error?
What is wrong with passing it with std prefix, if it DO is of std?

Body:
In order to make it working with std::isxdigit you should write something like:

#include <cctype>
#include <string>
#include <algorithm>

int main()
{
    std::string str("ABCD");
    std::all_of(str.begin(), str.end(), [](unsigned char c){ return std::isxdigit(c); });
    return 0;
}

<a href="https://godbolt.org/#g:!((g:!((g:!((h:codeEditor,i:(fontScale:14,j:1,lang:c%2B%2B,selection:(endColumn:2,endLineNumber:10,positionColumn:2,positionLineNumber:10,selectionStartColumn:2,selectionStartLineNumber:10,startColumn:2,startLineNumber:10),source:'%23include+%3Ccctype%3E%0A%23include+%3Cstring%3E%0A%23include+%3Calgorithm%3E%0A%0Aint+main()%0A%7B%0A++++std::string+str(%22ABCD%22)%3B%0A++++std::all_of(str.begin(),+str.end(),+%5B%5D(unsigned+char+c)%7B+return+std::isxdigit(c)%3B+%7D)%3B%0A++++return+0%3B%0A%7D'),l:'5',n:'0',o:'C%2B%2B+source+%231',t:'0')),k:49.85494633014216,l:'4',n:'0',o:'',s:0,t:'0'),(g:!((g:!((h:compiler,i:(compiler:gsnapshot,filters:(b:'0',binary:'1',commentOnly:'0',demangle:'0',directives:'0',execute:'0',intel:'0',libraryCode:'1',trim:'1'),fontScale:14,j:2,lang:c%2B%2B,libs:!(),options:'-std%3Dc%2B%2B11',selection:(endColumn:1,endLineNumber:1,positionColumn:1,positionLineNumber:1,selectionStartColumn:1,selectionStartLineNumber:1,startColumn:1,startLineNumber:1),source:1),l:'5',n:'0',o:'x86-64+gcc+(trunk)+(Editor+%231,+Compiler+%232)+C%2B%2B',t:'0')),k:50.145053669857845,l:'4',m:50,n:'0',o:'',s:0,t:'0'),(g:!((h:output,i:(compiler:2,editor:1,fontScale:14,wrap:'1'),l:'5',n:'0',o:'%232+with+x86-64+gcc+(trunk)',t:'0')),header:(),l:'4',m:50,n:'0',o:'',s:0,t:'0')),k:50.145053669857845,l:'3',n:'0',o:'',t:'0')),l:'2',n:'0',o:'',t:'0')),version:4" rel="nofollow noreferrer">Demo


问:
Getting a syntax error in Mysql create procedure statement which comes from the script I have exported from another mysql server
The following code generates an error saying there is a syntax error. I couldn't find any syntax error in this. Beside that, it cant have any syntax error since it has been imported in the form of script from another MySql server unless there is an update in the MySql language itself. if the error is due to the version difference, please can someone throw some light on how the code should be in the newer version.

```<code> CREATE DEFINER=`root`@`localhost` PROCEDURE `iterate_day` (IN `p1` TIME, IN `p2` TIME)  BEGIN
  SET @et = DATE_ADD(NOW(), INTERVAL 1 DAY);
  SET @currt = DATE_ADD(NOW(), INTERVAL 1 DAY);
  SET @lastday = DATE_ADD(NOW(), INTERVAL 30 DAY);
  SET @startHour = p1;
  SET @currHour = p1;
  SET @endHour = p2;
  WHILE  @currt<=@lastday  DO

  WHILE @currHour < @endHour   DO
    SET @currHour = ADDTIME(@currHour,'00:30:00');

  INSERT INTO `blooddb`.`appointments` (`Date`, `timeStart`, `timeEnd`, `status`, `client_id`, `app_id` ) VALUES (@currt, @startHour, @currHour, 1, NULL, NULL) ON DUPLICATE KEY UPDATE `date` = `date` ;
  END WHILE;
  SET @currt = DATE_ADD(@currt, INTERVAL 1 DAY);
  SET @startHour = p1;
  SET @currHour = p1;
  END WHILE;
END
</code>```

The error:

```<code>You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 2
</code>```

Can someone indicate whats wrong in the code

答:
To avoid MySQL thinking the ; within the procedures are ending the create procedure, you need to change the delimter for the end of a statement. Currently it is ;. You can set it to literally anything else.

If you use the mysql client program to define a stored program containing semicolon characters, a problem arises. By default, mysql itself recognizes the semicolon as a statement delimiter, so you must redefine the delimiter temporarily to cause mysql to pass the entire stored program definition to the server.

The MySQL documentation suggests //.

Don't forget to set it back to ;.

```<code>delimiter //

CREATE DEFINER=`root`@`localhost` PROCEDURE `iterate_day` (IN `p1` TIME, IN `p2` TIME)  BEGIN
  SET @et = DATE_ADD(NOW(), INTERVAL 1 DAY);
  ...
END

//

delimter ;
</code>```

Body:
The following code generates an error saying there is a syntax error. I couldn't find any syntax error in this. Beside that, it cant have any syntax error since it has been imported in the form of script from another MySql server unless there is an update in the MySql language itself. if the error is due to the version difference, please can someone throw some light on how the code should be in the newer version.

 CREATE DEFINER=`root`@`localhost` PROCEDURE `iterate_day` (IN `p1` TIME, IN `p2` TIME)  BEGIN
  SET @et = DATE_ADD(NOW(), INTERVAL 1 DAY);
  SET @currt = DATE_ADD(NOW(), INTERVAL 1 DAY);
  SET @lastday = DATE_ADD(NOW(), INTERVAL 30 DAY);
  SET @startHour = p1;
  SET @currHour = p1;
  SET @endHour = p2;
  WHILE  @currt<=@lastday  DO

  WHILE @currHour < @endHour   DO
    SET @currHour = ADDTIME(@currHour,'00:30:00');

  INSERT INTO `blooddb`.`appointments` (`Date`, `timeStart`, `timeEnd`, `status`, `client_id`, `app_id` ) VALUES (@currt, @startHour, @currHour, 1, NULL, NULL) ON DUPLICATE KEY UPDATE `date` = `date` ;
  END WHILE;
  SET @currt = DATE_ADD(@currt, INTERVAL 1 DAY);
  SET @startHour = p1;
  SET @currHour = p1;
  END WHILE;
END

The error:

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 2

Can someone indicate whats wrong in the code

Body:
To avoid MySQL thinking the ; within the procedures are ending the create procedure, you need to change the delimter for the end of a statement. Currently it is ;. You can set it to literally anything else.

If you use the mysql client program to define a stored program containing semicolon characters, a problem arises. By default, mysql itself recognizes the semicolon as a statement delimiter, so you must redefine the delimiter temporarily to cause mysql to pass the entire stored program definition to the server.

The MySQL documentation suggests //.

Don't forget to set it back to ;.

delimiter //

CREATE DEFINER=`root`@`localhost` PROCEDURE `iterate_day` (IN `p1` TIME, IN `p2` TIME)  BEGIN
  SET @et = DATE_ADD(NOW(), INTERVAL 1 DAY);
  ...
END

//

delimter ;


问:
Why does my selection sort fail when I hardcode a non-zero minimum value?
My code isn't performing a selection sort successfully when I specify min = arr[0] before entering the loop to process the array, it fails.

```<code>#include <stdio.h>
#include <stdlib.h>

int main()
{
    int arr[11] = {7, 12, 4, 28, 3, 15, 7, 3, 89, 1, 12};
    int x, i, next_index;

    /* Select first element (i = 0) first for loop and compare it with all
       elements of array till the end of array second for loop (so next
       iteration, when i = 1 the first element will be the smallest one */

    for (i = 0; i <= 10; i++)
    {
        // min = arr[0]; /* <-- WHEN I UNCOMMENT THIS THE CODE FAILS. WHY? */

        /* Select min element */
        for (next_index = i + 1; next_index <= 10; next_index++)
        {
            if (arr[next_index] < arr[i])
            {
                 /* Swap arr[i] with min value */
                 x = arr[i];
                 arr[i] = arr[next_index];
                 arr[next_index] = x;
            }
        }
     }
     printf("Sorted array: \n");

     for (i = 0; i <= 10; i++)
        printf(" %d \n", arr[i]);

     return 0;
}
</code>```

答: Second code is not working correctly because you are not swapping values correctly. Secondly the logic of assigning min = arr[0] will mot work, it’s logically wrong. You may need to do like min = arr[i] and swapping the values correctly.</p>

Body:
My code isn't performing a selection sort successfully when I specify min = arr[0] before entering the loop to process the array, it fails.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int arr[11] = {7, 12, 4, 28, 3, 15, 7, 3, 89, 1, 12};
    int x, i, next_index;

    /* Select first element (i = 0) first for loop and compare it with all
       elements of array till the end of array second for loop (so next
       iteration, when i = 1 the first element will be the smallest one */

    for (i = 0; i <= 10; i++)
    {
        // min = arr[0]; /* <-- WHEN I UNCOMMENT THIS THE CODE FAILS. WHY? */

        /* Select min element */
        for (next_index = i + 1; next_index <= 10; next_index++)
        {
            if (arr[next_index] < arr[i])
            {
                 /* Swap arr[i] with min value */
                 x = arr[i];
                 arr[i] = arr[next_index];
                 arr[next_index] = x;
            }
        }
     }
     printf("Sorted array: \n");

     for (i = 0; i <= 10; i++)
        printf(" %d \n", arr[i]);

     return 0;
}