问:
JS: delete first element from array by value
I have an array:

```<code>arr = [50, 40, 50, 50];
</code>```

I need to delete first element, that equal 50 and dont touch another.
This code return only [40].

```<code>arr = arr.filter(function(e) {return e !== 50}) // [40]
</code>```

But I need

```<code>arr = arr.somefunction(function(e) {return e !== 50}) // [40, 50, 50]
</code>```

I would be grateful for any help.

答:
Here's a curried function for that.  It does not modify your original array, returning a new one instead:

const removeFirst = (val) => ( xs = [], idx = xs .indexOf (val) ) => idx > -1
  ? xs .slice (0, idx) .concat ( xs .slice (idx + 1) )
  : xs

console .log (
  removeFirst (50) ([50, 40, 50, 50])
)```
</div>
</div>
</p>

<p>If you prefer to call it like <code>remove(50, [50, 40, 50, 50])</code>, then you can just change the first line: </p>

<pre class="lang-js prettyprint-override"><code>const removeFirst = (val, xs = [], idx = xs .indexOf (val) ) => idx > -1
  ? xs .slice (0, idx) .concat ( xs .slice (idx + 1) )
  : xs
</code>```

Body:
I have an array:

arr = [50, 40, 50, 50];

I need to delete first element, that equal 50 and dont touch another.
This code return only [40].

arr = arr.filter(function(e) {return e !== 50}) // [40]

But I need

arr = arr.somefunction(function(e) {return e !== 50}) // [40, 50, 50]

I would be grateful for any help.

Body:
Here's a curried function for that.  It does not modify your original array, returning a new one instead:

const removeFirst = (val) => ( xs = [], idx = xs .indexOf (val) ) => idx > -1
  ? xs .slice (0, idx) .concat ( xs .slice (idx + 1) )
  : xs

console .log (
  removeFirst (50) ([50, 40, 50, 50])
)

If you prefer to call it like remove(50, [50, 40, 50, 50]), then you can just change the first line:

const removeFirst = (val, xs = [], idx = xs .indexOf (val) ) => idx > -1
  ? xs .slice (0, idx) .concat ( xs .slice (idx + 1) )
  : xs


来源: stackexchange

问:
Getting Users API access in nodejs AppEngine environment with Identity Aware Proxy
I have a nodejs app deployed on AppEngine with IAP enabled, so right now access to its endpoints is protected against users outside of the project's IAM and I get the "x-goog-authenticated-user-id", "x-goog-authenticated-user-email" and another jwt assertion x-goog signed header, just like it should be (as detailed here https://cloud.google.com/iap/docs/identity-howto).

In certain AppEngine environments (so far Python, Java, Go) it seems you are able to use some already provided libraries to get more information about the user with Users API, however the nodejs page is disabled (here https://cloud.google.com/appengine/docs/standard/python/users/), there seems to be no indication of what should be done there. Any ideas?

If there is no straight forward way around it would I be able to have an app engine environment that also exposes for example the Python libraries for Users API so that I can wrap around them and use them in my nodejs app?

答:
The Users API isn't supported for Node.js. Instead, you can get the identity from the x-goog-iap-jwt-assertion header.

We don't currently have a code sample for Node.js, though this looks like one reasonable approach. (Disclaimer: I'm not a Node user, and don't know enough about Node JWT libraries to endorse any of them in particular.)

ContentLicense: CC BY-SA 4.0


问:
Get a single compare function to order both ASC and DESC using Array.sort()?
I need to order an array of objects by the property price.

Right now I have the following, which works as intended:

```<code>function orderByPriceASC(a,b) {
    return(
      a.price < b.price ? -1
      : a.price > b.price ? 1
        : 0
    );
  }

  function orderByPriceDESC(a,b) {
    return(
      a.price < b.price ? 1
      : a.price > b.price ? -1
        : 0
    );
  }

  function sortByPrice(order) {
    setProductList((prevState) => {
      const aux = Array.from(prevState);
      order === 'asc' ? aux.sort(orderByPriceASC) : aux.sort(orderByPriceDESC);
      return aux;
    });
  }
</code>```

But can is there a way that I can structure this so I can get a single compare function that works for both ASC and DESC order?

Something like:

```<code>function orderByPrice(a,b,order) {
    return(
      a.price < b.price ?
        order === 'asc' ? -1 : 1
      : a.price > b.price ? 1
        order === 'asc' ? 1 : -1
        : 0
    );
  }
</code>```

The problem is that I would have to send that extra parameter down to the Array.sort method which I don't think it's possible. Maybe with some wrapper function.

How can this be implemented?

答:
You can define the function and pass it to sort by binding it and sending a custom param like

let arr = [{price: 1},{price: 11},{price: 7},{price: 1},{price: 9},{price: 5},]
function orderByPrice(order, a,b) {

        if(a.price  b.price){
            if(order === 'asc') {
                return 1;
            }
            return -1
        }
        return 0;
      }

console.log(arr.sort(orderByPrice.bind(this, 'asc')))
console.log(arr.sort(orderByPrice.bind(this, 'desc')))```

Body:
I need to order an array of objects by the property price.

Right now I have the following, which works as intended:

function orderByPriceASC(a,b) {
    return(
      a.price  b.price ? 1
        : 0
    );
  }

  function orderByPriceDESC(a,b) {
    return(
      a.price  b.price ? -1
        : 0
    );
  }

  function sortByPrice(order) {
    setProductList((prevState) => {
      const aux = Array.from(prevState);
      order === 'asc' ? aux.sort(orderByPriceASC) : aux.sort(orderByPriceDESC);
      return aux;
    });
  }

But can is there a way that I can structure this so I can get a single compare function that works for both ASC and DESC order?

Something like:

function orderByPrice(a,b,order) {
    return(
      a.price  b.price ? 1
        order === 'asc' ? 1 : -1
        : 0
    );
  }

The problem is that I would have to send that extra parameter down to the Array.sort method which I don't think it's possible. Maybe with some wrapper function.

How can this be implemented?

Body:
You can define the function and pass it to sort by binding it and sending a custom param like

let arr = [{price: 1},{price: 11},{price: 7},{price: 1},{price: 9},{price: 5},]
function orderByPrice(order, a,b) {

        if(a.price < b.price) {
            if(order === 'asc') {
                return -1;
            }
            return 1;
        } else if(a.price > b.price){
            if(order === 'asc') {
                return 1;
            }
            return -1
        }
        return 0;
      }

console.log(arr.sort(orderByPrice.bind(this, 'asc')))
console.log(arr.sort(orderByPrice.bind(this, 'desc')))


问:
If a var in JavaScript is defined twice, which definition should the interpreter take?
I'm new to JavaScript and am trying to understand the concepts of hoisting and scope.

Case 1

var name;

function logName(num) {
  console.log(name, num);
}

logName(1);
name = "Auro";
logName(2);```
</div>
</div>
</p>

<p>and I have the following output in the console</p>

```Auro 1
Auro 2
```

<p>If I understand <code>hoisting</code> correctly, JS engine hoists the declaration of a variable first and then automatically assigns a value <code>undefined</code> to it. Only when it encounters the assignment (<code>=</code>) operator, does it actually assign the intended value to it.</p>

<p>If my understanding above is correct, then the first time the <code>logName</code> function was called, the variable <code>name</code> should have printed undefined, but it is printing the value.</p>

<p><strong>Case 2</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var name;

function logName(num) {
  console.log(name, num);
}

logName(1);
name = "Auro";
logName(2);
name = "Baner";</code>```

Output in the console:

```<code>Baner 1
Auro 2
</code>```

This confuses me even more. Here the first call to the function logName picked the later assignment to the variable and printed Baner, however, the second call picked the previous assignment, that is Auro.

What is going on here? What am I missing?

答:
In the global scope, name refers to window.name, that is the name property of the window - which in the examples you gave are sif1 and sif2 (possibly "Snippet IFrame 1/2").

Since window.name already exists, var name; in the global scope does nothing. The variable is already defined.

Until you overwrite it - and note that again you are setting the global window.name property. And, depending on browser settings, this can persist across reloads of the page (since you're naming the entire window). This explains why you see the value "stick".

Body:
I'm new to JavaScript and am trying to understand the concepts of hoisting and scope.

Case 1

var name;

function logName(num) {
  console.log(name, num);
}

logName(1);
name = "Auro";
logName(2);

and I have the following output in the console

Auro 1
Auro 2

If I understand hoisting correctly, JS engine hoists the declaration of a variable first and then automatically assigns a value undefined to it. Only when it encounters the assignment (=) operator, does it actually assign the intended value to it.

If my understanding above is correct, then the first time the logName function was called, the variable name should have printed undefined, but it is printing the value.

Case 2

var name;

function logName(num) {
  console.log(name, num);
}

logName(1);
name = "Auro";
logName(2);
name = "Baner";

Output in the console:

Baner 1
Auro 2

This confuses me even more. Here the first call to the function logName picked the later assignment to the variable and printed Baner, however, the second call picked the previous assignment, that is Auro.

What is going on here? What am I missing?


问:
Using negative integer range of int (4 bytes) as ids(-2.14 billion to 0) : Any downsides?
I am storing certain entities in my database with integer Ids of size 32 bits thus using the range of -2.14 billion to +2.14 billion.

I have given tried giving some meaning to my ids due to which my Ids, in the positive range, have finished up a bit quickly. I am looking forward to use the negative integer range of -2.14 billion to 0.

Wanted to know, if you could see any downsides of using negative integers as ids, though personally I don't see any downsides.

答: There is an old saying in database design that goes like this: "Intelligent keys are not".  You should never design for special meaning in an id when a descriptive attribute is more appropriate. </p>

ContentLicense: CC BY-SA 3.0


答:
You have to have the function return a function that accepts the direction as an argument, which is then passed into the inner function. I'm not a fan of flags in dynamically typed languages, but it would be something like this:

```<code>function orderByPrice(direction) { // either 'ASC' or 'DESC
  return function (a, b) {
    if (direction === 'DESC') {
      const temp = a;
      a = b
      b = temp;
    }
    return (
      a.price < b.price ? -1
        : a.price > b.price ? 1
          : 0
    );
  }
}
</code>```

Then implementation would be

```<code>  function sortByPrice(direction) {
    setProductList((prevState) => {
      return Array.from(prevState).sort(orderByPrice(direction));
    });
  }
</code>```

Title: Get a single compare function to order both ASC and DESC using Array.sort()?

Body:
You have to have the function return a function that accepts the direction as an argument, which is then passed into the inner function. I'm not a fan of flags in dynamically typed languages, but it would be something like this:

function orderByPrice(direction) { // either 'ASC' or 'DESC
  return function (a, b) {
    if (direction === 'DESC') {
      const temp = a;
      a = b
      b = temp;
    }
    return (
      a.price < b.price ? -1
        : a.price > b.price ? 1
          : 0
    );
  }
}

Then implementation would be

  function sortByPrice(direction) {
    setProductList((prevState) => {
      return Array.from(prevState).sort(orderByPrice(direction));
    });
  }


问:
Array of greater elements
I'd like to create a method that recieves an array and a value to compare. It should return the numbers which are greater than the value compared in the form of an array.

For instance, greaterThan([3, 4, 5, 6], 4]) should return [5, 6] and greaterThan([3, 4, 5, 6], 5]) should return [6].

Since the length of the result array is dynamic, I've incremented the size each time it finds a larger element.

```<code>static String greaterThan(int[] vectorCompare, int valueCompare)
{
    Arrays.sort(vectorCompare);         // make it faster

    int size = 0;

    int[] result = new int[size];

    for (int value : vectorCompare)
    {
        if (valueCompare < value)
        {
            size++;
        }
    }

    int[] resultCopy = Arrays.copyOf(result, size);

    // what to do next?

    return Arrays.toString(resultCopy);

}
</code>```

Any tips for me? I thought of using ArrayList but I'm kinda stuck.

答:
Sorting your input in the above method will actually make it slow. With normal array iteration and comparison your complexity will be O(n) while with sorting it would be O(nlogn). Instead you can try this. </p>

```<code>static String greaterThan(int[] vectorCompare, int valueCompare)
   {
      List<Integer> list = new ArrayList<>();
      for (int value : vectorCompare)
      {
         if (valueCompare < value)
         {
            list.add(value);
         }
      }
         return list.toString();
   }
</code>```

<p>By using Arraylist you would not be required to worry about the number of elements that are to be returned. </p>

Title: Array of greater elements

Body:
I'd like to create a method that recieves an array and a value to compare. It should return the numbers which are greater than the value compared in the form of an array.

For instance, greaterThan([3, 4, 5, 6], 4]) should return [5, 6] and greaterThan([3, 4, 5, 6], 5]) should return [6].

Since the length of the result array is dynamic, I've incremented the size each time it finds a larger element.

static String greaterThan(int[] vectorCompare, int valueCompare)
{
    Arrays.sort(vectorCompare);         // make it faster

    int size = 0;

    int[] result = new int[size];

    for (int value : vectorCompare)
    {
        if (valueCompare < value)
        {
            size++;
        }
    }

    int[] resultCopy = Arrays.copyOf(result, size);

    // what to do next?

    return Arrays.toString(resultCopy);

}

Any tips for me? I thought of using ArrayList but I'm kinda stuck.

Body:
Sorting your input in the above method will actually make it slow. With normal array iteration and comparison your complexity will be O(n) while with sorting it would be O(nlogn). Instead you can try this.

static String greaterThan(int[] vectorCompare, int valueCompare)
   {
      List<Integer> list = new ArrayList<>();
      for (int value : vectorCompare)
      {
         if (valueCompare < value)
         {
            list.add(value);
         }
      }
         return list.toString();
   }

By using Arraylist you would not be required to worry about the number of elements that are to be returned.


问:
Scala - "if(true) Some(1)" without having to type "else None"
In scala, if you have an Option, you can get another Option by doing oldOption.map(_.something). What I want to do is take a boolean and do the same thing. In other words, I want shorthand for the following:

```<code>if(someCondition)
  Some(data)
else
  None
</code>```

Is there an idiomatic way to get an Option out of a Boolean like this without having to do "else None"?

答:
Scala 2.13 has Option.when(someCondition)(dataExpression) and its corollary Option.unless

https://github.com/scala/scala/commit/44d08f68eb88c83a803eda240b6fdb18450aa8af

Body:
In scala, if you have an Option, you can get another Option by doing oldOption.map(_.something). What I want to do is take a boolean and do the same thing. In other words, I want shorthand for the following:

if(someCondition)
  Some(data)
else
  None

Is there an idiomatic way to get an Option out of a Boolean like this without having to do "else None"?


问:
What is the SQL/MP equivalent of CURRENT_DATE?
SQL/MP is an SQL dialect used on proprietary HP NonStop SQL database systems which go back to the 1980ies... (Who has ever worked on a system that is as old as they are, huh? :))

SQL/MP is only somewhat ANSI compliant, for example CURRENT_DATE does not exist. I have however a hard time figuring out what functions do exist that can help me to get the current date in my queries.

Can anyone help me with this dinosaur of an SQL language?

答:
You can use this:

```<code>CURRENT YEAR TO DAY
</code>```

CURRENT is a function that returns the current local date, time, or both. You can find the options of parameters in the HPE NonStopSQL/MP Reference Manual it´s most recent documentation that I know.

Body:
You can use this:

CURRENT YEAR TO DAY

CURRENT is a function that returns the current local date, time, or both. You can find the options of parameters in the HPE NonStopSQL/MP Reference Manual it´s most recent documentation that I know.


问:
How to capture output of a command run in python3 in python2?
I have a file which connects a database and fetches the result. Now the file must be ran using python 3 and my project uses python 2.7. So I run the file as a command line using subprocess module. Here is how I call the file.

```<code>import subprocess
import ast

def execute_python3(param):
    param = param.replace("\\", "")
    param = "\"" + param + "\""

    cmd = "python3 " + "get_db_result.py" + " " + param

    result = subprocess.check_output(cmd, shell=True)
    return ast.literal_eval(result)

execute_python3(sql_query)
</code>```

Here in the command, I am passing sql query to the get_db_result file.

The get_db_result.py file looks something like this

```<code>import sys
def get_result():
    param = sys.argv[1]
    '''
    Logic to get result from db
    '''
    result = db_output
    print(result)

if __name__ == "__main__":
    get_result()
</code>```

Now the issue is when I fetch the output from db, I have to do a print for the output to be captured by the subprocess module. This makes it difficult to parse the output to be used by program for further work. For example, when I receive an output like this

```<code>"[(u'Delhi', 20199330), (u'Mumbai', 134869470), (u'Kolkata', 6678446)]"
</code>```

This is a string list of tuples which can be converted to list of tuples by doing something like ast.literal_eval(result)

But sometimes I get output like this

```<code>"[(datetime.date(2019, 5, 27), 228.168093587), (datetime.date(2019, 5, 28), 228.834493641)]"
</code>```

Here ast doesn't understand datetime. Even json.loads() doesn't work on this.

How can I capture the output from a file without having to use print and simply return it back to subprocess as it is. Is it even possible?

答:
You need to serialize and deserialize the data on both ends. Simplest solution would be to use Python's pickle module and hope the types that are serialized on the Python 3 end, are similar enough to those on the deserializing Python 2 end.  You need to specify the used protocol on the sending end to a version understood by the receiving end:

Receiver with safer call of subprocess (no shell process in between):

```<code>#!/usr/bin/env python
import pickle
import subprocess

def execute_python3(param):
    result = subprocess.check_output(['python3', 'get_db_result.py', param])
    return pickle.loads(result)

def main():
    execute_python3(sql_query)

if __name__ == '__main__':
    main()
</code>```

Sender, explicitly choosing a pickle protocol still understood by Python 2:

```<code>#!/usr/bin/env python3
import sys
import pickle

def get_result():
    param = sys.argv[1]
    '''
    Logic to get result from db
    '''
    result = db_output
    pickle.dump(result, sys.stdout.buffer, protocol=2)

if __name__ == '__main__':
    get_result()
</code>```

If this doesn't work because of differences in the (de)serialized objects between Python 2 and 3, you have to fall back to explicitly (de)serialize the data, for example in JSON, as suggested by a comment from Jay.

Body:
I have a file which connects a database and fetches the result. Now the file must be ran using python 3 and my project uses python 2.7. So I run the file as a command line using subprocess module. Here is how I call the file.

import subprocess
import ast

def execute_python3(param):
    param = param.replace("\\", "")
    param = "\"" + param + "\""

    cmd = "python3 " + "get_db_result.py" + " " + param

    result = subprocess.check_output(cmd, shell=True)
    return ast.literal_eval(result)

execute_python3(sql_query)

Here in the command, I am passing sql query to the get_db_result file.

The get_db_result.py file looks something like this

import sys
def get_result():
    param = sys.argv[1]
    '''
    Logic to get result from db
    '''
    result = db_output
    print(result)

if __name__ == "__main__":
    get_result()

Now the issue is when I fetch the output from db, I have to do a print for the output to be captured by the subprocess module. This makes it difficult to parse the output to be used by program for further work. For example, when I receive an output like this

"[(u'Delhi', 20199330), (u'Mumbai', 134869470), (u'Kolkata', 6678446)]"

This is a string list of tuples which can be converted to list of tuples by doing something like ast.literal_eval(result)

But sometimes I get output like this

"[(datetime.date(2019, 5, 27), 228.168093587), (datetime.date(2019, 5, 28), 228.834493641)]"

Here ast doesn't understand datetime. Even json.loads() doesn't work on this.

How can I capture the output from a file without having to use print and simply return it back to subprocess as it is. Is it even possible?

Body:
You need to serialize and deserialize the data on both ends. Simplest solution would be to use Python's pickle module and hope the types that are serialized on the Python 3 end, are similar enough to those on the deserializing Python 2 end.  You need to specify the used protocol on the sending end to a version understood by the receiving end:

Receiver with safer call of subprocess (no shell process in between):

#!/usr/bin/env python
import pickle
import subprocess

def execute_python3(param):
    result = subprocess.check_output(['python3', 'get_db_result.py', param])
    return pickle.loads(result)

def main():
    execute_python3(sql_query)

if __name__ == '__main__':
    main()

Sender, explicitly choosing a pickle protocol still understood by Python 2:

#!/usr/bin/env python3
import sys
import pickle

def get_result():
    param = sys.argv[1]
    '''
    Logic to get result from db
    '''
    result = db_output
    pickle.dump(result, sys.stdout.buffer, protocol=2)

if __name__ == '__main__':
    get_result()

If this doesn't work because of differences in the (de)serialized objects between Python 2 and 3, you have to fall back to explicitly (de)serialize the data, for example in JSON, as suggested by a comment from Jay.


问:
Laravel - blade check if object has relationship
In my controller I'm getting a complex query that filter data depending on input provided by the user:

```<code>if (conditionB) {
   $query = Model::with('relationA', 'relationB');
} else {
   $query = Model::with('relationA', 'relationC');
}

// checking filters and apply conditions...

$query = $query->get();
</code>```

Now in my blade file I'm looping result and I want to display "eager load" relationship B or C:

```<code>@if (count($myObject->relationB)) {
    <span>{{ $myObject->relationB->someField }}</span>
@else
    <span>{{ $myObject->relationC->someField }}</span>
@endif
</code>```

It works, but if my $myObject has relationC and not relationB, then
during the verification of the if condition the relationship is loaded.

How I can avoid loading that relationship??

when I do: {{ $myObject }}

It gives me:

```<code>   // has relationB
   "field1": value1,
   "field2": value2,
    ....
   "fieldx": valuex,
   "relation_b":[
      {
         "relationBfield1": relationBvalue1,
         "relationBfield2": relationBvalue2,
      },
      { ... }

   // doesn't have relationB
   "field1": value1,
   "field2": value2,
    ....
   "fieldx": valuex
</code>```

I tried access relation_b (note that json is changing name by replacing UpperCase for _<LowerCase>) but it returns NULL, but if I access relationB it shows data:

```<code>myObject->relation_b; // NULL
myObject->relation_b[0]; // NULL
myObject->relationB; // works, but if item has RelationC it will "eager load" relationship B just to check that if condition
</code>```

I was trying different options, and I don't see where I make mistake, I also tried to create a public function in my model:

```<code>{{ $myObject->checkRelation() }}

public function checkRelation()
{
    if (count($this->relationB) > 0) {
        // code...
</code>```

But I always end up with the same problem, when object item doesn't have relationB it will load it to check that if condition.

How can I avoid it? Or there is another way to check with relation has my object item without executing an additional query?

答:
If you want to check if a relationship has been loaded you can use the relationLoaded() method on the model:

```<code>@if ($myObject->relationLoaded('relationB')) {
    <span>{{ $myObject->relationB->someField }}</span>
@else
    <span>{{ $myObject->relationC->someField }}</span>
@endif
</code>```

Body:
In my controller I'm getting a complex query that filter data depending on input provided by the user:

if (conditionB) {
   $query = Model::with('relationA', 'relationB');
} else {
   $query = Model::with('relationA', 'relationC');
}

// checking filters and apply conditions...

$query = $query->get();

Now in my blade file I'm looping result and I want to display "eager load" relationship B or C:

@if (count($myObject->relationB)) {
    {{ $myObject->relationB->someField }}
@else
    {{ $myObject->relationC->someField }}
@endif

It works, but if my $myObject has relationC and not relationB, then
during the verification of the if condition the relationship is loaded.

How I can avoid loading that relationship??

when I do: {{ $myObject }}

It gives me:

   // has relationB
   "field1": value1,
   "field2": value2,
    ....
   "fieldx": valuex,
   "relation_b":[
      {
         "relationBfield1": relationBvalue1,
         "relationBfield2": relationBvalue2,
      },
      { ... }

   // doesn't have relationB
   "field1": value1,
   "field2": value2,
    ....
   "fieldx": valuex

I tried access relation_b (note that json is changing name by replacing UpperCase for _<LowerCase>) but it returns NULL, but if I access relationB it shows data:

myObject->relation_b; // NULL
myObject->relation_b[0]; // NULL
myObject->relationB; // works, but if item has RelationC it will "eager load" relationship B just to check that if condition

I was trying different options, and I don't see where I make mistake, I also tried to create a public function in my model:

{{ $myObject->checkRelation() }}

public function checkRelation()
{
    if (count($this->relationB) > 0) {
        // code...

But I always end up with the same problem, when object item doesn't have relationB it will load it to check that if condition.

How can I avoid it? Or there is another way to check with relation has my object item without executing an additional query?

Body:
If you want to check if a relationship has been loaded you can use the relationLoaded() method on the model:

@if ($myObject->relationLoaded('relationB')) {
    <span>{{ $myObject->relationB->someField }}</span>
@else
    <span>{{ $myObject->relationC->someField }}</span>
@endif


问:
HTML insert "tab"
I would like the text (see PIC2) that every text begins in the same place, so to speak, provided with a tab. In Word that's just a tab. But how does that work in HTML or CSS? Can someone help me and tell me how I can make PIC1 from PIC2?

PIC1:

PIC2:

Code:

```<code><p><strong>Öffnungzeiten:</strong>
        <p>Montag Geschlossen<br/>
        Dienstag 09:00 - 18:00<br/>
        Mittwoch Geschlossen<br/>
        Donnerstag 09:00 - 18:00<br/>
        Freitag 09:00 - 18:00<br/>
        Samstag 09:00 - 13:00<br/>
        Sonntag Geschlossen</p>
</code>```

答:
You can achieve what you need with a combination of pre, the tab character (&#9) and setting the tab-size to whatever you want in CSS:

pre {tab-size: 8;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>```
  Montag&#9 Geschlossen

  Dienstag&#9 09:00 - 18:00

  Mittwoch&#9 Geschlossen

  Donnerstag&#9 09:00 - 18:00

  Freitag&#9 09:00 - 18:00

  Samstag&#9 09:00 - 13:00

  Sonntag&#9 Geschlossen
```</code>```

(tab-size isn't fully supported yet but the browsers that are lagging with this should render this ok using their default tab-size)

Title: HTML insert "tab"

Body:
I would like the text (see PIC2) that every text begins in the same place, so to speak, provided with a tab. In Word that's just a tab. But how does that work in HTML or CSS? Can someone help me and tell me how I can make PIC1 from PIC2?

PIC1:

PIC2:

Code:

Öffnungzeiten:

Montag Geschlossen

        Dienstag 09:00 - 18:00

        Mittwoch Geschlossen

        Donnerstag 09:00 - 18:00

        Freitag 09:00 - 18:00

        Samstag 09:00 - 13:00

        Sonntag Geschlossen

Body:
You can achieve what you need with a combination of pre, the tab character (&#9) and setting the tab-size to whatever you want in CSS:

pre {tab-size: 8;}

<pre>
  Montag&#9 Geschlossen<br/>
  Dienstag&#9 09:00 - 18:00<br/>
  Mittwoch&#9 Geschlossen<br/>
  Donnerstag&#9 09:00 - 18:00<br/>
  Freitag&#9 09:00 - 18:00<br/>
  Samstag&#9 09:00 - 13:00<br/>
  Sonntag&#9 Geschlossen
</pre>

(tab-size isn't fully supported yet but the browsers that are lagging with this should render this ok using their default tab-size)


答:
It can be done as below:</p>

```<code>    List<Integer> list = new ArrayList<>();
    list.add(2);
    list.add(1);
    list.add(4);
    list.add(6);
    list.add(7);

    int valToCompare = 4;
    List<Integer> result = find(list, valToCompare);

    private static List<Integer> find(List<Integer> list, int val) {
        return list.stream().filter(v -> v > val).collect(Collectors.toList());
    }
</code>```

Title: Array of greater elements

Body:
It can be done as below:

    List<Integer> list = new ArrayList<>();
    list.add(2);
    list.add(1);
    list.add(4);
    list.add(6);
    list.add(7);

    int valToCompare = 4;
    List<Integer> result = find(list, valToCompare);

    private static List<Integer> find(List<Integer> list, int val) {
        return list.stream().filter(v -> v > val).collect(Collectors.toList());
    }


问:
I accidentally changed the IP adapter of Azure windows vm, which made it impossible for me to connect to the server remotely
I accidentally changed the  IP adapter of Azure windows vm, which made it impossible for me to connect to the server remotely. Then I restarted the virtual machine several times on the manage console, but it didn't work. I'm going to crash.

How do I regain access to Virtual Machine?

答:
You need to reset the NIC configuration.  You can do that by changing the IP address from that Azure Portal.  See article below;

https://learn.microsoft.com/en-us/azure/virtual-machines/troubleshooting/reset-network-interface


问:
How to filter out item based on properties?
i wanted to refactor code use filter instead of lodash _forEach , Below filter code is not returning expected response. any idea what is implemented wrong here ?

main.js

const response = [];
const data = [{
    "isBrand": true,
    "drugName": "Lipitor",
    "specialtyPrice": {}
  },
  {
    "isBrand": false,
    "drugName": "Atorvastatin Calcium",
    "drugStrength": "80mg",
    "drugForm": "Tablet",
    "mailPrice": {
      "totalQuantity": 90,
      "rejectMessage": [{
        "settlementCode": "99",
        "settlementDesc": "Sorry, the system is temporarily:Lo sentimos,Intente(Código de error 85)"
      }]
    },
    "retailPrice": {
      "totalQuantity": 30,
      "rejectMessage": [{
        "settlementCode": "99",
        "settlementDesc": "Sorry, the system is temporarily:Lo sentimos,Intente(Código de error 85)"
      }]
    },
    "specialtyPrice": {}
  }
];
_.forEach(data, function(drug) {
  if (drug.retailPrice !== undefined || drug.mailPrice !== undefined) {
    response.push(drug);
  }
});

const filterItems = data.filter(item => item.retailPrice && item.mailPrice)

console.log(filterItems);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script></code>```

expected result

```<code>[{
            "isBrand": false,
            "drugName": "Atorvastatin Calcium",
            "drugStrength": "80mg",
            "drugForm": "Tablet",
            "mailPrice": {
                "totalQuantity": 90,
                "rejectMessage": [{
                    "settlementCode": "99",
                    "settlementDesc": "Sorry, the system is temporarily:Lo sentimos,Intente(Código de error 85)"
                }]
            },
            "retailPrice": {
                "totalQuantity": 30,
                "rejectMessage": [{
                    "settlementCode": "99",
                    "settlementDesc": "Sorry, the system is temporarily:Lo sentimos,Intente(Código de error 85)"
                }]
            },
            "specialtyPrice": {}
        }
    ];
</code>```

答:
You can simply do Array.forEach like this:

```<code>data.forEach(d => (d.retailPrice || d.mailPrice) ? response.push(d) : null)
</code>```

So it would looks like this:

const response = [];
const data = [{
    "isBrand": true,
    "drugName": "Lipitor",
    "specialtyPrice": {}
  },
  {
    "isBrand": false,
    "drugName": "Atorvastatin Calcium",
    "drugStrength": "80mg",
    "drugForm": "Tablet",
    "mailPrice": {
      "totalQuantity": 90,
      "rejectMessage": [{
        "settlementCode": "99",
        "settlementDesc": "Sorry, the system is temporarily:Lo sentimos,Intente(Código de error 85)"
      }]
    },
    "retailPrice": {
      "totalQuantity": 30,
      "rejectMessage": [{
        "settlementCode": "99",
        "settlementDesc": "Sorry, the system is temporarily:Lo sentimos,Intente(Código de error 85)"
      }]
    },
    "specialtyPrice": {}
  }
];

data.forEach(d => (d.retailPrice || d.mailPrice) ? response.push(d) : null)

const filterItems = data.filter(item => item.retailPrice && item.mailPrice)

console.log(filterItems);```

Body:
i wanted to refactor code use filter instead of lodash _forEach , Below filter code is not returning expected response. any idea what is implemented wrong here ?

main.js

const response = [];
const data = [{
    "isBrand": true,
    "drugName": "Lipitor",
    "specialtyPrice": {}
  },
  {
    "isBrand": false,
    "drugName": "Atorvastatin Calcium",
    "drugStrength": "80mg",
    "drugForm": "Tablet",
    "mailPrice": {
      "totalQuantity": 90,
      "rejectMessage": [{
        "settlementCode": "99",
        "settlementDesc": "Sorry, the system is temporarily:Lo sentimos,Intente(Código de error 85)"
      }]
    },
    "retailPrice": {
      "totalQuantity": 30,
      "rejectMessage": [{
        "settlementCode": "99",
        "settlementDesc": "Sorry, the system is temporarily:Lo sentimos,Intente(Código de error 85)"
      }]
    },
    "specialtyPrice": {}
  }
];
_.forEach(data, function(drug) {
  if (drug.retailPrice !== undefined || drug.mailPrice !== undefined) {
    response.push(drug);
  }
});

const filterItems = data.filter(item => item.retailPrice && item.mailPrice)

console.log(filterItems);

expected result

[{
            "isBrand": false,
            "drugName": "Atorvastatin Calcium",
            "drugStrength": "80mg",
            "drugForm": "Tablet",
            "mailPrice": {
                "totalQuantity": 90,
                "rejectMessage": [{
                    "settlementCode": "99",
                    "settlementDesc": "Sorry, the system is temporarily:Lo sentimos,Intente(Código de error 85)"
                }]
            },
            "retailPrice": {
                "totalQuantity": 30,
                "rejectMessage": [{
                    "settlementCode": "99",
                    "settlementDesc": "Sorry, the system is temporarily:Lo sentimos,Intente(Código de error 85)"
                }]
            },
            "specialtyPrice": {}
        }
    ];

Body:
You can simply do Array.forEach like this:

data.forEach(d => (d.retailPrice || d.mailPrice) ? response.push(d) : null)

So it would looks like this:

const response = [];
const data = [{
    "isBrand": true,
    "drugName": "Lipitor",
    "specialtyPrice": {}
  },
  {
    "isBrand": false,
    "drugName": "Atorvastatin Calcium",
    "drugStrength": "80mg",
    "drugForm": "Tablet",
    "mailPrice": {
      "totalQuantity": 90,
      "rejectMessage": [{
        "settlementCode": "99",
        "settlementDesc": "Sorry, the system is temporarily:Lo sentimos,Intente(Código de error 85)"
      }]
    },
    "retailPrice": {
      "totalQuantity": 30,
      "rejectMessage": [{
        "settlementCode": "99",
        "settlementDesc": "Sorry, the system is temporarily:Lo sentimos,Intente(Código de error 85)"
      }]
    },
    "specialtyPrice": {}
  }
];

data.forEach(d => (d.retailPrice || d.mailPrice) ? response.push(d) : null)

const filterItems = data.filter(item => item.retailPrice && item.mailPrice)

console.log(filterItems);


问:
MySQL: Login Failed for User
I have tried to connect to my SQL database being hosted on Plesk with InterServer using C# ASP.NET MVC. Despite numerous efforts, it never seems to want to connect. What am I doing wrong?

I've tried changing the connection string numerous times. Plesk and InterServer support ask me to deploy my code and access the database via localhost. Due to this, I have tried the following connection strings:

```<code>"SERVER=localhost;DATABASE=databasename;UID=username;PASSWORD=password;"
"SERVER=localhost:3306;DATABASE=databasename;UID=username;PASSWORD=password;"
"SERVER=localhost;PORT=3306;DATABASE=databasename;UID=username;PASSWORD=password;"
"SERVER=(Local);DATABASE=databasename;UID=username;PASSWORD=password;"
</code>```

I have tried interchanging "Server" with "Data Source", among other keyword changes. I have also tried setting Trusted_Connection to both true and false, and setting Integrated Security to both true and false. It seems when I try to set them to true, the application tries to log in using my Plesk username rather than the User ID I specified in the connection string. This user has no association to the database nor am I able to associate it in the Plesk control panel to my knowledge.

I have also tried using the default connection string in the Plesk Control Panel alongside a couple of modifications to said connection strings, one of which even provided by InterServer support as they suspect the error is in my connection strings. Here are those strings:

```<code>"data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
"Data Source=(IPAddressWasHere)\MSSQLSERVER2017;Initial Catalog=nlstatic;Persist Security Info=True;User ID=username;Password=password"
"Data Source=.\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\db.mdf;Initial Catalog=Portal.Web;Integrated Security=True"
"Data Source=.\SQLExpress;Initial Catalog=localhost;Integrated Security=True"
</code>```

I have also tried changing the proverName from System.Data.SqlClient to MySql.Data.SqlClient, but this seemed to not change the error message. Personally, I'm at the point where I suspect that this issue isn't with a connection string setup, but instead with the configuration of the MySQL database or its settings.

Despite trying to ask InterServer support for assistance regarding this, they refuse to look into the matter. Instead, they once asked me to "properly set up my VPS" (I don't have a VPS with them at all) and tried to convince me I was trying to connect via ODBC when I clearly stated it was through connection strings.

In case it's relevant, here's my C# code on how I'm using the connection string, though I don't feel it's the cause personally:

        public List<string> GetEffectByID(int id)
        {
            List<string> results = new List<string>();
            SqlConnection conn;
            string connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

            conn = new SqlConnection(connectionString);

            try
            {
                using (SqlCommand command = new SqlCommand("getFxById", conn) { CommandType = CommandType.StoredProcedure })
                {
                    conn.Open();
                    using (SqlDataReader dr = command.ExecuteReader())
                    {
                        while (dr.Read())
                        {
                            results.Add(dr["myColumn"].ToString());
                        }
                    }
                    conn.Close();
                    return results;
                }
            } catch(Exception e)
            {
                if(conn.State == ConnectionState.Open) conn.Close();
                return new List<string>() { e.ToString() };
            }
        }
```

This stored procedure definitely exists in my database, and it works in phpMyAdmin

Is there something that I've missed throughout this entire process? I expect it to be able to connect and run the stored procedure when my View calls the function. Despite this, using the methods provided by Plesk/InterServer, it claims that the server was not found/accessible. When I try to use the connection strings I've created (Without using Integrated Security), it provides this error message instead:

System.Data.SqlClient.SqlException (0x80131904): Login failed for user 'Shizuku'. at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, DbConnectionPool pool, String accessToken, Boolean applyTransientFaultHandling, SqlAuthenticationProviderManager sqlAuthProviderManager) at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection) at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions) at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions) at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource1 retry) at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource1 retry) at System.Data.SqlClient.SqlConnection.Open() at (Code file was here) ClientConnectionId:953f6859-a48b-4f58-a0b8-bef0702911a3 Error Number:18456,State:1,Class:14

I feel as if that error means I'm closer to solving the issue currently, but I'm not entirely sure. Is there anything I haven't tried or any error I've made that I just simply missed?

答:
I found out the error: My host, InterServer, was rejecting the connection, claiming that a "localhost connection was a remote connection". After several hours of back and forth with support, I finally requested a refund.

After this, the support agent finally started trying to get it to work desperately, scrambling for a solution by changing my Web.config as he was convinced it was my issue, not his. To no avail, he made a test domain and copied my files/database. Of course, he didn't have my C# code and this led to an "Object not set to a reference" error for an object creation statement (using the new keyword). As a last resort, he created a PHP file that literally read "Connection succeeded" and had no actual code in it, then sent me a link to it claiming that "the error was not on the server's side, see?"

The solution to my problem was to not buy shared hosting from InterServer, and potentially not even to go with InterServer as a whole. Their support is awful, and they employ these kinds of shady tactics to keep customers troubleshooting past the 30 day money-back period. Buyer beware.

Title: MySQL: Login Failed for User

Body:
I have tried to connect to my SQL database being hosted on Plesk with InterServer using C# ASP.NET MVC. Despite numerous efforts, it never seems to want to connect. What am I doing wrong?

I've tried changing the connection string numerous times. Plesk and InterServer support ask me to deploy my code and access the database via localhost. Due to this, I have tried the following connection strings:

"SERVER=localhost;DATABASE=databasename;UID=username;PASSWORD=password;"
"SERVER=localhost:3306;DATABASE=databasename;UID=username;PASSWORD=password;"
"SERVER=localhost;PORT=3306;DATABASE=databasename;UID=username;PASSWORD=password;"
"SERVER=(Local);DATABASE=databasename;UID=username;PASSWORD=password;"

I have tried interchanging "Server" with "Data Source", among other keyword changes. I have also tried setting Trusted_Connection to both true and false, and setting Integrated Security to both true and false. It seems when I try to set them to true, the application tries to log in using my Plesk username rather than the User ID I specified in the connection string. This user has no association to the database nor am I able to associate it in the Plesk control panel to my knowledge.

I have also tried using the default connection string in the Plesk Control Panel alongside a couple of modifications to said connection strings, one of which even provided by InterServer support as they suspect the error is in my connection strings. Here are those strings:

"data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
"Data Source=(IPAddressWasHere)\MSSQLSERVER2017;Initial Catalog=nlstatic;Persist Security Info=True;User ID=username;Password=password"
"Data Source=.\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\db.mdf;Initial Catalog=Portal.Web;Integrated Security=True"
"Data Source=.\SQLExpress;Initial Catalog=localhost;Integrated Security=True"

I have also tried changing the proverName from System.Data.SqlClient to MySql.Data.SqlClient, but this seemed to not change the error message. Personally, I'm at the point where I suspect that this issue isn't with a connection string setup, but instead with the configuration of the MySQL database or its settings.

Despite trying to ask InterServer support for assistance regarding this, they refuse to look into the matter. Instead, they once asked me to "properly set up my VPS" (I don't have a VPS with them at all) and tried to convince me I was trying to connect via ODBC when I clearly stated it was through connection strings.

In case it's relevant, here's my C# code on how I'm using the connection string, though I don't feel it's the cause personally:

        public List<string> GetEffectByID(int id)
        {
            List<string> results = new List<string>();
            SqlConnection conn;
            string connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

            conn = new SqlConnection(connectionString);

            try
            {
                using (SqlCommand command = new SqlCommand("getFxById", conn) { CommandType = CommandType.StoredProcedure })
                {
                    conn.Open();
                    using (SqlDataReader dr = command.ExecuteReader())
                    {
                        while (dr.Read())
                        {
                            results.Add(dr["myColumn"].ToString());
                        }
                    }
                    conn.Close();
                    return results;
                }
            } catch(Exception e)
            {
                if(conn.State == ConnectionState.Open) conn.Close();
                return new List<string>() { e.ToString() };
            }
        }

This stored procedure definitely exists in my database, and it works in phpMyAdmin

Is there something that I've missed throughout this entire process? I expect it to be able to connect and run the stored procedure when my View calls the function. Despite this, using the methods provided by Plesk/InterServer, it claims that the server was not found/accessible. When I try to use the connection strings I've created (Without using Integrated Security), it provides this error message instead:

System.Data.SqlClient.SqlException (0x80131904): Login failed for user 'Shizuku'. at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, DbConnectionPool pool, String accessToken, Boolean applyTransientFaultHandling, SqlAuthenticationProviderManager sqlAuthProviderManager) at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection) at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions) at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions) at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource1 retry) at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource1 retry) at System.Data.SqlClient.SqlConnection.Open() at (Code file was here) ClientConnectionId:953f6859-a48b-4f58-a0b8-bef0702911a3 Error Number:18456,State:1,Class:14

I feel as if that error means I'm closer to solving the issue currently, but I'm not entirely sure. Is there anything I haven't tried or any error I've made that I just simply missed?


问:
Audit.Net: add customfields
I am new to the use of audit.net.
I need to audit a series of custom values from the parameters received in the action method as follows.

```<code>[AuditField("User","reqLogin.User")]
[AuditCustom(EventTypeName =  "AccesoAction")]
public async Task<IActionResult> Acceso(LoginRequest reqLogin)
{
     ...
}
</code>```

I have to create a CustomField with FieldName "User" and value, the value of the User attribute of parameter reqLogin (reqLogin.User).

I'm extending the AuditAttribute class, to overwrite the OnActionExecutionAsync method and add the CustomField.

```<code>public class AuditCustomAttribute : AuditAttribute
{
  public override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
  {
      lock (context.ActionDescriptor.Parameters)
      {
        foreach (AuditFieldAttribute apa in context.ActionDescriptor.Parameters.Cast<ControllerParameterDescriptor>().First().ParameterInfo.Member.GetCustomAttributes<AuditFieldAttribute>())
    {
           // create CustomField and add to context
    }
}
 return base.OnActionExecutionAsync(context, next);
}
}
</code>```

Finally, in my custom AuditDataProvider class, I would audit the customFields that arrived in the auditevent field   of method:

```<code>  public override object InsertEvent(AuditEvent auditEvent)
</code>```

How would it be possible?
Thanks

答:
It's not very clear what are you asking, but I guess you're using the Audit.MVC extension.

Why do you need to create a CustomField with information you already have on the ActionParameters?

Also I don't think you need to subclass the AuditAttribute being that there is already a CustomAction mechanism you can use, for example:

```<code>Audit.Core.Configuration.AddOnCreatedAction(scope =>
{
    var action = scope.GetMvcAuditAction();
    var login = action.ActionParameters.FirstOrDefault(p => p.Key == "reqLogin").Value as LoginRequest;
    scope.SetCustomField("User", login.User);
});
</code>```

Title: Audit.Net: add customfields

Body:
I am new to the use of audit.net.
I need to audit a series of custom values from the parameters received in the action method as follows.

[AuditField("User","reqLogin.User")]
[AuditCustom(EventTypeName =  "AccesoAction")]
public async Task<IActionResult> Acceso(LoginRequest reqLogin)
{
     ...
}

I have to create a CustomField with FieldName "User" and value, the value of the User attribute of parameter reqLogin (reqLogin.User).

I'm extending the AuditAttribute class, to overwrite the OnActionExecutionAsync method and add the CustomField.

public class AuditCustomAttribute : AuditAttribute
{
  public override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
  {
      lock (context.ActionDescriptor.Parameters)
      {
        foreach (AuditFieldAttribute apa in context.ActionDescriptor.Parameters.Cast<ControllerParameterDescriptor>().First().ParameterInfo.Member.GetCustomAttributes<AuditFieldAttribute>())
    {
           // create CustomField and add to context
    }
}
 return base.OnActionExecutionAsync(context, next);
}
}

Finally, in my custom AuditDataProvider class, I would audit the customFields that arrived in the auditevent field   of method:

  public override object InsertEvent(AuditEvent auditEvent)

How would it be possible?
Thanks

Body:
It's not very clear what are you asking, but I guess you're using the Audit.MVC extension.

Why do you need to create a CustomField with information you already have on the ActionParameters?

Also I don't think you need to subclass the AuditAttribute being that there is already a CustomAction mechanism you can use, for example:

Audit.Core.Configuration.AddOnCreatedAction(scope =>
{
    var action = scope.GetMvcAuditAction();
    var login = action.ActionParameters.FirstOrDefault(p => p.Key == "reqLogin").Value as LoginRequest;
    scope.SetCustomField("User", login.User);
});


问:
Is there a way to skip error "filename is not found" and move to the next file
Is there a way to skip error "filename is not found" and move to the next file?

```<code>Sub CopyDataAndMoveDown()

Application.ScreenUpdating = False

Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws As Worksheet: Set ws = wb.ActiveSheet
Dim rngToCopy As Range, rngToPaste As Range
Dim x As Long
Dim breakdown1
Dim breakdown As Worksheet: Set breakdown = wb.ActiveSheet

For x = 4 To 504 Step 6

    With wb.Sheets("Sheet1")
        breakdown1 = breakdown.Cells(9, x - 2)
    End With

    If IsEmpty(breakdown1) Then
        Call MoveBelow
    Else

        With wb.Sheets("Sheet1")
            Set rngToCopy = .Range(.Cells(4, x - 2), .Cells(24, x + 3))
            Debug.Print rngToCopy.Address
        End With

        With wb.Sheets("Sheet2")
            Set rngToPaste = .Range(.Cells(4, x - 2), .Cells(rngToCopy.Rows.Count + 3, x + 3))
            Debug.Print rngToPaste.Address
        End With

        rngToPaste = rngToCopy.Value
    End If

Next x

Application.ScreenUpdating = True
MsgBox "Valmis."
End Sub

Sub MoveBelow ()

Application.ScreenUpdating = False

Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws As Worksheet: Set ws = wb.ActiveSheet
Dim rngToCopy As Range, rngToPaste As Range
Dim x As Long
Dim breakdown1
Dim breakdown As Worksheet: Set breakdown = wb.ActiveSheet

For x = 4 To 504 Step 6

    With wb.Sheets("Sheet1")
        breakdown1 = breakdown.Cells(9, x - 2)
    End With

    If IsEmpty(breakdown1) Then
        ' At this point when the macro meet again a empty cell
        ' it should keep moving from the same counted X
        ' but start the paste operation from 24 rows below.
    Else

        With wb.Sheets("Sheet1")
            Set rngToCopy = .Range(.Cells(4, x - 2), .Cells(24, x + 3))
            Debug.Print rngToCopy.Address
        End With

        With wb.Sheets("Sheet2")
            Set rngToPaste = .Range(.Cells(28, x - 2), .Cells(rngToCopy.Rows.Count + 3, x + 3))
            Debug.Print rngToPaste.Address
        End With

        rngToPaste = rngToCopy.Value
    End If

Next x

Application.ScreenUpdating = True
MsgBox "Valmis."
End Sub
</code>```

So when the macro is copying / pasting data from Sheet 1 to Sheet 2 and meets an empty cell it should keep going, copying next available data, but paste it 24 rows below.

--------Below the old question.

I have a VBA which is opening and closing file for that INDEX function get data. My problem is that. VBA is getting the filename from reference cell which contain the full path. But some of the reference cells are blanks/zeros and then the running VBA stops and give me error "filename is not found". Is there a way to skip that and move to next step?

```<code>Sub HaeReseptiTiedot()

Dim myfile As String
Dim myfile1 As String
Dim myfile2 As String
Dim myfile3 As String
Dim myfile4 As String
Dim myfile5 As String
Dim myfile6 As String
Dim myfile7 As String
Dim myfile8 As String
Dim myfile9 As String

myfile = Cells(19, 4).Value
myfile1 = Cells(19, 9).Value
myfile2 = Cells(19, 14).Value
myfile3 = Cells(19, 19).Value
myfile4 = Cells(19, 24).Value
myfile5 = Cells(19, 29).Value
myfile6 = Cells(19, 34).Value
myfile7 = Cells(19, 39).Value
myfile8 = Cells(19, 44).Value
myfile9 = Cells(19, 49).Value

Application.ScreenUpdating = False

Workbooks.Open Filename:=myfile, UpdateLinks:=0
ActiveWorkbook.Close False
Sheets("Aputaulukko 2").Select
Range("D16:G30").Select
Selection.Copy
Sheets("Aputaulukko 3").Select
Range("B4").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False

Workbooks.Open Filename:=myfile1, UpdateLinks:=0
ActiveWorkbook.Close False
Sheets("Aputaulukko 2").Select
Range("I16:L30").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Aputaulukko 3").Select
Range("G4").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
</code>```

答:
I took the liberty to rewrite your code... i'm still not quite sure why you are openning and closing the workbook immediately, but in essence this is what your code does at the moment:

Option Explicit

Sub HaeReseptiTiedot()

Application.ScreenUpdating = False

Dim wbSource As Workbook
Dim wb As Workbook: Set wb = ThisWorkbook 'Or ActiveWorkbook or Workbooks("book name")
Dim ws As Worksheet: Set ws = wb.ActiveSheet 'Or wb.Sheets("Sheet Name")
Dim rngToCopy As Range, rngToPaste As Range
Dim X As Long

For X = 4 To 49 Step 5
    On Error Resume Next
    Set wbSource = Workbooks.Open(FileName:=ws.Cells(19, X), UpdateLinks:=0)
    On Error GoTo 0

    If Not wbSource Is Nothing Then
        wbSource.Close False

        With wb.Sheets("Aputaulukko 2")
            Set rngToCopy = .Range(.Cells(16, X), .Cells(30, X + 3))
            'Debug.Print rngToCopy.Address
        End With

        With wb.Sheets("Aputaulukko 3")
            Set rngToPaste = .Range(.Cells(4, X - 2), .Cells(rngToCopy.Rows.Count + 3, X + 1))
            'Debug.Print rngToPaste.Address
        End With

        rngToPaste = rngToCopy.Value
    End If
    Set wbSource = Nothing
Next X

Application.ScreenUpdating = True
End Sub
```

Body:
Is there a way to skip error "filename is not found" and move to the next file?

Sub CopyDataAndMoveDown()

Application.ScreenUpdating = False

Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws As Worksheet: Set ws = wb.ActiveSheet
Dim rngToCopy As Range, rngToPaste As Range
Dim x As Long
Dim breakdown1
Dim breakdown As Worksheet: Set breakdown = wb.ActiveSheet

For x = 4 To 504 Step 6

    With wb.Sheets("Sheet1")
        breakdown1 = breakdown.Cells(9, x - 2)
    End With

    If IsEmpty(breakdown1) Then
        Call MoveBelow
    Else

        With wb.Sheets("Sheet1")
            Set rngToCopy = .Range(.Cells(4, x - 2), .Cells(24, x + 3))
            Debug.Print rngToCopy.Address
        End With

        With wb.Sheets("Sheet2")
            Set rngToPaste = .Range(.Cells(4, x - 2), .Cells(rngToCopy.Rows.Count + 3, x + 3))
            Debug.Print rngToPaste.Address
        End With

        rngToPaste = rngToCopy.Value
    End If

Next x

Application.ScreenUpdating = True
MsgBox "Valmis."
End Sub

Sub MoveBelow ()

Application.ScreenUpdating = False

Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws As Worksheet: Set ws = wb.ActiveSheet
Dim rngToCopy As Range, rngToPaste As Range
Dim x As Long
Dim breakdown1
Dim breakdown As Worksheet: Set breakdown = wb.ActiveSheet

For x = 4 To 504 Step 6

    With wb.Sheets("Sheet1")
        breakdown1 = breakdown.Cells(9, x - 2)
    End With

    If IsEmpty(breakdown1) Then
        ' At this point when the macro meet again a empty cell
        ' it should keep moving from the same counted X
        ' but start the paste operation from 24 rows below.
    Else

        With wb.Sheets("Sheet1")
            Set rngToCopy = .Range(.Cells(4, x - 2), .Cells(24, x + 3))
            Debug.Print rngToCopy.Address
        End With

        With wb.Sheets("Sheet2")
            Set rngToPaste = .Range(.Cells(28, x - 2), .Cells(rngToCopy.Rows.Count + 3, x + 3))
            Debug.Print rngToPaste.Address
        End With

        rngToPaste = rngToCopy.Value
    End If

Next x

Application.ScreenUpdating = True
MsgBox "Valmis."
End Sub

So when the macro is copying / pasting data from Sheet 1 to Sheet 2 and meets an empty cell it should keep going, copying next available data, but paste it 24 rows below.

--------Below the old question.

I have a VBA which is opening and closing file for that INDEX function get data. My problem is that. VBA is getting the filename from reference cell which contain the full path. But some of the reference cells are blanks/zeros and then the running VBA stops and give me error "filename is not found". Is there a way to skip that and move to next step?

Sub HaeReseptiTiedot()

Dim myfile As String
Dim myfile1 As String
Dim myfile2 As String
Dim myfile3 As String
Dim myfile4 As String
Dim myfile5 As String
Dim myfile6 As String
Dim myfile7 As String
Dim myfile8 As String
Dim myfile9 As String

myfile = Cells(19, 4).Value
myfile1 = Cells(19, 9).Value
myfile2 = Cells(19, 14).Value
myfile3 = Cells(19, 19).Value
myfile4 = Cells(19, 24).Value
myfile5 = Cells(19, 29).Value
myfile6 = Cells(19, 34).Value
myfile7 = Cells(19, 39).Value
myfile8 = Cells(19, 44).Value
myfile9 = Cells(19, 49).Value

Application.ScreenUpdating = False

Workbooks.Open Filename:=myfile, UpdateLinks:=0
ActiveWorkbook.Close False
Sheets("Aputaulukko 2").Select
Range("D16:G30").Select
Selection.Copy
Sheets("Aputaulukko 3").Select
Range("B4").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False

Workbooks.Open Filename:=myfile1, UpdateLinks:=0
ActiveWorkbook.Close False
Sheets("Aputaulukko 2").Select
Range("I16:L30").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Aputaulukko 3").Select
Range("G4").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False


问:
Is there an R function that will rank dates/times by other column criteria?
I am interested in changing the date column in dataf into ordered numbers (earliest date=1, second earliest=2... and so on) corresponding to id as in results$order. If an id only shows up once, I would like the order to be 1.

```<code>date=c("2012-02-18", "2013-03-01", "2013-04-11", "2013-06-06", "2013-09-20", "2013-07-02")
datef=strptime(date, format="%Y-%m-%d")
dataf=data.frame(id=c(20, 20, 20, 21, 21, 22),
              date=datef,
              service=c("web", "phone", "person", "phone", "web", "web"))
> dataf
  id       date service
1 20 2012-02-18     web
2 20 2013-03-01   phone
3 20 2013-04-11  person
4 21 2013-06-06   phone
5 21 2013-09-20     web
6 22 2013-07-02     web
</code>```

I am having a hard time even finding the correct wording to search for an answer to this dilemma. Am I looking to coerce? or index? the dataf$dates  into results$order below?

```<code>results=data.frame(id=c(20, 20, 20, 21, 21, 22),
                   order=c(1,2,3,1,2,1),
                   service=c("web", "phone", "person", "phone", "web", "web"))

> results
  id order service
1 20     1     web
2 20     2   phone
3 20     3  person
4 21     1   phone
5 21     2     web
6 22     1     web
</code>```

答:
With data.table:

```<code>library(data.table)

setDT(dataf)

setorder(dataf, id, date)
dataf[, order := 1:.N, by = id]
> dataf
   id       date service order
1: 20 2012-02-18     web     1
2: 20 2013-03-01   phone     2
3: 20 2013-04-11  person     3
4: 21 2013-06-06   phone     1
5: 21 2013-09-20     web     2
6: 22 2013-07-02     web     1
</code>```

Body:
I am interested in changing the date column in dataf into ordered numbers (earliest date=1, second earliest=2... and so on) corresponding to id as in results$order. If an id only shows up once, I would like the order to be 1.

date=c("2012-02-18", "2013-03-01", "2013-04-11", "2013-06-06", "2013-09-20", "2013-07-02")
datef=strptime(date, format="%Y-%m-%d")
dataf=data.frame(id=c(20, 20, 20, 21, 21, 22),
              date=datef,
              service=c("web", "phone", "person", "phone", "web", "web"))
> dataf
  id       date service
1 20 2012-02-18     web
2 20 2013-03-01   phone
3 20 2013-04-11  person
4 21 2013-06-06   phone
5 21 2013-09-20     web
6 22 2013-07-02     web

I am having a hard time even finding the correct wording to search for an answer to this dilemma. Am I looking to coerce? or index? the dataf$dates  into results$order below?

results=data.frame(id=c(20, 20, 20, 21, 21, 22),
                   order=c(1,2,3,1,2,1),
                   service=c("web", "phone", "person", "phone", "web", "web"))

> results
  id order service
1 20     1     web
2 20     2   phone
3 20     3  person
4 21     1   phone
5 21     2     web
6 22     1     web

Body:
With data.table:

library(data.table)

setDT(dataf)

setorder(dataf, id, date)
dataf[, order := 1:.N, by = id]
> dataf
   id       date service order
1: 20 2012-02-18     web     1
2: 20 2013-03-01   phone     2
3: 20 2013-04-11  person     3
4: 21 2013-06-06   phone     1
5: 21 2013-09-20     web     2
6: 22 2013-07-02     web     1


问:
How do I replace only first instance of a string
I need to replace the first instance of a word in a string with another string.  The problem is that the word being replaced sometimes appears more than once in the string that is being changed.  When that happens we only want the first instance to be replaced.  How can I do that?</p>

答:
```<code>        string s1 = "something replace replace replace replace something";
        string s2 = "replace";
        string newString=s1;

        int index = s1.IndexOf(s2);
        if (index > -1)
        {
            newString = s1.Substring(0, index) + "newWord" + s1.Substring(index + s2.Length);
        }
        Console.WriteLine(newString);
</code>```


问:
More efficient raster reclassification
I have a raster where the first column must be reclassified, leaving all other values as NA. I have written the code to do this (below) but it is very inefficient as the raster size grows much beyond this toy example.

Could someone recommend a more efficient way to re-write this code so that it can handle much larger raster files? I suspect apply() could be useful here but I'm unsure what direction to take this in.

```<code>r<-raster::raster(nrow=10, ncol=10)
r[]<-NA

  for(i in 1:r@nrows){
    r[(r@nrows*i)-(r@ncols-1)]<-2

  }

</code>```

答:
First a better way to do what you do

```<code>library(raster)
r <- raster::raster(nrow=10, ncol=10)
for(i in 1:nrow(r)){
    r[i, 1] <- 2
}
</code>```

A much better alternative

```<code>r <- raster::raster(nrow=10, ncol=10)
r[,1] <- 2
</code>```

But for larger rasters it is perhaps best do

```<code>r <- raster::raster(nrow=10, ncol=10)
xy <- cbind(xFromCol(r, 1), yFromRow(r, 1:nrow(r)))
r <- rasterize(xy, r, field=2)
</code>```

And probably less efficient like this

```<code>r <- raster::raster(nrow=10, ncol=10)
r <- init(r, "col")
r <- reclassify(r, rbind(c(1,1,2), c(2,Inf,NA)), right=TRUE, include.lowest=TRUE)
</code>```

Same idea, nicely concise

```<code>r <- subs(init(r, "col"), data.frame(from=1, to=2))
</code>```

Title: More efficient raster reclassification

Body:
I have a raster where the first column must be reclassified, leaving all other values as NA. I have written the code to do this (below) but it is very inefficient as the raster size grows much beyond this toy example.

Could someone recommend a more efficient way to re-write this code so that it can handle much larger raster files? I suspect apply() could be useful here but I'm unsure what direction to take this in.

r<-raster::raster(nrow=10, ncol=10)
r[]<-NA

  for(i in 1:r@nrows){
    r[(r@nrows*i)-(r@ncols-1)]<-2

  }

Body:
First a better way to do what you do

library(raster)
r <- raster::raster(nrow=10, ncol=10)
for(i in 1:nrow(r)){
    r[i, 1] <- 2
}

A much better alternative

r <- raster::raster(nrow=10, ncol=10)
r[,1] <- 2

But for larger rasters it is perhaps best do

r <- raster::raster(nrow=10, ncol=10)
xy <- cbind(xFromCol(r, 1), yFromRow(r, 1:nrow(r)))
r <- rasterize(xy, r, field=2)

And probably less efficient like this

r <- raster::raster(nrow=10, ncol=10)
r <- init(r, "col")
r <- reclassify(r, rbind(c(1,1,2), c(2,Inf,NA)), right=TRUE, include.lowest=TRUE)

Same idea, nicely concise

r <- subs(init(r, "col"), data.frame(from=1, to=2))


问:
How to pass value to confirmation popup from custom screen
I need to fire Complete Order action of Production Order Maintenance screen from my custom screen, the issue is, when action is fired am getting an error saying, "Are you sure want to complete the order" this is the same confirmation message we get when we do from Production Order Maintenance screen as well, my question is, how we can avoid this popup or how i can pass value to this popup from my custom graph.</p>

```<code>ProdMaintGraph.ProdMaintRecords.Current = ProdItem;
ProdMaintGraph.completeorder.Press();
</code>```

答:
You can try it like this!

```<code>ProdMaintGraph.ProdMaintRecords.Cache.Graph.Views["ProdMaintRecords"].Answer = WebDialogResult.Yes;
</code>```

If in the popup form Message Buttoin is Yes, or one is this values which are None,OK ,Cancel,Abort,Retry ,Ignore,Yes,No

Body:
I need to fire Complete Order action of Production Order Maintenance screen from my custom screen, the issue is, when action is fired am getting an error saying, "Are you sure want to complete the order" this is the same confirmation message we get when we do from Production Order Maintenance screen as well, my question is, how we can avoid this popup or how i can pass value to this popup from my custom graph.

ProdMaintGraph.ProdMaintRecords.Current = ProdItem;
ProdMaintGraph.completeorder.Press();

Body:
You can try it like this!

ProdMaintGraph.ProdMaintRecords.Cache.Graph.Views["ProdMaintRecords"].Answer = WebDialogResult.Yes;

If in the popup form Message Buttoin is Yes, or one is this values which are None,OK ,Cancel,Abort,Retry ,Ignore,Yes,No


问:
Xamarin.Forms iOS CursorPosition not being honored
In my Xamarin.Forms app, I have a behavior that sets the cursor's position (the behavior acts as a mask for our input field).

The CursorPosition is set by calling: targetEntry.CursorPosition = newCursorPosition. This works perfectly fine on Android, but on iOS the cursor always goes to the end of the text, is it an iOS version specific bug, or is it just across the board?

Everything else about the behavior (ensuring that the text is properly masked, that it properly removes the underline character which acts as the guide for where a user should input their data) works as it should. I can post more of my code if needed

Edit: newCursorPosition is a static int variable

Edit 2: Including my code

public class DurationViewMaskBehavior : Behavior
    {
        public static DurationViewMaskBehavior Instance = new DurationViewMaskBehavior();
        private static int cursorPosition = 0;

```<code>    protected override void OnAttachedTo(BorderlessEntry entry) {
        entry.TextChanged += OnInput;
        base.OnAttachedTo(entry);
    }

    protected override void OnDetachingFrom(BorderlessEntry entry) {
        entry.TextChanged -= OnInput;
        base.OnDetachingFrom(entry);
    }

    /// <summary>
    /// This method exists to ensure that if the user tried to shape the field to be something it shouldn't
    /// that it will return the mask to the correct format; this is to ensure that we only have valid data and also that
    /// </summary>
    /// <param name="text"></param>
    /// <returns></returns>
    private bool PatternMatchCheck(string text) {

        var regex = @"^(([0-9]\d{1}|__|[0-9]_|[0-9]|[0-9]*__|[0-9]\d{1}_| *) Min, ([0-9]\d{1}|__|[0-9]_|[0-9]|[0-9]__|[0-9]\d{1}_|) Sec|((Min, Sec)|[0-9]+ Min, Sec|Min, [0-9]+ Sec))$";

        var match = Regex.Match(text, regex, RegexOptions.IgnoreCase);

        return match.Success;
    }

    private void OnInput(object sender, TextChangedEventArgs args) {

        //Only fire this behavior when the user actually inputs some type of value
        if(!string.IsNullOrWhiteSpace(args.NewTextValue)) {

            var text = args.NewTextValue;

            //How this works so far:
            //At first you get the input, so text.length == 1 is fine. Then
            //it updates itself, so really for every input this event fires twice.
            //After that we will have to look at the actual text itself so we can use
            //the index instead

            var targetObject = ((BorderlessEntry)sender);

            if(!PatternMatchCheck(args.NewTextValue) && args.OldTextValue.Length > 2) {
                targetObject.Text = args.OldTextValue;
                return;
            }

            if (text.Length == 1) {
                targetObject.Text = $"{text}_ Min, __ Sec";
                cursorPosition = 1;
            }

            if(text.Contains("_")) {
                if (text.Length > 1 && (text[2] != '_' || text[1] != '_')) {
                    if (text[2] == '_' && text[0] != '_') {
                        targetObject.Text = $"{text.Substring(0, 2)} Min, __ Sec";
                        cursorPosition = 8;
                    }
                }

                if (text.Length > 1 && text[8] != '_' && text[9] == '_' && text[8] != ' ') {
                    targetObject.Text = $"{text.Substring(0, 2)} Min, {text[8]}_ Sec";
                    cursorPosition = 9;
                }

                if (text.Length > 1 && text[8] != '_' && text[9] != '_') {
                    targetObject.Text = $"{text.Substring(0, 2)} Min, {text.Substring(8, 2)} Sec";
                    cursorPosition = text.Length-1;
                }
            }

            targetObject.CursorPosition = cursorPosition;
        }
    }
}
</code>```

答:
Figured out why, looks like iOS requires me to bind another .TextChanged event that handles the setting of the cursor. It is strange and backward, but it works. </p>

```<code>private void SetCursor(object sender, TextChangedEventArgs args) {
            ((BorderlessEntry)sender).CursorPosition = cursorPosition;
        }

if(isRegistered) {
                    targetObject.TextChanged -= SetCursor;
                    isRegistered = false;
                }
                else {
                    targetObject.TextChanged += SetCursor;
                    isRegistered = true;
                }
</code>```

Body:
In my Xamarin.Forms app, I have a behavior that sets the cursor's position (the behavior acts as a mask for our input field).

The CursorPosition is set by calling: targetEntry.CursorPosition = newCursorPosition. This works perfectly fine on Android, but on iOS the cursor always goes to the end of the text, is it an iOS version specific bug, or is it just across the board?

Everything else about the behavior (ensuring that the text is properly masked, that it properly removes the underline character which acts as the guide for where a user should input their data) works as it should. I can post more of my code if needed

Edit: newCursorPosition is a static int variable

Edit 2: Including my code

public class DurationViewMaskBehavior : Behavior
    {
        public static DurationViewMaskBehavior Instance = new DurationViewMaskBehavior();
        private static int cursorPosition = 0;

    protected override void OnAttachedTo(BorderlessEntry entry) {
        entry.TextChanged += OnInput;
        base.OnAttachedTo(entry);
    }

    protected override void OnDetachingFrom(BorderlessEntry entry) {
        entry.TextChanged -= OnInput;
        base.OnDetachingFrom(entry);
    }

    ///
    /// This method exists to ensure that if the user tried to shape the field to be something it shouldn't
    /// that it will return the mask to the correct format; this is to ensure that we only have valid data and also that
    ///
    /// <param name="text"></param>
    /// <returns></returns>
    private bool PatternMatchCheck(string text) {

        var regex = @"^(([0-9]\d{1}|__|[0-9]_|[0-9]|[0-9]*__|[0-9]\d{1}_| *) Min, ([0-9]\d{1}|__|[0-9]_|[0-9]|[0-9]__|[0-9]\d{1}_|) Sec|((Min, Sec)|[0-9]+ Min, Sec|Min, [0-9]+ Sec))$";

        var match = Regex.Match(text, regex, RegexOptions.IgnoreCase);

        return match.Success;
    }

    private void OnInput(object sender, TextChangedEventArgs args) {

        //Only fire this behavior when the user actually inputs some type of value
        if(!string.IsNullOrWhiteSpace(args.NewTextValue)) {

            var text = args.NewTextValue;

            //How this works so far:
            //At first you get the input, so text.length == 1 is fine. Then
            //it updates itself, so really for every input this event fires twice.
            //After that we will have to look at the actual text itself so we can use
            //the index instead

            var targetObject = ((BorderlessEntry)sender);

            if(!PatternMatchCheck(args.NewTextValue) && args.OldTextValue.Length > 2) {
                targetObject.Text = args.OldTextValue;
                return;
            }

            if (text.Length == 1) {
                targetObject.Text = $"{text}_ Min, __ Sec";
                cursorPosition = 1;
            }

            if(text.Contains("_")) {
                if (text.Length > 1 && (text[2] != '_' || text[1] != '_')) {
                    if (text[2] == '_' && text[0] != '_') {
                        targetObject.Text = $"{text.Substring(0, 2)} Min, __ Sec";
                        cursorPosition = 8;
                    }
                }

                if (text.Length > 1 && text[8] != '_' && text[9] == '_' && text[8] != ' ') {
                    targetObject.Text = $"{text.Substring(0, 2)} Min, {text[8]}_ Sec";
                    cursorPosition = 9;
                }

                if (text.Length > 1 && text[8] != '_' && text[9] != '_') {
                    targetObject.Text = $"{text.Substring(0, 2)} Min, {text.Substring(8, 2)} Sec";
                    cursorPosition = text.Length-1;
                }
            }

            targetObject.CursorPosition = cursorPosition;
        }
    }
}

Body:
Figured out why, looks like iOS requires me to bind another .TextChanged event that handles the setting of the cursor. It is strange and backward, but it works.

private void SetCursor(object sender, TextChangedEventArgs args) {
            ((BorderlessEntry)sender).CursorPosition = cursorPosition;
        }

if(isRegistered) {
                    targetObject.TextChanged -= SetCursor;
                    isRegistered = false;
                }
                else {
                    targetObject.TextChanged += SetCursor;
                    isRegistered = true;
                }


问:
Why doesnt this hover trigger text animation?
Trying to add a hover in a CMS program that only allows internal css. Please note that, while there is no head tag, the CMS recognizes  tags and automatically places them in the .

I've tried exporting as html to work through the issue but so far no luck. Tried using hierarchy by placing the resting state as H1 and hover state as a div class and as an ID. This is to be used through EKTRON CMS running html5 with no accessibility to js.

body {
  margin: 0;
  padding: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
}

h1 {
  margin: 0;
  padding: 0;
}

h1 span {
  display: inline-flex;
  color: #1C7CB3;
}

h1 span:nth-child(even) {
  overflow: hidden;
  transition: ease 0.5s;
  color: purple;
  letter-spacing: -1em;
}

h1:hover span:nth-last-child(even) {
  letter-spacing: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>
  <span>F</span><span>lorida</span>
  <span>I</span><span>nstitute</span>
  <span></span><span>of</span>
  <span>E</span><span>ducation</span>
</h1></code>```

I expected the text to animate but the text stays static.

答:
In the hover effect you are using the :nth-last-child(even) selector. This will select every even element starting from the last. That is it will have it's first odd element being ducation and it's first even being E. You instead would want to use the :nth-child(even) to select from the start.

```<code>h1:hover span:nth-child(even)
{
    letter-spacing: 0;
}
</code>```

Body:
Trying to add a hover in a CMS program that only allows internal css. Please note that, while there is no head tag, the CMS recognizes  tags and automatically places them in the .

I've tried exporting as html to work through the issue but so far no luck. Tried using hierarchy by placing the resting state as H1 and hover state as a div class and as an ID. This is to be used through EKTRON CMS running html5 with no accessibility to js.

body {
  margin: 0;
  padding: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
}

h1 {
  margin: 0;
  padding: 0;
}

h1 span {
  display: inline-flex;
  color: #1C7CB3;
}

h1 span:nth-child(even) {
  overflow: hidden;
  transition: ease 0.5s;
  color: purple;
  letter-spacing: -1em;
}

h1:hover span:nth-last-child(even) {
  letter-spacing: 0;
}

  Florida
  Institute
  of
  Education

I expected the text to animate but the text stays static.

Body:
In the hover effect you are using the :nth-last-child(even) selector. This will select every even element starting from the last. That is it will have it's first odd element being <span>ducation</span> and it's first even being <span>E</span>. You instead would want to use the :nth-child(even) to select from the start.

h1:hover span:nth-child(even)
{
    letter-spacing: 0;
}


问:
How do I override JSON errors and prevent a blank page from loading?
How do I prevent my JSON feed from crashing and ignore errors from a database if they occur while running, also how do I change the undefined errors into a string to return as a fall back like "pending" or "not available."

I tried inputting the Try, catch, finally method. Also, the If statements conditional equal and null ones I found to change undefined into a "string"

```<code>var flight             = document.getElementById("flight");
var time               = document.getElementById("time");
var airline            = document.getElementById("airline");
var stat               = document.getElementById("status");
var cities             = document.getElementById("cities");

//Loading the document

//this is for updating the url
 var url                = './airport-test.json';
//var url = './proxy.php';
 $(document).ready(function () {
  $.ajax({
 type: "GET",
 dataType: "json",
 url: url,
 async: true,
 contentType: "application/json; charset=utf-8",
 cache: false,
 success: function (data) {
 var flightString      = "";
 var timeString        = "";
 var airlineString     = "";
 var statString        = "";
 var citiesString      = "";

 if(data) {
      try {
        var a           = JSON.parse(data);
        console.log(a);
        } catch(e) {
       var errorMessage = e.name + '' + e.message;
       console.log(errorMessage);
      }
    }

  for (i= 0,l = data.length = 16; i < l; i++ ) {
 code here I erased to fit this question better...

     }

 flight.insertAdjacentHTML('beforeend', flightString);
 time.insertAdjacentHTML('beforeend', timeString);
 airline.insertAdjacentHTML('beforeend', airlineString);
 stat.insertAdjacentHTML('beforeend', statString);
 cities.insertAdjacentHTML('beforeend', citiesString);

      }});

    });
</code>```

I am using a raspberry pi with chromium I just want the JSON feed to still show up even when there is an error instead of a blank page. It works most of the time. Also, want to change undefined from errors into a fallback string.

答:
Not totally sure what exactly is the problem, taking a wild guess the server is not responding properly.

Define error handler,

```<code>$.ajax({
 type: "GET",
 dataType: "json",
 url: url,
 async: true,
 contentType: "application/json; charset=utf-8",
 cache: false,
 success: function (data) {
  ....
 }
 error: function (error) {
  // handle your error here.
  ....
 }
</code>```

Body:
How do I prevent my JSON feed from crashing and ignore errors from a database if they occur while running, also how do I change the undefined errors into a string to return as a fall back like "pending" or "not available."

I tried inputting the Try, catch, finally method. Also, the If statements conditional equal and null ones I found to change undefined into a "string"

var flight             = document.getElementById("flight");
var time               = document.getElementById("time");
var airline            = document.getElementById("airline");
var stat               = document.getElementById("status");
var cities             = document.getElementById("cities");

//Loading the document

//this is for updating the url
 var url                = './airport-test.json';
//var url = './proxy.php';
 $(document).ready(function () {
  $.ajax({
 type: "GET",
 dataType: "json",
 url: url,
 async: true,
 contentType: "application/json; charset=utf-8",
 cache: false,
 success: function (data) {
 var flightString      = "";
 var timeString        = "";
 var airlineString     = "";
 var statString        = "";
 var citiesString      = "";

 if(data) {
      try {
        var a           = JSON.parse(data);
        console.log(a);
        } catch(e) {
       var errorMessage = e.name + '' + e.message;
       console.log(errorMessage);
      }
    }

  for (i= 0,l = data.length = 16; i < l; i++ ) {
 code here I erased to fit this question better...

     }

 flight.insertAdjacentHTML('beforeend', flightString);
 time.insertAdjacentHTML('beforeend', timeString);
 airline.insertAdjacentHTML('beforeend', airlineString);
 stat.insertAdjacentHTML('beforeend', statString);
 cities.insertAdjacentHTML('beforeend', citiesString);

      }});

    });

I am using a raspberry pi with chromium I just want the JSON feed to still show up even when there is an error instead of a blank page. It works most of the time. Also, want to change undefined from errors into a fallback string.

Body:
Not totally sure what exactly is the problem, taking a wild guess the server is not responding properly.

Define error handler,

$.ajax({
 type: "GET",
 dataType: "json",
 url: url,
 async: true,
 contentType: "application/json; charset=utf-8",
 cache: false,
 success: function (data) {
  ....
 }
 error: function (error) {
  // handle your error here.
  ....
 }


问:
If a var in JavaScript is defined twice, which definition should the interpreter take?
I'm new to JavaScript and am trying to understand the concepts of hoisting and scope.

Case 1

var name;

function logName(num) {
  console.log(name, num);
}

logName(1);
name = "Auro";
logName(2);```
</div>
</div>
</p>

<p>and I have the following output in the console</p>

```Auro 1
Auro 2
```

<p>If I understand <code>hoisting</code> correctly, JS engine hoists the declaration of a variable first and then automatically assigns a value <code>undefined</code> to it. Only when it encounters the assignment (<code>=</code>) operator, does it actually assign the intended value to it.</p>

<p>If my understanding above is correct, then the first time the <code>logName</code> function was called, the variable <code>name</code> should have printed undefined, but it is printing the value.</p>

<p><strong>Case 2</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var name;

function logName(num) {
  console.log(name, num);
}

logName(1);
name = "Auro";
logName(2);
name = "Baner";</code>```

Output in the console:

```<code>Baner 1
Auro 2
</code>```

This confuses me even more. Here the first call to the function logName picked the later assignment to the variable and printed Baner, however, the second call picked the previous assignment, that is Auro.

What is going on here? What am I missing?

答:
No none of the specified output matches, as initially you have value of name equal to window.name, so initially the value of name variable will be equal to winow.name and once overwrite it you get the new value

let's understand how this all works

You can understand as such there are two phase of code execution

Creation phase

Execution phase

Creation phase:- During creation phase function is hoisted at top as it is, while the variable are hoisted but there is no value assigned to it ( or you can say it's value is undefined )

Execution phase:- During execution context it assigns value to variable when it reaches line where assignment is happening

var name;

function logName(num) {
  console.log(name, num);
}

logName(1);
name = "Auro";
logName(2);
name = "Baner";```

Body:
I'm new to JavaScript and am trying to understand the concepts of hoisting and scope.

Case 1

var name;

function logName(num) {
  console.log(name, num);
}

logName(1);
name = "Auro";
logName(2);

and I have the following output in the console

Auro 1
Auro 2

If I understand hoisting correctly, JS engine hoists the declaration of a variable first and then automatically assigns a value undefined to it. Only when it encounters the assignment (=) operator, does it actually assign the intended value to it.

If my understanding above is correct, then the first time the logName function was called, the variable name should have printed undefined, but it is printing the value.

Case 2

var name;

function logName(num) {
  console.log(name, num);
}

logName(1);
name = "Auro";
logName(2);
name = "Baner";

Output in the console:

Baner 1
Auro 2

This confuses me even more. Here the first call to the function logName picked the later assignment to the variable and printed Baner, however, the second call picked the previous assignment, that is Auro.

What is going on here? What am I missing?


问:
How to use wsdl2java to generate code from WSDL which is secured using x.509 certificate?
I try to generate Java classes using wsdl2java.

Wsdl is located in remote server which is secured using X509 certificate, in such a way, that when I try to access it in the browser without having certificate in trust store, it is returning an error (of course when I have certificate imported into certmgr.msc, wsdl is showing just fine).

Unfortunatelly, when I try to run wsdl2java, I get:

```<code>> org.apache.cxf.wsdl11.WSDLRuntimeException: Fail to create wsdl definition file:/resources/wsdl/my.xml: WSDLException (at /wsdl:definitions/wsdl:types/xsd:schema): faultCode=PARSER_ERROR: Problem parsing 'https://SERVER_HOST/my?xsd=../xsd/XX.xsd'.: javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure
</code>```

I have my certificate imported in JKS store.

How can I advise wsdl2java to use that certificate from JKS in order to connect to the serwer?

答:
I would like suggest you skip this problem by below steps:

Download that wsdl manually to your local machine.

Dlownload that xsd files which referenced in that wsdl file manaully to your local machine.

Modify that wsdl to change xsd location to your local one.

You are fine to generate java code now.

If you really want to make it. Please refer to here:

"%JAVA_HOME%\bin\java" -Djavax.net.ssl.trustStore="{keystorefile}" -Djavax.net.ssl.trustStorePassword="{password}" -Djavax.net.ssl.keyStoreType="jks" -Dorg.jboss.security.ignoreHttpsHost="true" -Xmx128M -Djava.endorsed.dirs="%CXF_HOME%\lib\endorsed" -cp "%CXF_JAR%;%TOOLS_JAR%;%CLASSPATH%" -Djava.util.logging.config.file="%CXF_HOME%\etc\logging.properties" org.apache.cxf.tools.wadlto.WADLToJava %*
```

coming from : How to generate client code using wsdl2java through https?

Body:
I try to generate Java classes using wsdl2java.

Wsdl is located in remote server which is secured using X509 certificate, in such a way, that when I try to access it in the browser without having certificate in trust store, it is returning an error (of course when I have certificate imported into certmgr.msc, wsdl is showing just fine).

Unfortunatelly, when I try to run wsdl2java, I get:

> org.apache.cxf.wsdl11.WSDLRuntimeException: Fail to create wsdl definition file:/resources/wsdl/my.xml: WSDLException (at /wsdl:definitions/wsdl:types/xsd:schema): faultCode=PARSER_ERROR: Problem parsing 'https://SERVER_HOST/my?xsd=../xsd/XX.xsd'.: javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure

I have my certificate imported in JKS store.

How can I advise wsdl2java to use that certificate from JKS in order to connect to the serwer?

Body:
I would like suggest you skip this problem by below steps:

Download that wsdl manually to your local machine.

Dlownload that xsd files which referenced in that wsdl file manaully to your local machine.

Modify that wsdl to change xsd location to your local one.

You are fine to generate java code now.

If you really want to make it. Please refer to here:

"%JAVA_HOME%\bin\java" -Djavax.net.ssl.trustStore="{keystorefile}" -Djavax.net.ssl.trustStorePassword="{password}" -Djavax.net.ssl.keyStoreType="jks" -Dorg.jboss.security.ignoreHttpsHost="true" -Xmx128M -Djava.endorsed.dirs="%CXF_HOME%\lib\endorsed" -cp "%CXF_JAR%;%TOOLS_JAR%;%CLASSPATH%" -Djava.util.logging.config.file="%CXF_HOME%\etc\logging.properties" org.apache.cxf.tools.wadlto.WADLToJava %*

coming from : How to generate client code using wsdl2java through https?