问:
How to input variable in dbcontext.SqlQuery query?
When creating this function in my Web API project controller everything works just fine.

```<code>public IQueryable<EquipmentApproval> GetUserEquipmentApprovalRejections(string username)
{
    return db.EquipmentApprovals.SqlQuery("select * from EquipmentApproval where rejectedReason is not NULL AND createdBy = 'hmbangu'").AsQueryable<EquipmentApproval>();
}
</code>```

But When I try yo add a variable parameter like this:

```<code>...
    return db.EquipmentApprovals.SqlQuery("select * from EquipmentApproval where rejectedReason IS NOT NULL AND createdBy = @username" + new SqlParameter("@username", username)).AsQueryable<EquipmentApproval>()
...
</code>```

I receive and error when I query the API, could someone tell me please tell how to add a variable to my dbcontext.SqlQuery() query. I also want my data to be returend as an IQueryable list.

答:
You need to add them comma separated</p>

```<code>return db.EquipmentApprovals
        .SqlQuery("select * from EquipmentApproval where rejectedReason IS NOT NULL AND createdBy = @username",
            new SqlParameter("username", username))
        .AsQueryable<EquipmentApproval>()
</code>```

Body:
When creating this function in my Web API project controller everything works just fine.

public IQueryable<EquipmentApproval> GetUserEquipmentApprovalRejections(string username)
{
    return db.EquipmentApprovals.SqlQuery("select * from EquipmentApproval where rejectedReason is not NULL AND createdBy = 'hmbangu'").AsQueryable<EquipmentApproval>();
}

But When I try yo add a variable parameter like this:

...
    return db.EquipmentApprovals.SqlQuery("select * from EquipmentApproval where rejectedReason IS NOT NULL AND createdBy = @username" + new SqlParameter("@username", username)).AsQueryable<EquipmentApproval>()
...

I receive and error when I query the API, could someone tell me please tell how to add a variable to my dbcontext.SqlQuery() query. I also want my data to be returend as an IQueryable list.

Body:
You need to add them comma separated

return db.EquipmentApprovals
        .SqlQuery("select * from EquipmentApproval where rejectedReason IS NOT NULL AND createdBy = @username",
            new SqlParameter("username", username))
        .AsQueryable<EquipmentApproval>()


来源: stackexchange

问:
Warning: Invalid argument supplied for foreach() on filter
I have a column where I'm pulling in objects from Recipe and getting the names back, but some posts don't have 'required' authors yet and I'm getting a debug error back - Is it possible to set a 'No authors available' echo if there are no array/objects being returned?

Here is the code:

```<code>add_action('manage_post_posts_custom_column', function($column, $post_id) {
    switch ($column) {
        case 'authors':

            $recipe = Recipe::init($post_id);

            if (is_array($recipe) || is_object($recipe))
            {
                foreach ($recipe->get_authors() as $profile) {
                    $arr[] = '<a href="' . $profile->get_url() . '">' . $profile->get_name() . '</a>';
                }
                echo implode($arr, ', ');
                break;
            } else {
                echo 'No authors';
            }
    }
}, 10, 3);
</code>```

Here in the screenshot below, you can see my first post has authors, but the second post doesn't have them set yet.

var_dump(is_object($recipe)) returns true for the first post.

Could someone tell me what I might be doing wrong?

```<code>public function set_authors($authors)
{
    $profiles = [];

    foreach ($authors as $author) {
        $profiles[] = Profile::init($author);
    }

    $this->authors = $profiles;
}

public function get_authors()
{
    return $this->authors;
}
</code>```

答:
Here you go! You also had a problem in implode, you were passing the array then the glue, but it had to be the other way around.

```<code>add_action('manage_post_posts_custom_column', function ($column, $post_id) {
    switch ($column) {
        case 'authors':

            $recipe = Recipe::init($post_id);

            if (is_array($recipe) || is_object($recipe)) {
                $authors = $recipe->get_authors();

                if (isset($authors) && !empty($authors)) {
                    $arr = array();
                    foreach ($authors as $profile) {
                        $arr[] = '<a href="' . $profile->get_url() . '">' . $profile->get_name() . '</a>';
                    }
                    echo implode(', ', $arr);
                    break;
                }
                echo "No Authors";
                break;
            } else {
                echo 'No authors';
            }
    }
}, 10, 3);
</code>```

Update, change set_authors to:

```<code>public function set_authors($authors)
{
    $profiles = [];
    if(!empty($authors)){
        foreach ($authors as $author) {
            $profiles[] = Profile::init($author);
        }
    }
    $this->authors = $profiles;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a column where I'm pulling in objects from Recipe and getting the names back, but some posts don't have 'required' authors yet and I'm getting a debug error back - Is it possible to set a 'No authors available' echo if there are no array/objects being returned?

Here is the code:

add_action('manage_post_posts_custom_column', function($column, $post_id) {
    switch ($column) {
        case 'authors':

            $recipe = Recipe::init($post_id);

            if (is_array($recipe) || is_object($recipe))
            {
                foreach ($recipe->get_authors() as $profile) {
                    $arr[] = 'get_url() . '">' . $profile->get_name() . '';
                }
                echo implode($arr, ', ');
                break;
            } else {
                echo 'No authors';
            }
    }
}, 10, 3);

Here in the screenshot below, you can see my first post has authors, but the second post doesn't have them set yet.

var_dump(is_object($recipe)) returns true for the first post.

Could someone tell me what I might be doing wrong?

public function set_authors($authors)
{
    $profiles = [];

    foreach ($authors as $author) {
        $profiles[] = Profile::init($author);
    }

    $this->authors = $profiles;
}

public function get_authors()
{
    return $this->authors;
}

Body:
Here you go! You also had a problem in implode, you were passing the array then the glue, but it had to be the other way around.

add_action('manage_post_posts_custom_column', function ($column, $post_id) {
    switch ($column) {
        case 'authors':

            $recipe = Recipe::init($post_id);

            if (is_array($recipe) || is_object($recipe)) {
                $authors = $recipe->get_authors();

                if (isset($authors) && !empty($authors)) {
                    $arr = array();
                    foreach ($authors as $profile) {
                        $arr[] = '<a href="' . $profile->get_url() . '">' . $profile->get_name() . '</a>';
                    }
                    echo implode(', ', $arr);
                    break;
                }
                echo "No Authors";
                break;
            } else {
                echo 'No authors';
            }
    }
}, 10, 3);

Update, change set_authors to:

public function set_authors($authors)
{
    $profiles = [];
    if(!empty($authors)){
        foreach ($authors as $author) {
            $profiles[] = Profile::init($author);
        }
    }
    $this->authors = $profiles;
}


问:
How to send keyed message to Kafka using Spring Cloud Stream Supplier
I want to use Spring Cloud Stream to produce keyed (message with specific key) messages to Kafka.

```<code>@SpringBootApplication
public class SpringCloudStreamKafkaApplication {

  public static void main(String[] args) {
    SpringApplication.run(SpringCloudStreamKafkaApplication.class, args);
  }

  @Bean
  Supplier<DataRecord> process(){
    return () -> new DataRecord(42L);
  }

}
</code>```

What do I need to change in the Supplier code to provide key?
Is it possible in new style of API (using lambdas)?

Thank you

答:
Return a Message<?> and set the KafkaHeaders.MESSAGE_KEY header:

```<code>@Bean
Supplier<Message<String>> process() {
    return () -> MessageBuilder.withPayload("foo")
            .setHeader(KafkaHeaders.MESSAGE_KEY, "bar".getBytes())
            .build();
}
</code>```

(assumes the default key serializer (byte[]).

EDIT

This will be called endlessly.

If you want to send a finite stream, I believe you have to switch to the reactive model.

```<code>@Bean
Supplier<Flux<Message<String>>> processFinite() {
    Message<String> msg1 = MessageBuilder.withPayload("foo")
            .setHeader(KafkaHeaders.MESSAGE_KEY, "bar".getBytes())
            .build();
    Message<String> msg2 = MessageBuilder.withPayload("baz")
            .setHeader(KafkaHeaders.MESSAGE_KEY, "qux".getBytes())
            .build();
    return () -> {
        return Flux.just(msg1, msg2);
    };
}
</code>```

There is also Flux.fromStream(myStream).

Which will end at the end of the stream.

EDIT2

You can also use the StreamBridge.

https://docs.spring.io/spring-cloud-stream/docs/3.1.4/reference/html/spring-cloud-stream.html#_sending_arbitrary_data_to_an_output_e_g_foreign_event_driven_sources

Body:
I want to use Spring Cloud Stream to produce keyed (message with specific key) messages to Kafka.

@SpringBootApplication
public class SpringCloudStreamKafkaApplication {

  public static void main(String[] args) {
    SpringApplication.run(SpringCloudStreamKafkaApplication.class, args);
  }

  @Bean
  Supplier<DataRecord> process(){
    return () -> new DataRecord(42L);
  }

}

What do I need to change in the Supplier code to provide key?
Is it possible in new style of API (using lambdas)?

Thank you

Body:
Return a Message<?> and set the KafkaHeaders.MESSAGE_KEY header:

@Bean
Supplier<Message<String>> process() {
    return () -> MessageBuilder.withPayload("foo")
            .setHeader(KafkaHeaders.MESSAGE_KEY, "bar".getBytes())
            .build();
}

(assumes the default key serializer (byte[]).

EDIT

This will be called endlessly.

If you want to send a finite stream, I believe you have to switch to the reactive model.

@Bean
Supplier<Flux<Message<String>>> processFinite() {
    Message<String> msg1 = MessageBuilder.withPayload("foo")
            .setHeader(KafkaHeaders.MESSAGE_KEY, "bar".getBytes())
            .build();
    Message<String> msg2 = MessageBuilder.withPayload("baz")
            .setHeader(KafkaHeaders.MESSAGE_KEY, "qux".getBytes())
            .build();
    return () -> {
        return Flux.just(msg1, msg2);
    };
}

There is also Flux.fromStream(myStream).

Which will end at the end of the stream.

EDIT2

You can also use the StreamBridge.

https://docs.spring.io/spring-cloud-stream/docs/3.1.4/reference/html/spring-cloud-stream.html#_sending_arbitrary_data_to_an_output_e_g_foreign_event_driven_sources


问:
Email Intent subject is ignored in gmail, but works with other mail clients
For below mentioned code subject is getting displayed in other email accounts but the same is coming blank in gmail.     </p>

```<code>Intent j = new Intent(Intent.ACTION_SENDTO);
j.setData(Uri.parse("mailto:appsupport@prali.in"));
j.putExtra(Intent.EXTRA_SUBJECT, "Request approval for Kiranam Registration - " + KiranamUserId);
startActivity(Intent.createChooser(j, "Select your mail account to send mail for Approval"));
</code>```

答:
I found that setting the data part of the intent to Uri.parse("mailto:") and defining the email via Intent.EXTRA_EMAIL works fine:

```<code>Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:")).apply {
    putExtra(Intent.EXTRA_EMAIL, arrayOf("help@test.com"))
    putExtra(Intent.EXTRA_SUBJECT, "Support request")
    putExtra(Intent.EXTRA_TEXT, "Hello team!")
}
</code>```

Body:
For below mentioned code subject is getting displayed in other email accounts but the same is coming blank in gmail.

Intent j = new Intent(Intent.ACTION_SENDTO);
j.setData(Uri.parse("mailto:appsupport@prali.in"));
j.putExtra(Intent.EXTRA_SUBJECT, "Request approval for Kiranam Registration - " + KiranamUserId);
startActivity(Intent.createChooser(j, "Select your mail account to send mail for Approval"));

Body:
I found that setting the data part of the intent to Uri.parse("mailto:") and defining the email via Intent.EXTRA_EMAIL works fine:

Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:")).apply {
    putExtra(Intent.EXTRA_EMAIL, arrayOf("help@test.com"))
    putExtra(Intent.EXTRA_SUBJECT, "Support request")
    putExtra(Intent.EXTRA_TEXT, "Hello team!")
}


问:
R adding element to Dataframe at specific position
I want to add a row to a dataframe in R at a specific position. I am aware that there are solutions for this on this site, yet they don't seem to work. I know rbind is rather slow, but given that I only need to do it for a single element it doesn't matter:

Example:

```<code>vector_labour_brexit.m <- data.frame("value" = c(1,2,3,4,5,6,7,8,9))

temp <- rbind(vector_labour_brexit.m[1:5,], data.frame("value"=5000),
                            vector_labour_brexit.m[6:nrow(vector_labour_brexit.m),])
</code>```

The desired result is obviously 1,2,3,4,5,5000,6,7,8,9, yet I get 1,5000,6. Where is my mistake?

答:
Your problem is that when indexing data.frames that only have one column in the result, the returned value is simplified to a vector which confuses rbind. To be safe you can do

```<code>vector_labour_brexit.m <- data.frame("value" = c(1,2,3,4,5,6,7,8,9))

temp <- rbind(vector_labour_brexit.m[1:5,,drop=FALSE],
              data.frame("value"=5000),
              vector_labour_brexit.m[6:nrow(vector_labour_brexit.m),,drop=FALSE])
</code>```

Body:
I want to add a row to a dataframe in R at a specific position. I am aware that there are solutions for this on this site, yet they don't seem to work. I know rbind is rather slow, but given that I only need to do it for a single element it doesn't matter:

Example:

vector_labour_brexit.m <- data.frame("value" = c(1,2,3,4,5,6,7,8,9))

temp <- rbind(vector_labour_brexit.m[1:5,], data.frame("value"=5000),
                            vector_labour_brexit.m[6:nrow(vector_labour_brexit.m),])

The desired result is obviously 1,2,3,4,5,5000,6,7,8,9, yet I get 1,5000,6. Where is my mistake?

Body:
Your problem is that when indexing data.frames that only have one column in the result, the returned value is simplified to a vector which confuses rbind. To be safe you can do

vector_labour_brexit.m <- data.frame("value" = c(1,2,3,4,5,6,7,8,9))

temp <- rbind(vector_labour_brexit.m[1:5,,drop=FALSE],
              data.frame("value"=5000),
              vector_labour_brexit.m[6:nrow(vector_labour_brexit.m),,drop=FALSE])


问:
ReactJs: Is it possible to retrieve the edited value inside this tag  {this.state.value} 	 tag
I have searched in many different stackOverflow questions and native html documentation and apparantly there's no way to retrieve the value inside a  :

```<code><td contentEditable='true'> {this.state.value}  </td>
</code>```

Apparently there's no native way to retrieve the edited value by the user?

In my app:

After the user clicks on the green button, I set the contentEditable attribute to true and hence he is able to edit the right column. However, I've found myself stuck when I wanted to retrieve the new value that the user has typed to send it to the backend!

But this doesn't make any sense, because what's the use of the attribute contentEditable if I cannot retrieve the edited value?

I have only found the onClick listener which I can use to learn when the user has clicked on a particular cell.

PS: I remember in Angular I used to do this easily with two-way data binding..

答: Instead of {this.state.value} your code should use a component that supports entering information through it. For example, textarea and use its related event functions to send the info to the server.</p>

Title: ReactJs: Is it possible to retrieve the edited value inside this tag <td contentEditable='true'> {this.state.value} </td> tag

Body:
I have searched in many different stackOverflow questions and native html documentation and apparantly there's no way to retrieve the value inside a  :

 {this.state.value}

Apparently there's no native way to retrieve the edited value by the user?

In my app:

After the user clicks on the green button, I set the contentEditable attribute to true and hence he is able to edit the right column. However, I've found myself stuck when I wanted to retrieve the new value that the user has typed to send it to the backend!

But this doesn't make any sense, because what's the use of the attribute contentEditable if I cannot retrieve the edited value?

I have only found the onClick listener which I can use to learn when the user has clicked on a particular cell.

PS: I remember in Angular I used to do this easily with two-way data binding..


问:
Is it guaranteed that the function passed to useEffect will be called at least once after the component is called, even in concurrent mode?
Except if exceptions occur of course.

I couldn't find a clear answer to this.

In their reference useSubscription hook implementation they say:

It is important not to subscribe while rendering because this can lead to memory leaks.

But it's not clear if it's possible to implement subscriptions in the body that can't lead to a memory leaks, or if subscribing in the body will, eventually, cause memory leaks if the unsubscription happens inside useEffect.

I'm especially interested in knowing if this holds true under concurrent mode.

答:
Does useEffect run after every render? Yes! By default, it runs both after the first render and after every update. (We will later talk about how to customize this.) Instead of thinking in terms of “mounting” and “updating”, you might find it easier to think that effects happen “after render”. React guarantees the DOM has been updated by the time it runs the effects.

The commit phase is usually very fast, but rendering can be slow. For this reason, the upcoming async mode (which is not enabled by default yet) breaks the rendering work into pieces, pausing and resuming the work to avoid blocking the browser. This means that React may invoke render phase lifecycles more than once before committing, or it may invoke them without committing at all (because of an error or a higher priority interruption).

Since DOM update happens in the commit phase, and there might be no commit phase at all (in case something happened) I'm guessing that NO, it is not guaranteed that what's in useEffect is called AT ALL.

note: render should not contain any side effect, including subscription as these functions might be called more than once leading to an invalid state. Use useEffect() for subscribing.

Render phase lifecycles include the following class component methods:

constructor componentWillMount (or UNSAFE_componentWillMount)

componentWillReceiveProps (or UNSAFE_componentWillReceiveProps)

componentWillUpdate (or UNSAFE_componentWillUpdate)

getDerivedStateFromProps shouldComponentUpdate

render

setState updater functions (the first argument)

Because the above methods might be called more than once, it’s important that they do not contain
side-effects. Ignoring this rule can lead to a variety of problems,
including memory leaks and invalid application state. Unfortunately,
it can be difficult to detect these problems as they can often be
non-deterministic.


问:
How to call one function app from another locally?
In Visual Studio, I have created 2 Azure function apps f1 and f2.

I have already change the port for both function apps.

I want to call f2 from f1 but I'm getting a NotFound error.

f1 is using http://localhost:999/demo1

f2 is using http://localhost:1212/demo2

答:
I have tried calling one Function to Another Function within the same project and different project too both works fine.

Function 1 Example:

 [FunctionName("Function1")]
    public static async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
        ILogger log)
    {
        log.LogInformation("C# HTTP trigger function processed a request.");
        try
        {
            //Extract Request Param

            var content = await new StreamReader(req.Body).ReadToEndAsync();
            QnAMakerQuestion objQnAMakerQuestion = JsonConvert.DeserializeObject<QnAMakerQuestion>(content);

            //Global Variable for containing message

            dynamic validationMessage;

            // Validate param

            if (string.IsNullOrEmpty(objQnAMakerQuestion.question))
            {
                validationMessage = new OkObjectResult("Question is required!");
                return (IActionResult)validationMessage;
            }
            //Selialize Request Param
            var json = JsonConvert.SerializeObject(objQnAMakerQuestion);
            var stringContent = new StringContent(json, UnicodeEncoding.UTF8, "application/json");
            // Call Function 2
            HttpClient newClient = new HttpClient();
            HttpResponseMessage responseFromAnotherFunction = await newClient.PostAsync("http://localhost:7073/api/Function2FromApp2", stringContent);
            dynamic response = "";

            if (responseFromAnotherFunction.IsSuccessStatusCode)
            {
                response = responseFromAnotherFunction.Content.ReadAsStringAsync().Result;
            }

            validationMessage = new OkObjectResult(response);
            return (IActionResult)validationMessage;
        }
        catch (Exception ex)
        {
            dynamic validationMessage = new OkObjectResult(string.Format("Something went wrong, please try agian! Reason:{0}", ex.Message));
            return (IActionResult)validationMessage;
        }
    }
```

<p><strong><em>Function 2 Example:</em></strong></p>

<pre class="lang-cs prettyprint-override"><code>  [FunctionName("Function2FromApp2")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            try
            {
                var content = await new StreamReader(req.Body).ReadToEndAsync();
                QnAMakerQuestion objQnAMakerQuestion = JsonConvert.DeserializeObject<QnAMakerQuestion>(content);

                //Global Variable for containing message

                dynamic validationMessage;

                // Validate param

                if (string.IsNullOrEmpty(objQnAMakerQuestion.question))
                {
                    validationMessage = new OkObjectResult("Question is required!");
                    return (IActionResult)validationMessage;
                }
                validationMessage = new OkObjectResult(objQnAMakerQuestion);
                return (IActionResult)validationMessage;
            }
            catch (Exception ex)
            {

                dynamic validationMessage = new OkObjectResult(string.Format("Something went wrong, please try agian! Reason:{0}", ex.Message));
                return (IActionResult)validationMessage;
            }
        }
</code>```

Class Used:

```<code>   public class QnAMakerQuestion
    {
        public string question { get; set; }

    }
</code>```

Note: If you run in same project then you wouldn't encounter any problem. But if you run in different project encounter a issue
  regarding port. To resolve that in local.settings.json file replace
  below code :

```<code>"Host": {

    "LocalHttpPort": 7073

  }
</code>```

And Update Project Properties -> Debug to following

host start --port 7073 --pause-on-error See the screen shot below:

Post Man Test:

I have invoked Function 1 on PostMan it Invoked Function 1 as Function 1 Invoked Function 2 and Send Response or vice-versa from function 2 to function 1. See the screen shot below:

Just plug and play, let me know if you have any additional question.

Body:
I have tried calling one Function to Another Function within the same project and different project too both works fine.

Function 1 Example:

 [FunctionName("Function1")]
    public static async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
        ILogger log)
    {
        log.LogInformation("C# HTTP trigger function processed a request.");
        try
        {
            //Extract Request Param

            var content = await new StreamReader(req.Body).ReadToEndAsync();
            QnAMakerQuestion objQnAMakerQuestion = JsonConvert.DeserializeObject<QnAMakerQuestion>(content);

            //Global Variable for containing message

            dynamic validationMessage;

            // Validate param

            if (string.IsNullOrEmpty(objQnAMakerQuestion.question))
            {
                validationMessage = new OkObjectResult("Question is required!");
                return (IActionResult)validationMessage;
            }
            //Selialize Request Param
            var json = JsonConvert.SerializeObject(objQnAMakerQuestion);
            var stringContent = new StringContent(json, UnicodeEncoding.UTF8, "application/json");
            // Call Function 2
            HttpClient newClient = new HttpClient();
            HttpResponseMessage responseFromAnotherFunction = await newClient.PostAsync("http://localhost:7073/api/Function2FromApp2", stringContent);
            dynamic response = "";

            if (responseFromAnotherFunction.IsSuccessStatusCode)
            {
                response = responseFromAnotherFunction.Content.ReadAsStringAsync().Result;
            }

            validationMessage = new OkObjectResult(response);
            return (IActionResult)validationMessage;
        }
        catch (Exception ex)
        {
            dynamic validationMessage = new OkObjectResult(string.Format("Something went wrong, please try agian! Reason:{0}", ex.Message));
            return (IActionResult)validationMessage;
        }
    }

Function 2 Example:

  [FunctionName("Function2FromApp2")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            try
            {
                var content = await new StreamReader(req.Body).ReadToEndAsync();
                QnAMakerQuestion objQnAMakerQuestion = JsonConvert.DeserializeObject<QnAMakerQuestion>(content);

                //Global Variable for containing message

                dynamic validationMessage;

                // Validate param

                if (string.IsNullOrEmpty(objQnAMakerQuestion.question))
                {
                    validationMessage = new OkObjectResult("Question is required!");
                    return (IActionResult)validationMessage;
                }
                validationMessage = new OkObjectResult(objQnAMakerQuestion);
                return (IActionResult)validationMessage;
            }
            catch (Exception ex)
            {

                dynamic validationMessage = new OkObjectResult(string.Format("Something went wrong, please try agian! Reason:{0}", ex.Message));
                return (IActionResult)validationMessage;
            }
        }

Class Used:

   public class QnAMakerQuestion
    {
        public string question { get; set; }

    }

Note: If you run in same project then you wouldn't encounter any problem. But if you run in different project encounter a issue
  regarding port. To resolve that in local.settings.json file replace
  below code :

"Host": {

    "LocalHttpPort": 7073

  }

And Update Project Properties -> Debug to following

host start --port 7073 --pause-on-error See the screen shot below:

Post Man Test:

I have invoked Function 1 on PostMan it Invoked Function 1 as Function 1 Invoked Function 2 and Send Response or vice-versa from function 2 to function 1. See the screen shot below:

Just plug and play, let me know if you have any additional question.


问:
JavaScript do not allow dot as first when highlighted and inserted
I'm trying to validate the input field that is only for numbers and decimals. But the dot can't be first! All works fine except when someone select/highlight the input value and hit dot then the dot is added as first. Try highlighting 0 and click dot(.) it will let you insert it as first. Any idea?

function isNumberKey(evt, obj) {
  var charCode = (evt.which) ? evt.which : evt.keyCode
  var value = obj.value;
  var dotcontains = value.indexOf(".") != -1;
  if ((value.length==0) && (event.keyCode==46)) return false; // checking that length ==0 than not allow to enter '.'
  if (dotcontains)
    if (charCode == 46) return false;
  if (charCode == 46) return true;
  if (charCode > 31 && (charCode < 48 || charCode > 57))
    return false;
  return true;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><INPUT TYPE="TEXT" VALUE="0" onkeypress="return isNumberKey(event,this)">
    </code>```

答:
The reason that your value.length==0 check isn't applying is because your previous value (0) made the length 1. But you could expand this idea, and check to see if the portion being edited starts with position 0.

```<code>if (evt.target.selectionStart === 0 && (evt.keyCode==46)) return false;
</code>```

This will catch both a highlighted section being edited that starts with the first position, as well as the cursor just being there.

https://jsfiddle.net/nyzkdb81/9/

Body:
I'm trying to validate the input field that is only for numbers and decimals. But the dot can't be first! All works fine except when someone select/highlight the input value and hit dot then the dot is added as first. Try highlighting 0 and click dot(.) it will let you insert it as first. Any idea?

function isNumberKey(evt, obj) {
  var charCode = (evt.which) ? evt.which : evt.keyCode
  var value = obj.value;
  var dotcontains = value.indexOf(".") != -1;
  if ((value.length==0) && (event.keyCode==46)) return false; // checking that length ==0 than not allow to enter '.'
  if (dotcontains)
    if (charCode == 46) return false;
  if (charCode == 46) return true;
  if (charCode > 31 && (charCode < 48 || charCode > 57))
    return false;
  return true;
}

<INPUT TYPE="TEXT" VALUE="0" onkeypress="return isNumberKey(event,this)">

Body:
The reason that your value.length==0 check isn't applying is because your previous value (0) made the length 1. But you could expand this idea, and check to see if the portion being edited starts with position 0.

if (evt.target.selectionStart === 0 && (evt.keyCode==46)) return false;

This will catch both a highlighted section being edited that starts with the first position, as well as the cursor just being there.

https://jsfiddle.net/nyzkdb81/9/


问:
Can't use setTimeout to undo boolean
In my Javascript code I am trying to set up this code

```<code>    if(this.boolean == true) {
        setTimeout(function(){ this.boolean = false; }, 2000);

    }
</code>```

But for some reason it won't work, the boolean just remains true. How can I fix this/what can I do instead?
The setTimeout works with other lines of code but weirdly not this one.

答:
It's because of "this" - you can use a closure to do this:

```<code>var x = this;
var onTimeout = function(){
  x.boolean = false;
}

if(this.boolean == true) {
       setTimeout(onTimeout, 2000);
}
</code>```

"this" is not what you think it is inside the setTimeout function:

setTimeout and "this" in JavaScript

If you have ES6 available, arrow functions use their lexical scope for this

```<code>var onTimeout = () => this.boolean = false;
setTimeout(onTimeout , 2000);
</code>```

More about that here:

https://medium.com/tfogo/advantages-and-pitfalls-of-arrow-functions-a16f0835799e

Title: Can't use setTimeout to undo boolean

Body:
In my Javascript code I am trying to set up this code

    if(this.boolean == true) {
        setTimeout(function(){ this.boolean = false; }, 2000);

    }

But for some reason it won't work, the boolean just remains true. How can I fix this/what can I do instead?
The setTimeout works with other lines of code but weirdly not this one.

Body:
It's because of "this" - you can use a closure to do this:

var x = this;
var onTimeout = function(){
  x.boolean = false;
}

if(this.boolean == true) {
       setTimeout(onTimeout, 2000);
}

"this" is not what you think it is inside the setTimeout function:

setTimeout and "this" in JavaScript

If you have ES6 available, arrow functions use their lexical scope for this

var onTimeout = () => this.boolean = false;
setTimeout(onTimeout , 2000);

More about that here:

https://medium.com/tfogo/advantages-and-pitfalls-of-arrow-functions-a16f0835799e


问:
Cloning a DOM node list and accessing members are undefined
I have a DOM node list arr1 that is being cloned arr2 and I wonder whether it has been cloned properly as both behave differently. I cannot seem to access the members of arr2 as they return undefined.

Why does this happen, and how can it be fixed?

Note that I tried cloning the same array via arr.slice but this errors with Uncaught TypeError: arr.slice is not a function

Thanks for any help here - the code is below:

var arr = document.querySelectorAll('li');
console.log(arr[1]); // works

var arr2 = [].concat(arr);
console.log(arr2[1]); // undefined, & logs twice```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>test</li>
  <li>test</li>
  <li>test</li>
  <li>test</li>
  <li>test</li>
</ul></code>```

答:
As noted by Jim Thorpe you currently have a nodeList. Below is a modified snippet of your code transforming that nodeList to an array. from there array 2 is modified by extracting out the innerText of the LI giving you an array of values as an example. but at this point you could do normal array functions with the data as you choose.

const nodeList = document.querySelectorAll('li'),
  arr = Array.prototype.slice.call(nodeList); //now its an array
console.log(arr[1]); // works

const arr2 = arr.map(function (li) { return li.innerText; });
console.log(arr2[1]); // undefined, & logs twice```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>test</li>
  <li>test</li>
  <li>test</li>
  <li>test</li>
  <li>test</li>
</ul></code>```

Body:
I have a DOM node list arr1 that is being cloned arr2 and I wonder whether it has been cloned properly as both behave differently. I cannot seem to access the members of arr2 as they return undefined.

Why does this happen, and how can it be fixed?

Note that I tried cloning the same array via arr.slice but this errors with Uncaught TypeError: arr.slice is not a function

Thanks for any help here - the code is below:

var arr = document.querySelectorAll('li');
console.log(arr[1]); // works

var arr2 = [].concat(arr);
console.log(arr2[1]); // undefined, & logs twice

test

test

test

test

test

Body:
As noted by Jim Thorpe you currently have a nodeList. Below is a modified snippet of your code transforming that nodeList to an array. from there array 2 is modified by extracting out the innerText of the LI giving you an array of values as an example. but at this point you could do normal array functions with the data as you choose.

const nodeList = document.querySelectorAll('li'),
  arr = Array.prototype.slice.call(nodeList); //now its an array
console.log(arr[1]); // works

const arr2 = arr.map(function (li) { return li.innerText; });
console.log(arr2[1]); // undefined, & logs twice

<ul>
  <li>test</li>
  <li>test</li>
  <li>test</li>
  <li>test</li>
  <li>test</li>
</ul>


问:
Which (ML/DL) model is best for multi class classification for smaller datasets?
I am working with health dataset.

The dataset is about body signals (8 features) and the target variable is body failing Temperature.
There were 6 different temperatures or Multi classes. (targets)

My data set is of shape (1500*9) -  Numerical Data

I fitted my data with RMClassifier, but it shows a accuracy of around 80%
But i needed my accuracy & F1 score to be improved even more.
On the other hand I am tweaking some parameters for better accuracy.

Apart from Random Forest, I would like to get some suggestion, which model would be the best choice fr my above problem.  Since my dataset is small, I am not sure about selecting the best ML model

I thought of going with boosting,SVM or Neural Nets.
Kindly share your thoughts.

答:
To find the best model for your problem you can use GridSearchCV of Scikit-learn. Use pipeline and configure the GridSearchCV to experiment with different learning methods changing their hyper-parameters. It will find the best ML model for you.

A group of researchers found with quality and quantity data the performance of different ML models vary a little (Hands-On Machine Learning with Scikit-Learn and TensorFlow, first edition, page 23). You should also spend some effort on feature engineering to see if you can increase the number of features. You can get some idea from this Titanic solution


问:
True case statements are executed even if condition is false - MySQL
I need to select a column only if that column exists.

I've tried this check in this way:

```<code>set @esisteIlCampo =
    (
        SELECT COUNT(*)
        FROM
        (
            SELECT *
            FROM information_schema.COLUMNS
            WHERE TABLE_SCHEMA = 'ventodelnord'
            AND TABLE_NAME = 'impiegati'
            AND COLUMN_NAME = 'Email'
        ) AS t
    ) > 0
</code>```

If gives 1 if the column Email exists and 0 if not.

Then I have this query to make use of it:

```<code>SELECT
    `i`.`IDImpiegato` AS `ID`,
    `i`.`TelDomicilio` AS `Numero Di Telefono`,
    CONCAT(`i`.`Nome`, ' ', `i`.`Cognome`) AS `Nome Completo`,
    (
        CASE WHEN
        @esisteIlCampo = 1
        THEN
        (
            SELECT impiegati.Email from impiegati limit 1
        )
        ELSE
        (
           SELECT "Campo Mancante"
        )
        END
    ) as "Email",
    'Impiegati' AS `Tabella di provenienza`
FROM
    `impiegati` `i`;
</code>```

But even if the @esisteIlCampo is 0, so the @esisteIlCampo = 1 evaluates to false, the SELECT impiegati.Email from impiegati limit 1 query is executed.

How is this possible?

答:
You can use this trick:

```<code>select i.*,
       (select email  -- NO qualified name on purpose!!!
        from impiegati i2
        where i2.IDImpiegato = i.IDImpiegato
      ) as email
from impiegati i cross join
     (select 'Camp Mancante' as email) x;
</code>```

This uses a scoping trick in the correlated subquery.  If the column does not exist in impiegati, then email refers to x.email.  If the column does exist, it refers to i2.impiegati -- and because of the correlation clause, this should come from the same row.

Body:
I need to select a column only if that column exists.

I've tried this check in this way:

set @esisteIlCampo =
    (
        SELECT COUNT(*)
        FROM
        (
            SELECT *
            FROM information_schema.COLUMNS
            WHERE TABLE_SCHEMA = 'ventodelnord'
            AND TABLE_NAME = 'impiegati'
            AND COLUMN_NAME = 'Email'
        ) AS t
    ) > 0

If gives 1 if the column Email exists and 0 if not.

Then I have this query to make use of it:

SELECT
    `i`.`IDImpiegato` AS `ID`,
    `i`.`TelDomicilio` AS `Numero Di Telefono`,
    CONCAT(`i`.`Nome`, ' ', `i`.`Cognome`) AS `Nome Completo`,
    (
        CASE WHEN
        @esisteIlCampo = 1
        THEN
        (
            SELECT impiegati.Email from impiegati limit 1
        )
        ELSE
        (
           SELECT "Campo Mancante"
        )
        END
    ) as "Email",
    'Impiegati' AS `Tabella di provenienza`
FROM
    `impiegati` `i`;

But even if the @esisteIlCampo is 0, so the @esisteIlCampo = 1 evaluates to false, the SELECT impiegati.Email from impiegati limit 1 query is executed.

How is this possible?

Body:
You can use this trick:

select i.*,
       (select email  -- NO qualified name on purpose!!!
        from impiegati i2
        where i2.IDImpiegato = i.IDImpiegato
      ) as email
from impiegati i cross join
     (select 'Camp Mancante' as email) x;

This uses a scoping trick in the correlated subquery.  If the column does not exist in impiegati, then email refers to x.email.  If the column does exist, it refers to i2.impiegati -- and because of the correlation clause, this should come from the same row.


问:
LiveData never gets updated
In my App i insert a couple of "route" objects using room. directly after doing the insert the app shows a new screen where i need the data.

The Problem looks like the insert takes place after the new view is already created, i insert the data by using ViewModel-> Repository -> DAO

On the next screen i observe the Data

```<code>@Query("SELECT * from RouteEntity")
fun getRoutesAsLiveData(): LiveData<List<RouteEntity>>
</code>```

How do i "sync" that the insert which seem to run after the new screen is already shown triggers the observed livedata ?

答:
As I can understand, you want to navigate to a new screen immediately after data insertion, and also want to observe the newly inserted data from the Database.

The insertion is an asynchronous operation and you may have to wait for the insertion acknowledgement callback to take the user to a new screen.

Unfortunately, LiveData doesn't support callback response for Insertion/Delete/Update operation.

As per google docs (Source), the LiveData support is N/A for One-shot write/read.
I recommend RxJava's Single wrapped with a Long object.

```<code>  @Insert(onConflict = OnConflictStrategy.REPLACE)
  fun insert(routeEntity: RouteEntity): Single<Long>
</code>```

Where Long returns the rowId for the inserted item.
With this approach, you could take the user to a new screen when you get an onSuccess() response from Single.

Title: LiveData never gets updated

Body:
In my App i insert a couple of "route" objects using room. directly after doing the insert the app shows a new screen where i need the data.

The Problem looks like the insert takes place after the new view is already created, i insert the data by using ViewModel-> Repository -> DAO

On the next screen i observe the Data

@Query("SELECT * from RouteEntity")
fun getRoutesAsLiveData(): LiveData<List<RouteEntity>>

How do i "sync" that the insert which seem to run after the new screen is already shown triggers the observed livedata ?

Body:
As I can understand, you want to navigate to a new screen immediately after data insertion, and also want to observe the newly inserted data from the Database.

The insertion is an asynchronous operation and you may have to wait for the insertion acknowledgement callback to take the user to a new screen.

Unfortunately, LiveData doesn't support callback response for Insertion/Delete/Update operation.

As per google docs (Source), the LiveData support is N/A for One-shot write/read.
I recommend RxJava's Single wrapped with a Long object.

  @Insert(onConflict = OnConflictStrategy.REPLACE)
  fun insert(routeEntity: RouteEntity): Single<Long>

Where Long returns the rowId for the inserted item.
With this approach, you could take the user to a new screen when you get an onSuccess() response from Single.


问:
NOT NULL constraint failed: food_app_recipe.user_id in django
I am getting this error i don't know what's the issue. I am very beginner in django. The error here is
NOT NULL constraint failed: food_app_recipe.user_id when i trying to post data from template. Help with the error here

Here is my Models.py

```<code>from django.db import models

    # Create your models here.
    class User(models.Model):
        name = models.CharField(max_length=20,null=True)
        email = models.CharField(max_length=100,null=True)
        date_created = models.DateTimeField(auto_now_add=True)

        def __str__(self):
            return self.name

    class Recipe(models.Model):
        name = models.CharField(max_length=50,null=True)
        steps = models.TextField(max_length=1000,null=True)
        image = models.ImageField(null = True, blank = True)
        ingredients = models.CharField(max_length=100, null=True)
        description = models.TextField(max_length=1000,null=True)
        user = models.ForeignKey(User, on_delete=models.CASCADE)

        def __str__(self):
            return self.name
</code>```

Here is my forms.py

```<code>from django import forms
from django.forms import ModelForm
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import Recipe

class SignupForm(UserCreationForm):
    username = forms.CharField(max_length=30)
    email = forms.EmailField(max_length=200)

    class Meta:
        model = User
        fields = ['username','email','password1','password2']

class RecipeForm(ModelForm):
    class Meta:
        model = Recipe
        fields = ['name','steps','image','ingredients','description']
</code>```

Here is my Views.py

```<code>from django.shortcuts import render, redirect
from .forms import SignupForm,RecipeForm
from django.contrib.auth import authenticate,login,logout
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from .models import User,Recipe

# views here

@login_required(login_url='blog-login')
def add_recipes(request):
    user = request.user
    form = RecipeForm(instance=user)
    if request.method == "POST":
        print('printing post:',request.POST)
        form = RecipeForm(request.POST,request.FILES)
        if form.is_valid():
            form.save()
            return redirect('blog-home')
    context = {'form':form}
    return render(request,'food_app/Add_recipe.html',context)
</code>```

Here is my template of that form

```<code>{% block content %}

<div class = "container mt-4">
        <div class = "row justify-content-center">
            <div class = "col-6">
                <div class = "card">
                    <div class = "card-body">
                      <form action="" method="POST" class="form">
                {% csrf_token %}
                {% bootstrap_form form %}
                {% buttons %}
                    <button type="submit" class="btn btn-primary">
                    Submit
                    </button>
                {% endbuttons %}

                    </div>
                </div>
            </div>
        </div>
</div>

{% endblock content %}
</code>```

答:
When you are trying to save your RecipeForm django tries to create a new Recipe. Your model definition for Recipe contains a mandatory user field. However, your RecipeForm does not supply this information, i.e it has no user field. This is why you get the error.

In order to solve this you can add the the user before saving the recipe to the database. You do this by using commit=False when calling form.save():

```<code>form = RecipeForm(request.POST, request.FILES)
recipe = form.save(commit=False)
recipe.user = request.user
recipe.save()
</code>```

One further remark: Your RecipeForm is a ModelForm for Recipe, passing instance=request.user does not make sense.

And @Tane comment regarding the enctype in your html form is correct

Body:
I am getting this error i don't know what's the issue. I am very beginner in django. The error here is
NOT NULL constraint failed: food_app_recipe.user_id when i trying to post data from template. Help with the error here

Here is my Models.py

from django.db import models

    # Create your models here.
    class User(models.Model):
        name = models.CharField(max_length=20,null=True)
        email = models.CharField(max_length=100,null=True)
        date_created = models.DateTimeField(auto_now_add=True)

        def __str__(self):
            return self.name

    class Recipe(models.Model):
        name = models.CharField(max_length=50,null=True)
        steps = models.TextField(max_length=1000,null=True)
        image = models.ImageField(null = True, blank = True)
        ingredients = models.CharField(max_length=100, null=True)
        description = models.TextField(max_length=1000,null=True)
        user = models.ForeignKey(User, on_delete=models.CASCADE)

        def __str__(self):
            return self.name

Here is my forms.py

from django import forms
from django.forms import ModelForm
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import Recipe

class SignupForm(UserCreationForm):
    username = forms.CharField(max_length=30)
    email = forms.EmailField(max_length=200)

    class Meta:
        model = User
        fields = ['username','email','password1','password2']

class RecipeForm(ModelForm):
    class Meta:
        model = Recipe
        fields = ['name','steps','image','ingredients','description']

Here is my Views.py

from django.shortcuts import render, redirect
from .forms import SignupForm,RecipeForm
from django.contrib.auth import authenticate,login,logout
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from .models import User,Recipe

# views here

@login_required(login_url='blog-login')
def add_recipes(request):
    user = request.user
    form = RecipeForm(instance=user)
    if request.method == "POST":
        print('printing post:',request.POST)
        form = RecipeForm(request.POST,request.FILES)
        if form.is_valid():
            form.save()
            return redirect('blog-home')
    context = {'form':form}
    return render(request,'food_app/Add_recipe.html',context)

Here is my template of that form

{% block content %}

                      <form action="" method="POST" class="form">
                {% csrf_token %}
                {% bootstrap_form form %}
                {% buttons %}
                    <button type="submit" class="btn btn-primary">
                    Submit
                    </button>
                {% endbuttons %}

{% endblock content %}

Body:
When you are trying to save your RecipeForm django tries to create a new Recipe. Your model definition for Recipe contains a mandatory user field. However, your RecipeForm does not supply this information, i.e it has no user field. This is why you get the error.

In order to solve this you can add the the user before saving the recipe to the database. You do this by using commit=False when calling form.save():

form = RecipeForm(request.POST, request.FILES)
recipe = form.save(commit=False)
recipe.user = request.user
recipe.save()

One further remark: Your RecipeForm is a ModelForm for Recipe, passing instance=request.user does not make sense.

And @Tane comment regarding the enctype in your html form is correct


答:
this behaves in a special way in JavaScript.

Change

```<code>setTimeout(function(){ this.boolean = false; }, 2000);
</code>```

to

```<code>setTimeout(() => { this.boolean = false; }, 2000);
</code>```

and the this keyword will be interpreted block-scoped.

Title: Can't use setTimeout to undo boolean

Body:
this behaves in a special way in JavaScript.

Change

setTimeout(function(){ this.boolean = false; }, 2000);

to

setTimeout(() => { this.boolean = false; }, 2000);

and the this keyword will be interpreted block-scoped.


问:
Facebook Registration linking to MySQL Database
I'm relatively new to website programming and any tips or help is much appreciated.

I have designed a golf site for my region in the UK, and I would like to implement facebook Login/Registration facebook-connect for easy access and sign-ups. I have gone over the facebook developers website a few times but goes over my head a little.

I have the login button fine, but for registration I would like to access the users information in a [tag:MySQL} database. Does anyone know how to do this? I have set parameters in the database which are:

id

fb_id

name

email

gender

birthday

location

However, it says: -

```<code>#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'near) NOT NULL, `birthday` DATE NOT NULL, `location` VARCHAR(255) NOT NULL, UNIQ' at line 1
</code>```

How can I rectify the problem and then successfully have my registration login redirect to MySQL?

Essentially I would like a separate profile for each user who can share golf stats, organise games with friends and post recent scores.

Let me know your thoughts and any tips are welcomed.

Thanks,
Darren

答: You're trying to access Facebook data with MySQL, which is not possible. Try using the native Facebook connect APIs instead.</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm relatively new to website programming and any tips or help is much appreciated.

I have designed a golf site for my region in the UK, and I would like to implement facebook Login/Registration facebook-connect for easy access and sign-ups. I have gone over the facebook developers website a few times but goes over my head a little.

I have the login button fine, but for registration I would like to access the users information in a [tag:MySQL} database. Does anyone know how to do this? I have set parameters in the database which are:

id

fb_id

name

email

gender

birthday

location

However, it says: -

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'near) NOT NULL, `birthday` DATE NOT NULL, `location` VARCHAR(255) NOT NULL, UNIQ' at line 1

How can I rectify the problem and then successfully have my registration login redirect to MySQL?

Essentially I would like a separate profile for each user who can share golf stats, organise games with friends and post recent scores.

Let me know your thoughts and any tips are welcomed.

Thanks,
Darren


问:
CondaHTTPError: HTTP 000 CONNECTION FAILED for url - Anaconda
I have seen other post solving through ssl_verify making it false or adding the path of the certificate. I have done every one of them. I have installed and reinstalled several times the anaconda. I have disabled my antivirus program.

I have tried every option that I find online but nothing is working for me and I still get this error.

```<code>CondaHTTPError: HTTP 000 CONNECTION FAILED for url <https://repo.anaconda.com/pkgs/main/win-64/current_repodata.json>
Elapsed: -

An HTTP error occurred when trying to retrieve this URL.
HTTP errors are often intermittent, and a simple retry will get you on your way.

If your current network has https://www.anaconda.com blocked, please file
a support request with your network engineering team.

SSLError(MaxRetryError('HTTPSConnectionPool(host=\'repo.anaconda.com\', port=443): Max retries exceeded with url: /pkgs/main/win-64/current_repodata.json (Caused by SSLError("Can\'t connect to HTTPS URL because the SSL module is not available."))'))
</code>```

I'm not sure what I'm should be doing?

答:
I strongly recommend to copy libcrypto-1_1-x64.* libssl-1_1-x64.* from .\Library in Anaconda folder to .\DLL in Anaconda folder. I'm 100% sure that your problem will be solved. Please don't crack your heads looking for solution on all the platforms.
Don't try editing .condarc file and face further issues. I am sure that problem will be solved after moving the above mentioned DLL files as directed.

Body:
I have seen other post solving through ssl_verify making it false or adding the path of the certificate. I have done every one of them. I have installed and reinstalled several times the anaconda. I have disabled my antivirus program.

I have tried every option that I find online but nothing is working for me and I still get this error.

CondaHTTPError: HTTP 000 CONNECTION FAILED for url <https://repo.anaconda.com/pkgs/main/win-64/current_repodata.json>
Elapsed: -

An HTTP error occurred when trying to retrieve this URL.
HTTP errors are often intermittent, and a simple retry will get you on your way.

If your current network has https://www.anaconda.com blocked, please file
a support request with your network engineering team.

SSLError(MaxRetryError('HTTPSConnectionPool(host=\'repo.anaconda.com\', port=443): Max retries exceeded with url: /pkgs/main/win-64/current_repodata.json (Caused by SSLError("Can\'t connect to HTTPS URL because the SSL module is not available."))'))

I'm not sure what I'm should be doing?


问:
threejs mesh with alpha mask, cast shadow
A single plane with an alpha mask must cast shadows. It does but for the whole plane- not applying the alpha mask-.

Searching around I've found that adding a customDeptMaterial to the mesh should do it:

```<code>var customDepthMaterial = new THREE.MeshDepthMaterial( {
            depthPacking: THREE.RGBADepthPacking,
            alphaMap: alphaTex,
            alphaTest: 0.5
        } );
figures.customDepthMaterial = customDepthMaterial;
</code>```

Not that I am very sure of what's going on exactly but I must be missing something because it keeps casting the whole plane

Please see the complete fiddle:
https://jsfiddle.net/truji7/gj7az9eo/34/

How can I cast the "alpha filtered" shadow?

答:
PointLights are the only type of light that utilizes MeshDistanceMaterial instead of MeshDepthMaterial.

```<code>object.customDistanceMaterial = new THREE.MeshDistanceMaterial( {
    alphaMap: alphaTex,
    alphaTest: 0.5,
}
</code>```

JSFiddle Example

Body:
A single plane with an alpha mask must cast shadows. It does but for the whole plane- not applying the alpha mask-.

Searching around I've found that adding a customDeptMaterial to the mesh should do it:

var customDepthMaterial = new THREE.MeshDepthMaterial( {
            depthPacking: THREE.RGBADepthPacking,
            alphaMap: alphaTex,
            alphaTest: 0.5
        } );
figures.customDepthMaterial = customDepthMaterial;

Not that I am very sure of what's going on exactly but I must be missing something because it keeps casting the whole plane

Please see the complete fiddle:
https://jsfiddle.net/truji7/gj7az9eo/34/

How can I cast the "alpha filtered" shadow?

Body:
PointLights are the only type of light that utilizes MeshDistanceMaterial instead of MeshDepthMaterial.

object.customDistanceMaterial = new THREE.MeshDistanceMaterial( {
    alphaMap: alphaTex,
    alphaTest: 0.5,
}

JSFiddle Example


问:
When should one use Environment.Exit to terminate a console application?
I'm maintaining a number of console applications at work and one thing I've been noticing in a number of them is that they call Environment.Exit(0).

A sample program would look like this:

```<code>public class Program
{
    public static void Main(string[] args)
    {
        DoStuff();
        Environment.Exit(0);
    }
}
</code>```

I don't understand what the intent of the original programmer was in doing this? In my mind even without the Environment.Exit statement the program should exit just fine. That said, for one of these programs, it's console window has been remaining even after it was supposed to have closed so I'm really not sure what's going on there....

Am I missing something here? Or is there a reason why Environment.Exit should be called in this instance?

答:
I'm currently using Environment.Exit() in a console application where I don't want to throw ugly exception text back to the console. Instead, I just notice the condition, write a user-friendly message to the screen about what happened and then call Environment.Exit().

Otherwise, you shouldn't need to call it from Main() in a basic console application.

OwnerDisplayName: mezoid

ContentLicense: CC BY-SA 2.5

Body:
I'm maintaining a number of console applications at work and one thing I've been noticing in a number of them is that they call Environment.Exit(0).

A sample program would look like this:

public class Program
{
    public static void Main(string[] args)
    {
        DoStuff();
        Environment.Exit(0);
    }
}

I don't understand what the intent of the original programmer was in doing this? In my mind even without the Environment.Exit statement the program should exit just fine. That said, for one of these programs, it's console window has been remaining even after it was supposed to have closed so I'm really not sure what's going on there....

Am I missing something here? Or is there a reason why Environment.Exit should be called in this instance?


问:
Objective-c "multiple" getters and binding
I have a class that holds some information and one member is a property options (an NSUInteger). The individual bits of options should be accessible through property getters and setters, to be value-bound to checkboxes:

```<code>#define OP_CHAN_TAG   12

@interface MuxConfig: NSObject

@property NSUInteger options;
@property (nonatomic) BOOL opTagBlocks;

@end

@implementation MuxConfig

- (BOOL) isOpTagBlocks
{
  return (_options & (1 << OP_CHAN_TAG));
}

- (void) setOpTagBlocks:(BOOL)op
{
  if (op)
    _options |= (1 << OP_CHAN_TAG);
  else
    _options &= ~(1 << OP_CHAN_TAG);
}

@end
</code>```

In this example, a checkbox has a value binding to opTagBlocks and an action handler to send the entire options property to a hardware device. This mechanism works. Another part of the application can receive the options from said device and stores them as one word into property options. And I was hoping that the checkbox(es) got updated but they don't. Obviously accessing property options does not 'trigger' the bitwise option handler(s).
So the big question is: how can I make this work?

答:
Got is working. It appears that

```<code>- (BOOL) isOpTagBlocks
{
  return (_options & (1 << OP_CHAN_TAG));
}
</code>```

needed to be changed into:

```<code>- (BOOL) opTagBlocks
{
  return ((_options & (1 << OP_CHAN_TAG)) > 0);
}
</code>```

Quite remarkable because the documentation says that boolean getters should start with "is" but this is not accepted by the KVO mechanism.
Regarding the returned value: checking against 0 is of course better but from the embedded world I live in, anything non-zero may be returned for a boolean result. Apparently not in Objective-C.

Body:
I have a class that holds some information and one member is a property options (an NSUInteger). The individual bits of options should be accessible through property getters and setters, to be value-bound to checkboxes:

#define OP_CHAN_TAG   12

@interface MuxConfig: NSObject

@property NSUInteger options;
@property (nonatomic) BOOL opTagBlocks;

@end

@implementation MuxConfig

- (BOOL) isOpTagBlocks
{
  return (_options & (1 << OP_CHAN_TAG));
}

- (void) setOpTagBlocks:(BOOL)op
{
  if (op)
    _options |= (1 << OP_CHAN_TAG);
  else
    _options &= ~(1 << OP_CHAN_TAG);
}

@end

In this example, a checkbox has a value binding to opTagBlocks and an action handler to send the entire options property to a hardware device. This mechanism works. Another part of the application can receive the options from said device and stores them as one word into property options. And I was hoping that the checkbox(es) got updated but they don't. Obviously accessing property options does not 'trigger' the bitwise option handler(s).
So the big question is: how can I make this work?

Body:
Got is working. It appears that

- (BOOL) isOpTagBlocks
{
  return (_options & (1 << OP_CHAN_TAG));
}

needed to be changed into:

- (BOOL) opTagBlocks
{
  return ((_options & (1 << OP_CHAN_TAG)) > 0);
}

Quite remarkable because the documentation says that boolean getters should start with "is" but this is not accepted by the KVO mechanism.
Regarding the returned value: checking against 0 is of course better but from the embedded world I live in, anything non-zero may be returned for a boolean result. Apparently not in Objective-C.


问:
How to find a word from arrays of characters?
What is the best way to solve this:

I have a group of arrays with 3-4 characters inside each like so:

```<code>{p,     {a,    {t,    {m,
 q,      b,     u,     n,
 r,      c      v      o
 s      }      }      }
}
</code>```

I also have an array of dictionary words.

What is the best/fastest way to find if the array of characters can combine to form one of the dictionary words? For example, the above arrays could make the words:

"pat","rat","at","to","bum"(lol)
but not "nub" or "mat"

Should i loop through the dictionary to see if words can be made or get all the combinations from the letters then compare those to the dictionary

答:
The reformulated question can be answered just by generating and testing.  Since you have 4 letters and 10 arrays, you've only got about 1 million possible combinations (10 million if you allow a blank character). You'll need an efficient way to look them up, use a BDB or some sort of disk based hash.

The trie solution previously posted should work as well, you are just restricted more by what characters you can choose at each step of the search. It should be faster as well.

Body:
What is the best way to solve this:

I have a group of arrays with 3-4 characters inside each like so:

{p,     {a,    {t,    {m,
 q,      b,     u,     n,
 r,      c      v      o
 s      }      }      }
}

I also have an array of dictionary words.

What is the best/fastest way to find if the array of characters can combine to form one of the dictionary words? For example, the above arrays could make the words:

"pat","rat","at","to","bum"(lol)
but not "nub" or "mat"

Should i loop through the dictionary to see if words can be made or get all the combinations from the letters then compare those to the dictionary


问:
How to remove N+1 queries
I have a rails API that currently has quite a few N+1 queries that I'd like to reduce.

As you can see it's going through quite a few loops before returning the data.

The relationships are as follows:

Company Model

```<code>class Company < ApplicationRecord
  has_many :jobs, dependent: :destroy
  has_many :contacts, dependent: :destroy
  has_many :listings
end
</code>```

Job Model

```<code>class Job < ApplicationRecord
  belongs_to :company
  has_many :listings
  has_and_belongs_to_many :technologies
  has_and_belongs_to_many :tools

  scope :category, -> ( category ) { where category: category }
end
</code>```

Listing Modal

```<code>class Listing < ApplicationRecord
  belongs_to :job, dependent: :destroy
  belongs_to :company, dependent: :destroy

  scope :is_active, -> ( active ) { where is_active: active }
end
</code>```

Job Serializer

```<code>class SimpleJobSerializer < ActiveModel::Serializer
  attributes  :id,
              :title,
              :company_name,

  attribute :technology_list, if: :technologies_exist
  attribute :tool_list, if: :tools_exist

  def technology_list
    custom_technologies = []

    object.technologies.each do |technology|
      custom_technology = { label: technology.label, icon: technology.icon }
      custom_technologies.push(custom_technology)
    end

    return custom_technologies
  end

  def tool_list
    custom_tools = []

    object.tools.each do |tool|
      custom_tool = { label: tool.label, icon: tool.icon }
      custom_tools.push(custom_tool)
    end

    return custom_tools
  end

  def tools_exist
    return object.tools.any?
  end

  def technologies_exist
    return object.technologies.any?
  end

  def company_name
    object.company.name
  end
end
</code>```

Current query in controller

```<code>Job.eager_load(:listings).order("listings.live_date DESC").where(category: "developer", listings: { is_active: true }).first(90)
</code>```

I've tried to use eager_load to join the listings to the Jobs to make the request more efficient but i'm unsure how to handle this when some of the n+1 queries are coming from inside the serializer as it tries to look at tools and technologies.

Any help would be much appreciated!

答:
You might was well eager load tools and technologies since you know that the serializer is going to use them:

```<code>Job.eager_load(:listings, :tools, :technologies)
   .order("listings.live_date DESC")
   .where(category: "developer", listings: { is_active: true })
   .first(90)
</code>```

After that you really need to refactor that serializer. #each should only be used when you are only interested in the side effects of the iteration and not the return value. Use #map, #each_with_object, #inject etc. These calls can be optimized. return is implicit in ruby so you only explicitly return if you are bailing early.

```<code>class SimpleJobSerializer < ActiveModel::Serializer
  # ...
  def tool_list
    object.tools.map { |t| { label: tool.label, icon: tool.icon } }
  end
  # ...
end
</code>```

Title: How to remove N+1 queries

Body:
I have a rails API that currently has quite a few N+1 queries that I'd like to reduce.

As you can see it's going through quite a few loops before returning the data.

The relationships are as follows:

Company Model

class Company < ApplicationRecord
  has_many :jobs, dependent: :destroy
  has_many :contacts, dependent: :destroy
  has_many :listings
end

Job Model

class Job < ApplicationRecord
  belongs_to :company
  has_many :listings
  has_and_belongs_to_many :technologies
  has_and_belongs_to_many :tools

  scope :category, -> ( category ) { where category: category }
end

Listing Modal

class Listing < ApplicationRecord
  belongs_to :job, dependent: :destroy
  belongs_to :company, dependent: :destroy

  scope :is_active, -> ( active ) { where is_active: active }
end

Job Serializer

class SimpleJobSerializer < ActiveModel::Serializer
  attributes  :id,
              :title,
              :company_name,

  attribute :technology_list, if: :technologies_exist
  attribute :tool_list, if: :tools_exist

  def technology_list
    custom_technologies = []

    object.technologies.each do |technology|
      custom_technology = { label: technology.label, icon: technology.icon }
      custom_technologies.push(custom_technology)
    end

    return custom_technologies
  end

  def tool_list
    custom_tools = []

    object.tools.each do |tool|
      custom_tool = { label: tool.label, icon: tool.icon }
      custom_tools.push(custom_tool)
    end

    return custom_tools
  end

  def tools_exist
    return object.tools.any?
  end

  def technologies_exist
    return object.technologies.any?
  end

  def company_name
    object.company.name
  end
end

Current query in controller

Job.eager_load(:listings).order("listings.live_date DESC").where(category: "developer", listings: { is_active: true }).first(90)

I've tried to use eager_load to join the listings to the Jobs to make the request more efficient but i'm unsure how to handle this when some of the n+1 queries are coming from inside the serializer as it tries to look at tools and technologies.

Any help would be much appreciated!

Body:
You might was well eager load tools and technologies since you know that the serializer is going to use them:

Job.eager_load(:listings, :tools, :technologies)
   .order("listings.live_date DESC")
   .where(category: "developer", listings: { is_active: true })
   .first(90)

After that you really need to refactor that serializer. #each should only be used when you are only interested in the side effects of the iteration and not the return value. Use #map, #each_with_object, #inject etc. These calls can be optimized. return is implicit in ruby so you only explicitly return if you are bailing early.

class SimpleJobSerializer < ActiveModel::Serializer
  # ...
  def tool_list
    object.tools.map { |t| { label: tool.label, icon: tool.icon } }
  end
  # ...
end


问:
Memory leak in WkWebView instantiation
I have a Viewcontroller which contains wkwebview when I pop it from the navigation controller I get memory leak

The stack trace leads WkWebview instantiation

I am not using any delegates as well.

I am really wondering what causes this and how to fix this

答:
It is not observed for a long time (at least I can't remember when I met it last time). Just tested in Xcode 11.2 / iOS 13.2. No leaks - neither in simple test project nor in Playground.

Thus, I assume it should be analysed real usage, which introduces leak.

Title: Memory leak in WkWebView instantiation


答:
You get the .slice is not a function error, because .querySelectorAll does not return an Array – it returns a NodeList. A NodeList is an array-like object that doesn't share the interface an Array has.

You can convert the NodeList to a real Array like so:

```<code>Array.from(document.querySelectorAll('li'))
</code>```

Or you might use spreading:

```<code>var arr2 = [...arr];
</code>```

Title: Cloning a DOM node list and accessing members are undefined

Body:
I have a DOM node list arr1 that is being cloned arr2 and I wonder whether it has been cloned properly as both behave differently. I cannot seem to access the members of arr2 as they return undefined.

Why does this happen, and how can it be fixed?

Note that I tried cloning the same array via arr.slice but this errors with Uncaught TypeError: arr.slice is not a function

Thanks for any help here - the code is below:

var arr = document.querySelectorAll('li');
console.log(arr[1]); // works

var arr2 = [].concat(arr);
console.log(arr2[1]); // undefined, & logs twice

test

test

test

test

test

Body:
You get the .slice is not a function error, because .querySelectorAll does not return an Array – it returns a NodeList. A NodeList is an array-like object that doesn't share the interface an Array has.

You can convert the NodeList to a real Array like so:

Array.from(document.querySelectorAll('li'))

Or you might use spreading:

var arr2 = [...arr];


问:
SUSER_SID support for Azure SQL
SUSER_SID has two optional parameters. I am using only first 'login'. Documentation for it applies to Azure SQL Database, but it doesn't work. For 'login' parameter is says "Applies to: SQL Server 2008 and later".

When I call SELECT SUSER_SID('test');
using SSMS, I get the error:

'SUSER_SID' cannot be invoked with parameters in this version of SQL Server.

I am using Azure SQL Server ver. 12.0.2000.8

How is that possible, what am I missing?

答:
Odd, this isn't actually documented but I get the same problem. (Will raise this on the document's GitHub).

If you want the sid you could use sys.database_principals instead:

```<code>SELECT dp.sid
FROM sys.database_principals dp
WHERE dp.name = N'test';
</code>```

Title: SUSER_SID support for Azure SQL

Body:
Odd, this isn't actually documented but I get the same problem. (Will raise this on the document's GitHub).

If you want the sid you could use sys.database_principals instead:

SELECT dp.sid
FROM sys.database_principals dp
WHERE dp.name = N'test';


答:
If you are not using arrow function, the this variable will be the one from setTimeout and not your main class because of its scope.

The following should resolve the issue.

```<code>    if(this.boolean == true) {
        setTimeout(() => { this.boolean = false; }, 2000);

    }
</code>```

Title: Can't use setTimeout to undo boolean

Body:
In my Javascript code I am trying to set up this code

    if(this.boolean == true) {
        setTimeout(function(){ this.boolean = false; }, 2000);

    }

But for some reason it won't work, the boolean just remains true. How can I fix this/what can I do instead?
The setTimeout works with other lines of code but weirdly not this one.

Body:
If you are not using arrow function, the this variable will be the one from setTimeout and not your main class because of its scope.

The following should resolve the issue.

    if(this.boolean == true) {
        setTimeout(() => { this.boolean = false; }, 2000);

    }


答:
There are probably many way of solving this.

What you are interested in is the number of each character you have available to form a word, and how many of each character is required for each dictionary word.  The trick is how to efficiently look up this information in the dictionary.

Perhaps you can use a prefix tree (a trie), some kind of smart hash table, or similar.

Anyway, you will probably have to try out all your possibilities and check them against the dictionary.  I.e., if you have three arrays of three values each, there will be 3^3+3^2+3^1=39 combinations to check out.  If this process is too slow, then perhaps you could stick a Bloom filter in front of the dictionary, to quickly check if a word is definitely not in the dictionary.

EDIT: Anyway, isn't this essentially the same as Scrabble?  Perhaps try Googling for "scrabble algorithm" will give you some good clues.

Title: How to find a word from arrays of characters?


问:
Regex not contain at end and start differents string
i want to take only mail address which not contains 'xxx-' at the start and '@test.com' at the end of the mail string.

Here my code :

```<code>->where('email', 'regexp', "/^((?!@test.com).)*$/i")
</code>```

Here i take only email where not  contains 'test.com' at the end.
I want to not take email where the start is 'xxx-' too. Anyone know how to do this ?
Thank you !

答:
You may use this regex with 2 negative lookahead assertions (rules):

```<code>^(?!xxx-)(?![^@]+@test\.com$)[^@]+@[^@]+$
</code>```

RegEx Demo

RegEx Details:

^: Start

(?!xxx-): Don't allow email to start with xxx-

(?![^@]+@test\.com$): Don't allow email to end with test.com

[^@]+@[^@]+: Match an email that must have only one @

$: End

Body:
i want to take only mail address which not contains 'xxx-' at the start and '@test.com' at the end of the mail string.

Here my code :

->where('email', 'regexp', "/^((?!@test.com).)*$/i")

Here i take only email where not  contains 'test.com' at the end.
I want to not take email where the start is 'xxx-' too. Anyone know how to do this ?
Thank you !

Body:
You may use this regex with 2 negative lookahead assertions (rules):

^(?!xxx-)(?![^@]+@test\.com$)[^@]+@[^@]+$

RegEx Demo

RegEx Details:

^: Start

(?!xxx-): Don't allow email to start with xxx-

(?![^@]+@test\.com$): Don't allow email to end with test.com

[^@]+@[^@]+: Match an email that must have only one @

$: End


问:
Functions that return functions with parameters in Go?
I've done this in JS, unsure if it's possible in Go, but I'm looking to return a function as the return type from a function that has parameters.

Example

```<code>func StoreTask(db *sql.DB) func(rw http.ResponseWriter, r *http.Request) {
    return func(rw, r) {
        fmt.Printf("This is the store task GET request %s", strings.Split(r.URL.Path, "/")[1])
        for _, val := range r.URL.Query() {
            fmt.Printf("Current val is: %s\n", val[0])
        }
    }
}
</code>```

The way this would be invoked would be like the following:
thing := StoreTask(myDb) then I could invoke this as a handler via the HTTP library for later uses.

答:
You can do that with the following syntax:

```<code>func StoreTask(db *sql.DB) func(http.ResponseWriter, *http.Request) {
  return func(wr http.ResponseWriter, r *http.Request) {
    fmt.Printf("This is the store task GET request %s", strings.Split(r.URL.Path, "/")[1])
    for _, val := range r.URL.Query() {
        fmt.Printf("Current val is: %s\n", val[0])
    }
  }
}
</code>```

Here, StoreTask returns a function that gets an HTTP handler, and that handler can also use the db argument passed into StoreTask.

Body:
I've done this in JS, unsure if it's possible in Go, but I'm looking to return a function as the return type from a function that has parameters.

Example

func StoreTask(db *sql.DB) func(rw http.ResponseWriter, r *http.Request) {
    return func(rw, r) {
        fmt.Printf("This is the store task GET request %s", strings.Split(r.URL.Path, "/")[1])
        for _, val := range r.URL.Query() {
            fmt.Printf("Current val is: %s\n", val[0])
        }
    }
}

The way this would be invoked would be like the following:
thing := StoreTask(myDb) then I could invoke this as a handler via the HTTP library for later uses.

Body:
You can do that with the following syntax:

func StoreTask(db *sql.DB) func(http.ResponseWriter, *http.Request) {
  return func(wr http.ResponseWriter, r *http.Request) {
    fmt.Printf("This is the store task GET request %s", strings.Split(r.URL.Path, "/")[1])
    for _, val := range r.URL.Query() {
        fmt.Printf("Current val is: %s\n", val[0])
    }
  }
}

Here, StoreTask returns a function that gets an HTTP handler, and that handler can also use the db argument passed into StoreTask.


问:
Can't use setTimeout to undo boolean
In my Javascript code I am trying to set up this code

```<code>    if(this.boolean == true) {
        setTimeout(function(){ this.boolean = false; }, 2000);

    }
</code>```

But for some reason it won't work, the boolean just remains true. How can I fix this/what can I do instead?
The setTimeout works with other lines of code but weirdly not this one.

答:
Functions have their own this, so this.boolean inside of function implies that you are trying to change the property boolean of the function itself. On the other hand, if you use arrow functions, you can avoid that because arrow functions don't have their own this.

```<code>setTimeout(() => { this.boolean = false }, 2000)
</code>```

Title: Can't use setTimeout to undo boolean

Body:
Functions have their own this, so this.boolean inside of function implies that you are trying to change the property boolean of the function itself. On the other hand, if you use arrow functions, you can avoid that because arrow functions don't have their own this.

setTimeout(() => { this.boolean = false }, 2000)


问:
How tab works in Java?
I came across a weired situation while using tabs. Mostly tabs are made up of 8 or 4 spaces. But lets say right now its 8

For example

```<code>"abc"+"\t"+"bcd"      -> abc        bcd
"abcderft"+"\t"+"bcd" -> abcderft   bcd
</code>```

Why am getting differences in tab distance between two strings ?

Checked this post too

```<code>https://stackoverflow.com/questions/6000810/printing-with-t-tabs-does-not-result-in-aligned-columns
</code>```

Didnt clear much.

Even if tab is equivalent to 8 spaces, then why its considering the string count ? I mean if my string length is 3 then next string am getting after only 5 spaces, and if string length is 8 then next string is coming after 8 characters.

Does tabs includes the string length too post which its being added ?

答:
Tabs are made to align text in columns.

So yes they are multiple spaces from an empty start of the line, but not anymore following some text, as they'll go to say the next columns multiple of 8 (or 4).

So as you guessed, they include part of the length of he text before them

Title: How tab works in Java?

Body:
I came across a weired situation while using tabs. Mostly tabs are made up of 8 or 4 spaces. But lets say right now its 8

For example

"abc"+"\t"+"bcd"      -> abc        bcd
"abcderft"+"\t"+"bcd" -> abcderft   bcd

Why am getting differences in tab distance between two strings ?

Checked this post too

https://stackoverflow.com/questions/6000810/printing-with-t-tabs-does-not-result-in-aligned-columns

Didnt clear much.

Even if tab is equivalent to 8 spaces, then why its considering the string count ? I mean if my string length is 3 then next string am getting after only 5 spaces, and if string length is 8 then next string is coming after 8 characters.

Does tabs includes the string length too post which its being added ?


问:
Ion Slide Overflow
I am using ion-slide and transforming my image on second slide zooming IN and OUT and it overflows on my main slide.

Here's my main slide and the second slide is overflowing:

HTML:

```<code><ion-content>
<ion-slides>
  <ion-slide class="slide-main">
    <ion-grid>
      <ion-row class="row-main">
        <img class="img-main" src="https://cdopromos.com/wp-content/uploads/2019/07/maxs-restaurant-chicken-all-you-can.jpg">
      </ion-row>
    </ion-grid>
  </ion-slide>
  <ion-slide class="slide-secondaruy">
    <ion-grid>
      <ion-row class="row-secondary">
        <img class="img-secondary" src="https://lh3.googleusercontent.com/proxy/iP2XG4WiD4Q2U18hRlCG9375ujydwARovLR8R6HrMLVp3iyH5pteC7RHOivfo3_njckHJyN21we1qmrbc7F3Bc2ao7UyCsMeMh6AGdt4v8loHSu51bHtOEC69e7HedDHrX3A9HRnKDg">
      </ion-row>
    </ion-grid>
  </ion-slide>
</ion-slides>
</ion-content>
</code>```

CSS:

```<code>.row-main{
  height: 100vh;
  width: 100vw;
}

*{
  padding: 0;
}
.img-secondary{
  height: 100vh;
  transform: scale(1);
    animation: zoominout 30s infinite ;

}

.img-main{

}
.row-secondary{
  z-index: -1;
}
.swiper-slide{
  z-index: -1;

}

@keyframes zoominout {
  0% {
      transform: scale(1,1);
  }
  50% {
      transform: scale(1.2,1.2);
  }
  100% {
      transform: scale(1,1);
  }
}

.slide-main{
  z-index: 99;
}
</code>```

I used z-index and overflow-x:hidden but nothing happened

答:
I'm not sure if using the <ion-grid> is necessary, but if you structure your template code like this it let's the default layout in <ion-slide> structure your content.

html

```<code><ion-content>
  <ion-slides>
    <ion-slide class="slide-main">
      <img class="img-main" src="https://cdopromos.com/wp-content/uploads/2019/07/maxs-restaurant-chicken-all-you-can.jpg">
    </ion-slide>
    <ion-slide class="slide-secondary">
      <img class="img-secondary" src="https://images.pexels.com/photos/2397361/pexels-photo-2397361.jpeg?auto=compress&cs=tinysrgb&dpr=2&w=500">
    </ion-slide>
  </ion-slides>
</ion-content>
</code>```

In your scss of the component go ahead and tell the <ion-slide> to hide anything outside of its containing boundary.

```<code>/**
Add this to your scss
 */
ion-slide {
  overflow-x: hidden!important; // or overflow: hidden or overflow-y: hidden
}
/**
Add this to your scss
 */

.row-main{
  height: 100vh;
  width: 100vw;
}

*{
  padding: 0;
}
.img-secondary{
  height: 100vh;
  transform: scale(1);
  animation: zoominout 30s infinite ;

}

.img-main{

}
.row-secondary{
  z-index: -1;
}
.swiper-slide{
  z-index: -1;

}

@keyframes zoominout {
  0% {
    transform: scale(1,1);
  }
  50% {
    transform: scale(1.2,1.2);
  }
  100% {
    transform: scale(1,1);
  }
}

.slide-main{
  z-index: 99;
}
</code>```

The end result looks like this.

Title: Ion Slide Overflow

Body:
I am using ion-slide and transforming my image on second slide zooming IN and OUT and it overflows on my main slide.

Here's my main slide and the second slide is overflowing:

HTML:

<ion-content>
<ion-slides>
  <ion-slide class="slide-main">
    <ion-grid>
      <ion-row class="row-main">

      </ion-row>
    </ion-grid>
  </ion-slide>
  <ion-slide class="slide-secondaruy">
    <ion-grid>
      <ion-row class="row-secondary">

      </ion-row>
    </ion-grid>
  </ion-slide>
</ion-slides>
</ion-content>

CSS:

.row-main{
  height: 100vh;
  width: 100vw;
}

*{
  padding: 0;
}
.img-secondary{
  height: 100vh;
  transform: scale(1);
    animation: zoominout 30s infinite ;

}

.img-main{

}
.row-secondary{
  z-index: -1;
}
.swiper-slide{
  z-index: -1;

}

@keyframes zoominout {
  0% {
      transform: scale(1,1);
  }
  50% {
      transform: scale(1.2,1.2);
  }
  100% {
      transform: scale(1,1);
  }
}

.slide-main{
  z-index: 99;
}

I used z-index and overflow-x:hidden but nothing happened

Body:
I'm not sure if using the <ion-grid> is necessary, but if you structure your template code like this it let's the default layout in <ion-slide> structure your content.

html

<ion-content>
  <ion-slides>
    <ion-slide class="slide-main">
      <img class="img-main" src="https://cdopromos.com/wp-content/uploads/2019/07/maxs-restaurant-chicken-all-you-can.jpg">
    </ion-slide>
    <ion-slide class="slide-secondary">
      <img class="img-secondary" src="https://images.pexels.com/photos/2397361/pexels-photo-2397361.jpeg?auto=compress&cs=tinysrgb&dpr=2&w=500">
    </ion-slide>
  </ion-slides>
</ion-content>

In your scss of the component go ahead and tell the <ion-slide> to hide anything outside of its containing boundary.

/**
Add this to your scss
 */
ion-slide {
  overflow-x: hidden!important; // or overflow: hidden or overflow-y: hidden
}
/**
Add this to your scss
 */

.row-main{
  height: 100vh;
  width: 100vw;
}

*{
  padding: 0;
}
.img-secondary{
  height: 100vh;
  transform: scale(1);
  animation: zoominout 30s infinite ;

}

.img-main{

}
.row-secondary{
  z-index: -1;
}
.swiper-slide{
  z-index: -1;

}

@keyframes zoominout {
  0% {
    transform: scale(1,1);
  }
  50% {
    transform: scale(1.2,1.2);
  }
  100% {
    transform: scale(1,1);
  }
}

.slide-main{
  z-index: 99;
}

The end result looks like this.


问:
Why is printf with a single argument (without conversion specifiers) deprecated?
In a book that I'm reading, it's written that printf with a single argument (without conversion specifiers) is deprecated. It recommends to substitute

```<code>printf("Hello World!");
</code>```

with

```<code>puts("Hello World!");
</code>```

or

```<code>printf("%s", "Hello World!");
</code>```

Can someone tell me why printf("Hello World!"); is wrong? It is written in the book that it contains vulnerabilities. What are these vulnerabilities?

答:
Beside the other well-explained answers with any side-concerns covered, I would like to give a precise and concise answer to the provided question.

Why is printf with a single argument (without conversion specifiers) deprecated?

A printf function call with a single argument in general is not deprecated and has also no vulnerabilities when used properly as you always shall code.

C Users amongst the whole world, from status beginner to status expert use printf that way to give a simple text phrase as output to the console.

Furthermore, Someone have to distinguish whether this one and only argument is a string literal or a pointer to a string, which is valid but commonly not used. For the latter, of course, there can occur inconvenient outputs or any kind of Undefined Behavior, when the pointer is not set properly to point to a valid string but these things can also occur if the format specifiers are not matching the respective arguments by giving multiple arguments.

Of course, It is also not right and proper that the string, provided as one and only argument, has any format or conversion specifiers, since there is no conversion going to be happen.

That said, giving a simple string literal like "Hello World!" as only argument without any format specifiers inside that string like you provided it in the question:

```<code>printf("Hello World!");
</code>```

is not deprecated or "bad practice" at all nor has any vulnerabilities.

In fact, many C programmers begin and began to learn and use C or even programming languages in general with that HelloWorld-program and this printf statement as first ones of its kind.

They wouldn´t be that if they were deprecated.

In a book that I'm reading, it's written that printf with a single argument (without conversion specifiers) is deprecated.

Well, then I would take the focus on the book or the author itself. If an author is really doing such, in my opinion, incorrect assertions and even teaching that without explicitly explaining why he/she is doing so (if those assertions are really literally equivalent provided in that book), I would consider it a bad book. A good book, as opposed to that, shall explain why to avoid certain kind of programming methods or functions.

According to what I said above, using printf with only one argument (a string literal) and without any format specifiers  is not in any case deprecated or considered as "bad practice".

You should ask the author, what he meant with that or even better, mind him to clarify or correct the relative section for the next edition or imprints in general.

Body:
In a book that I'm reading, it's written that printf with a single argument (without conversion specifiers) is deprecated. It recommends to substitute

printf("Hello World!");

with

puts("Hello World!");

or

printf("%s", "Hello World!");

Can someone tell me why printf("Hello World!"); is wrong? It is written in the book that it contains vulnerabilities. What are these vulnerabilities?

Body:
Beside the other well-explained answers with any side-concerns covered, I would like to give a precise and concise answer to the provided question.

Why is printf with a single argument (without conversion specifiers) deprecated?

A printf function call with a single argument in general is not deprecated and has also no vulnerabilities when used properly as you always shall code.

C Users amongst the whole world, from status beginner to status expert use printf that way to give a simple text phrase as output to the console.

Furthermore, Someone have to distinguish whether this one and only argument is a string literal or a pointer to a string, which is valid but commonly not used. For the latter, of course, there can occur inconvenient outputs or any kind of Undefined Behavior, when the pointer is not set properly to point to a valid string but these things can also occur if the format specifiers are not matching the respective arguments by giving multiple arguments.

Of course, It is also not right and proper that the string, provided as one and only argument, has any format or conversion specifiers, since there is no conversion going to be happen.

That said, giving a simple string literal like "Hello World!" as only argument without any format specifiers inside that string like you provided it in the question:

printf("Hello World!");

is not deprecated or "bad practice" at all nor has any vulnerabilities.

In fact, many C programmers begin and began to learn and use C or even programming languages in general with that HelloWorld-program and this printf statement as first ones of its kind.

They wouldn´t be that if they were deprecated.

In a book that I'm reading, it's written that printf with a single argument (without conversion specifiers) is deprecated.

Well, then I would take the focus on the book or the author itself. If an author is really doing such, in my opinion, incorrect assertions and even teaching that without explicitly explaining why he/she is doing so (if those assertions are really literally equivalent provided in that book), I would consider it a bad book. A good book, as opposed to that, shall explain why to avoid certain kind of programming methods or functions.

According to what I said above, using printf with only one argument (a string literal) and without any format specifiers  is not in any case deprecated or considered as "bad practice".

You should ask the author, what he meant with that or even better, mind him to clarify or correct the relative section for the next edition or imprints in general.


问:
How to submit map_blocks operation to a Client
I am trying to chunk-wise evaluate a funtion on a dask array. I can successfully do the following:

```<code>import numpy as np
import dask.array as da
arr = np.random.randint(0, 9, (4, 4))
darr = da.from_array(arr, chunks=(2, 2))

def block_mean(block):
    return np.array([[block.mean()]])
r = darr.map_blocks(block_mean)
out_arr = r.compute()
</code>```

How can I replicate this in a Client? I tried the following:

```<code>import numpy as np
import dask.array as da
arr = np.random.randint(0, 9, (4, 4))
darr = da.from_array(arr, chunks=(2, 2))

def block_mean(block):
    return np.array([[block.mean()]])
r = darr.map_blocks(block_mean)
c = Client()

# The following does not work
out = c.submit(r)
</code>```

答:
To keep this very short: you need not do anything at all; if you define a Client, it will become the default scheduler, and .compute() uses the default scheduler (unless specified).

```<code>r = darr.map_blocks(block_mean)
c = Client()
out_arr = r.compute()
</code>```

If you read the docs for submit, it expects a function - there are plenty of examples of how to use it.

Body:
I am trying to chunk-wise evaluate a funtion on a dask array. I can successfully do the following:

import numpy as np
import dask.array as da
arr = np.random.randint(0, 9, (4, 4))
darr = da.from_array(arr, chunks=(2, 2))

def block_mean(block):
    return np.array([[block.mean()]])
r = darr.map_blocks(block_mean)
out_arr = r.compute()

How can I replicate this in a Client? I tried the following:

import numpy as np
import dask.array as da
arr = np.random.randint(0, 9, (4, 4))
darr = da.from_array(arr, chunks=(2, 2))

def block_mean(block):
    return np.array([[block.mean()]])
r = darr.map_blocks(block_mean)
c = Client()

# The following does not work
out = c.submit(r)

Body:
To keep this very short: you need not do anything at all; if you define a Client, it will become the default scheduler, and .compute() uses the default scheduler (unless specified).

r = darr.map_blocks(block_mean)
c = Client()
out_arr = r.compute()

If you read the docs for submit, it expects a function - there are plenty of examples of how to use it.


问:
is there anyway to get Hyperlink content from resource file in WPF
Is there anyway to get hyperlink content from resource file in xaml. I know there is way on back hand code. I have tried using Name="{x:Static Properties:Resources.stringname}" but it throws error

Or if there is any work around?

I have tried Name but it gives an error:Not able to bind to Uid or Name property in XAML

答:
You cannot bind to the Name in XAML since it is being used internally to create references and it needs to be unique. Some relevant bits from MSDN:

Name is one of the very few dependency properties that cannot be animated (IsAnimationProhibited is true in metadata), because the name itself is vital for targeting an animation. Data binding a Name is technically possible, but is an extremely uncommon scenario because a data-bound Name cannot serve the main intended purpose of the property: to provide an identifier connection point for code-behind.

Names must be unique within a namescope. For more information, see WPF XAML Namescopes.