问:
What is meant by speech bias and how to use speechBiasHints in google-actions appResponse
I've build an app in "Actions on google" using actions SDK. App request and App response works fine, earlier i've created expectedInput section in AppResponse without using speechBiasingHints, but now i want to use it, and i can't find any information about speechBiasHints.

I mean i need info on:

What is meant by speech bias

Can you provide an example on how to use speechBiasingHints

答:
Speech biases are influencing the speech to text recognition. So you can for example add here names and other slots etc.

For example you have a Hotel named King Thegeorge you can add it. So google will try to recognize it and deliver the String to you.

but one question, how you use the rest of the inspected input? Do you found a way to give him the possible intents and got them in the request after your response?

you can use them like that (slots is an array, message a string):

```<code>function answerWithMessage(message,slots){
  let token = {
    "state":null,
    "data":{}
  };

  let jsonResponse = {
        conversationToken: JSON.stringify(token),
        expectUserResponse: true,
        expectedInputs: [
            {
                inputPrompt: {
                    initialPrompts: [
                        {
                            textToSpeech: message
                        }
                    ],
                    noInputPrompts: []
                },
                possibleIntents: [
                    {
                        intent: "actions.intent.TEXT"
                    }
                ],
                speechBiasingHints: slots
            }
        ]
    };
  return JSON.stringify(jsonResponse,null, 4);
}
</code>```

if you create the json response by yourself

Body:
Speech biases are influencing the speech to text recognition. So you can for example add here names and other slots etc.

For example you have a Hotel named King Thegeorge you can add it. So google will try to recognize it and deliver the String to you.

but one question, how you use the rest of the inspected input? Do you found a way to give him the possible intents and got them in the request after your response?

you can use them like that (slots is an array, message a string):

function answerWithMessage(message,slots){
  let token = {
    "state":null,
    "data":{}
  };

  let jsonResponse = {
        conversationToken: JSON.stringify(token),
        expectUserResponse: true,
        expectedInputs: [
            {
                inputPrompt: {
                    initialPrompts: [
                        {
                            textToSpeech: message
                        }
                    ],
                    noInputPrompts: []
                },
                possibleIntents: [
                    {
                        intent: "actions.intent.TEXT"
                    }
                ],
                speechBiasingHints: slots
            }
        ]
    };
  return JSON.stringify(jsonResponse,null, 4);
}

if you create the json response by yourself


来源: stackexchange

问:
Rectangle and circle resolve collision
How can I change the dy of the ball if it touches the top and bottom of the block? Now it just gets a wobble effect and gets trapped inside of the block when it hits the top or bottom.
Here is my Jsfiddle: https://jsfiddle.net/6qh70wdo/</p>

```<code>if (ball.x - ball.radius < block.x + block.w &&
    ball.x + ball.radius > block.x &&
    ball.y - ball.radius < block.y + block.h &&
    ball.y + ball.radius > block.y) {
    ball.dx  = -ball.dx;
}
</code>```

答:
I would break it up into two sections. First detect if it is being hit and then worry about where it's hitting. I think you could do something like this: </p>

```<code>var bool = ball.x - ball.radius < block.x + block.w &&
    ball.x + ball.radius > block.x &&
    ball.y - ball.radius < block.y + block.h &&
    ball.y + ball.radius > block.y) {
    ball.dx  = -ball.dx;

if(bool) // if true, meaning a hit, find which direction.
    if(ball.x - ball.radius < block.x + block.w || ball.x + ball.radius > block.x){
        ball.dx = -ball.dx; //hit detected on left/right...change left/right direction
    }else{
        ball.dy = -ball.dy; //hit detected on top/bottom...change top/bottom direction
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Rectangle and circle resolve collision

Body:
How can I change the dy of the ball if it touches the top and bottom of the block? Now it just gets a wobble effect and gets trapped inside of the block when it hits the top or bottom.
Here is my Jsfiddle: https://jsfiddle.net/6qh70wdo/

if (ball.x - ball.radius < block.x + block.w &&
    ball.x + ball.radius > block.x &&
    ball.y - ball.radius < block.y + block.h &&
    ball.y + ball.radius > block.y) {
    ball.dx  = -ball.dx;
}

Body:
I would break it up into two sections. First detect if it is being hit and then worry about where it's hitting. I think you could do something like this:

var bool = ball.x - ball.radius < block.x + block.w &&
    ball.x + ball.radius > block.x &&
    ball.y - ball.radius < block.y + block.h &&
    ball.y + ball.radius > block.y) {
    ball.dx  = -ball.dx;

if(bool) // if true, meaning a hit, find which direction.
    if(ball.x - ball.radius < block.x + block.w || ball.x + ball.radius > block.x){
        ball.dx = -ball.dx; //hit detected on left/right...change left/right direction
    }else{
        ball.dy = -ball.dy; //hit detected on top/bottom...change top/bottom direction
    }
}


问:
How to use 'in' keyword in Javascript
I have a question here. I know my code have plenty of problems and I need your help.
The problem is, To return an object which have numbers of repetition information of the string.
The given string is

```<code>var r = countFreq(["a", "b", "b", "c", "c", "c", "d"]);
</code>```

and the result have to be

```<code>{"a":1, "b":2, "c":3, "d":1 }
</code>```

by console.log(r);

All that I know is, key(properties) have to be element and value(value of property) have to be the number of repetition.
AND, I must use 'in' key world to solve this problem.

```<code>Like,
if('property' in 'object')  {
 //...
}else {
 //...
}
</code>```

(if there's no property initialize as 1, and if there's a same property, add 1 each time)

I really appreciate your help.
(This post may have grammatical errors. I really feel sorry about that...)

```<code>      function countFreq(array) {
        var i;
        for(i=0; i<array.length; i++)
        {
          if(array[i] in array)
          {
            return i += 1;
          }else
          {
            return i = 1;
          }
          console.log(array[i]+": "+i+", ");
        }
      }
      var r = countFreq(["a","b","c","c","c","d"]);
      console.log(r);
</code>```

答:
According to MDN - The 'in' operator returns true if the specified property is in the specified object or its prototype chain.
Prop is a string or symbol representing a property name or array index (non-symbols will be coerced to strings).
Object is to check if it (or its prototype chain) contains the property with specified name.

So in your case, it depends what your object is? if you object is an array, you need to use prop as properties of array. All index values up to length of array will return true.
MDN Example of arrays

```<code>var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
0 in trees        // returns true
3 in trees        // returns true
6 in trees        // returns false
'bay' in trees    // returns false (you must specify the
                  // index number, not the value at that index)
'length' in trees // returns true (length is an Array property)
Symbol.iterator in trees // returns true (arrays are iterable, works only in ES2015+)
</code>```

Title: How to use 'in' keyword in Javascript

Body:
I have a question here. I know my code have plenty of problems and I need your help.
The problem is, To return an object which have numbers of repetition information of the string.
The given string is

var r = countFreq(["a", "b", "b", "c", "c", "c", "d"]);

and the result have to be

{"a":1, "b":2, "c":3, "d":1 }

by console.log(r);

All that I know is, key(properties) have to be element and value(value of property) have to be the number of repetition.
AND, I must use 'in' key world to solve this problem.

Like,
if('property' in 'object')  {
 //...
}else {
 //...
}

(if there's no property initialize as 1, and if there's a same property, add 1 each time)

I really appreciate your help.
(This post may have grammatical errors. I really feel sorry about that...)

      function countFreq(array) {
        var i;
        for(i=0; i<array.length; i++)
        {
          if(array[i] in array)
          {
            return i += 1;
          }else
          {
            return i = 1;
          }
          console.log(array[i]+": "+i+", ");
        }
      }
      var r = countFreq(["a","b","c","c","c","d"]);
      console.log(r);

Body:
According to MDN - The 'in' operator returns true if the specified property is in the specified object or its prototype chain.
Prop is a string or symbol representing a property name or array index (non-symbols will be coerced to strings).
Object is to check if it (or its prototype chain) contains the property with specified name.

So in your case, it depends what your object is? if you object is an array, you need to use prop as properties of array. All index values up to length of array will return true.
MDN Example of arrays

var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
0 in trees        // returns true
3 in trees        // returns true
6 in trees        // returns false
'bay' in trees    // returns false (you must specify the
                  // index number, not the value at that index)
'length' in trees // returns true (length is an Array property)
Symbol.iterator in trees // returns true (arrays are iterable, works only in ES2015+)


问:
Disable/Enable a textbox in bootstrap modal form based on radio button click
I have a bootsrap modal form.In that if i click on the radio button,'For All Subjects','Subject' textbox should be in disabled state.Similarly,if I click on radio button 'Specific Subject', 'Subject' textbox should be enabled.

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

        <button type="button" class="btn  btn-lg"
         data-toggle="modal" data-target="#addMasterData" >Add Master</button>

    <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

          Add Master

        <form id="mastercreate" action="addConfig" method="post">

          Subjects:
           <input type="radio" name="roleSubjectRadio" id="forAllSubjects"
           value="Yes"  >For All Subjects
            <input type="radio"
           name="roleSubjectRadio" id="specificFlights"
         value="Specific"  checked>Specific Subject
           <input type="hidden" class="form-control" id="specs" name="specs"
           value="">

            Subject
             Name: <input type="text" class="form-control" id="subNo"
             name="subNo" >

          <button type="button" class="btn btn-primary"
           onclick="addMaster()">Submit</button>
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

        </form>

```

Please suggest how to do it from javascript.

答:
For that you need to use event handling for radio buttons, you can try below snippet for that. I have written that in jQuery, you can also use JavaScript for the same.

$('input[type=radio]').click(function(){
  if($(this).prop("id")==="forAllSubjects"){
    $("#subNo").prop("disabled","remove");
  } else {
    $("#subNo").removeAttr("disabled");
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container" id="adminContent">
  <div class="row">
    <div class="col s12 m12 l12" style="float: right">
      <button type="button" class="btn  btn-lg" data-toggle="modal" data-target="#addMasterData" >Add Master</button>
    </div>
  </div>
</div>

<div class="modal fade vertical-align-center" id="addMasterData" role="dialog" style="width: 500px"; role="dialog" data-backdrop="static" data-keyboard="false">
  <div class="modal-dialog ">
    <div class="modal-content ">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">×</span>
        </button>
        <h4 class="modal-title">
          <b><font class="font">Add Master</font></b>
        </h4>
      </div>
      <form id="mastercreate" action="addConfig" method="post">
        <div class="modal-content ">
          <div class="modal-body ">
            <div class="form-group">
             <label for="text">Subjects:</label> <label class="radio-inline">
                <input type="radio" name="roleSubjectRadio" id="forAllSubjects" value="Yes"  >For All Subjects
              </label>
              <label class="radio-inline">
                <input type="radio" name="roleSubjectRadio" id="specificFlights" value="Specific" checked>Specific Subject
              </label>
              <input type="hidden" class="form-control" id="specs" name="specs" value="">
            </div>
            <div class="form-group" id="subName">
              <label for="createorigin" class="form-control-label">
                <font >Subject Name:</font>
              </label>
              <input type="text" class="form-control" id="subNo" name="subNo" >
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-primary" onclick="addMaster()">Submit</button>
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
          </div>
        </div>
      </form>
    </div>
  </div>
</div></code>```

Body:
I have a bootsrap modal form.In that if i click on the radio button,'For All Subjects','Subject' textbox should be in disabled state.Similarly,if I click on radio button 'Specific Subject', 'Subject' textbox should be enabled.

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

        <button type="button" class="btn  btn-lg"
         data-toggle="modal" data-target="#addMasterData" >Add Master</button>

    <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

          Add Master

        <form id="mastercreate" action="addConfig" method="post">

          Subjects:
           <input type="radio" name="roleSubjectRadio" id="forAllSubjects"
           value="Yes"  >For All Subjects
            <input type="radio"
           name="roleSubjectRadio" id="specificFlights"
         value="Specific"  checked>Specific Subject
           <input type="hidden" class="form-control" id="specs" name="specs"
           value="">

            Subject
             Name: <input type="text" class="form-control" id="subNo"
             name="subNo" >

          <button type="button" class="btn btn-primary"
           onclick="addMaster()">Submit</button>
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

        </form>

Please suggest how to do it from javascript.

Body:
For that you need to use event handling for radio buttons, you can try below snippet for that. I have written that in jQuery, you can also use JavaScript for the same.

$('input[type=radio]').click(function(){
  if($(this).prop("id")==="forAllSubjects"){
    $("#subNo").prop("disabled","remove");
  } else {
    $("#subNo").removeAttr("disabled");
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container" id="adminContent">
  <div class="row">
    <div class="col s12 m12 l12" style="float: right">
      <button type="button" class="btn  btn-lg" data-toggle="modal" data-target="#addMasterData" >Add Master</button>
    </div>
  </div>
</div>

<div class="modal fade vertical-align-center" id="addMasterData" role="dialog" style="width: 500px"; role="dialog" data-backdrop="static" data-keyboard="false">
  <div class="modal-dialog ">
    <div class="modal-content ">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
        <h4 class="modal-title">
          <b><font class="font">Add Master</font></b>
        </h4>
      </div>
      <form id="mastercreate" action="addConfig" method="post">
        <div class="modal-content ">
          <div class="modal-body ">
            <div class="form-group">
             <label for="text">Subjects:</label> <label class="radio-inline">
                <input type="radio" name="roleSubjectRadio" id="forAllSubjects" value="Yes"  >For All Subjects
              </label>
              <label class="radio-inline">
                <input type="radio" name="roleSubjectRadio" id="specificFlights" value="Specific" checked>Specific Subject
              </label>
              <input type="hidden" class="form-control" id="specs" name="specs" value="">
            </div>
            <div class="form-group" id="subName">
              <label for="createorigin" class="form-control-label">
                <font >Subject Name:</font>
              </label>
              <input type="text" class="form-control" id="subNo" name="subNo" >
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-primary" onclick="addMaster()">Submit</button>
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
          </div>
        </div>
      </form>
    </div>
  </div>
</div>


问:
python - How to parse numbers around a specific word/phrase
Suppose that I have a text like this:

Our favorite numbers are 5, 6, and 7, but his favorite number is 0. Also, this text contains 2 sentences.

Let's say I'd like to get favorite numbers only in this text, for instance. I won't be able to know if there's a favorite number in this text, unless the phrase favorite number is present. So I'm basically trying to parse numbers around the phrase favorite number (or favorite numbers). The expected result should be something like this:

['5', '6', '7', '0']
```

<p>I tried using regex for that but I've failed so far. What's the most logical way to do this?</p>

<p>Edit: After reading @LouiseDavies's question, I'll add another example below:</p>

<p><code>Alice has 2 favorite numbers: 11 and 12. Bob has 10 favorite numbers: 0, 100, 1264, 598, 78496, 33546, 1028896, 23, 48, 6.</code></p>

<p>So in this example, my output should be something like this (the order doesn't matter):</p>

```['11', '12', '0', '100', '1264', '598', '78496', '33546', '1028896', '23', '48', '6']
```

答:
You can use regex:

```<code>import re
import itertools
s = 'Our favorite numbers are 5, 6, and 7, but his favorite number is 0. Also, this text contains 2 sentences.'

numbers = re.findall('(?<= favorite number is)[,\s\d]+|(?<=favorite numbers are)[,\s\dand]+', s)
final_numbers = list(itertools.chain(*[re.findall('\d+', i) for i in numbers]))
</code>```

Output:

```<code>['5', '6', '7', '0']
</code>```

Body:
Suppose that I have a text like this:

Our favorite numbers are 5, 6, and 7, but his favorite number is 0. Also, this text contains 2 sentences.

Let's say I'd like to get favorite numbers only in this text, for instance. I won't be able to know if there's a favorite number in this text, unless the phrase favorite number is present. So I'm basically trying to parse numbers around the phrase favorite number (or favorite numbers). The expected result should be something like this:

['5', '6', '7', '0']

I tried using regex for that but I've failed so far. What's the most logical way to do this?

Edit: After reading @LouiseDavies's question, I'll add another example below:

Alice has 2 favorite numbers: 11 and 12. Bob has 10 favorite numbers: 0, 100, 1264, 598, 78496, 33546, 1028896, 23, 48, 6.

So in this example, my output should be something like this (the order doesn't matter):

['11', '12', '0', '100', '1264', '598', '78496', '33546', '1028896', '23', '48', '6']

Body:
You can use regex:

import re
import itertools
s = 'Our favorite numbers are 5, 6, and 7, but his favorite number is 0. Also, this text contains 2 sentences.'

numbers = re.findall('(?<= favorite number is)[,\s\d]+|(?<=favorite numbers are)[,\s\dand]+', s)
final_numbers = list(itertools.chain(*[re.findall('\d+', i) for i in numbers]))

Output:

['5', '6', '7', '0']


问:
How to document function-based views parameters?
I'm developing a REST API with Django 1.11 and Django REST Framework 3.7. I installed Django REST Swagger 2.1 to generate the documentation.

I'm using a function-based view like this:

```<code>from rest_framework.decorators import api_view, permission_classes

@api_view(['POST'])
@permission_classes((permissions.AllowAny,))
def jwt_auth(request, provider, format=None):
    """
    View description here
    """
    pass
</code>```

As you can see, my view is recognized by Swagger and it has the correct description: "View description here".

However:

You can see the "Description" column is empty for the provider URL parameter.

The POST parameters are not documented (obviously, because there is no way for Swagger to know them)

How can I write documentation for the URL and POST parameters of a function-based view, as well as the responses?

I tried YAML Docstrings but it seems it's for the old version (0.3.x) and it doesn't work with version 2.x.

答:
Following this github issue, it seems it's not possible for the method-based views as you stated.

But I think this link can help you.

Body:
I'm developing a REST API with Django 1.11 and Django REST Framework 3.7. I installed Django REST Swagger 2.1 to generate the documentation.

I'm using a function-based view like this:

from rest_framework.decorators import api_view, permission_classes

@api_view(['POST'])
@permission_classes((permissions.AllowAny,))
def jwt_auth(request, provider, format=None):
    """
    View description here
    """
    pass

As you can see, my view is recognized by Swagger and it has the correct description: "View description here".

However:

You can see the "Description" column is empty for the provider URL parameter.

The POST parameters are not documented (obviously, because there is no way for Swagger to know them)

How can I write documentation for the URL and POST parameters of a function-based view, as well as the responses?

I tried YAML Docstrings but it seems it's for the old version (0.3.x) and it doesn't work with version 2.x.


问:
Apply drop caps to each word in a link
I'd like to recreate the menu effect seen at http://www.thedecoratorsource.co.uk using CSS fonts and drop caps.

I know that I can use

```<code>p.introduction:first-letter {
font-size : 300%;
}
</code>```

which will give me the first word with a larger first characerer but I want to apply it to each word. I'm guessing there isn't a way to do this with CSS(3). Would my best bet with javascript? I've already got Moo on the page so this would be my preferred method.

I don't want to add extra HTML to my links to achieve this.

Thanks

答:
Based on these other answers, I'm not sure I understand the question. BUT, based on my understanding this must be done with JS if you want that exact effect. Not much moo to it though.

This will add a span around the first letter of each word and apply a class to it. You can do whatever you want to the first letters in your css after that.

```<code>  $$('p.introduction').each(function(el) {
    var text = el.textContent || el.innerText;
    el.innerHTML = text.replace(/\b(\w)([^\b]*?)/g, function(match, first, remainder) {
      return ['<span class="first-letter">', first, '</span>', remainder].join('');
    });
  });
</code>```

ContentLicense: CC BY-SA 2.5

Title: Apply drop caps to each word in a link

Body:
I'd like to recreate the menu effect seen at http://www.thedecoratorsource.co.uk using CSS fonts and drop caps.

I know that I can use

p.introduction:first-letter {
font-size : 300%;
}

which will give me the first word with a larger first characerer but I want to apply it to each word. I'm guessing there isn't a way to do this with CSS(3). Would my best bet with javascript? I've already got Moo on the page so this would be my preferred method.

I don't want to add extra HTML to my links to achieve this.

Thanks

Body:
Based on these other answers, I'm not sure I understand the question. BUT, based on my understanding this must be done with JS if you want that exact effect. Not much moo to it though.

This will add a span around the first letter of each word and apply a class to it. You can do whatever you want to the first letters in your css after that.

  $$('p.introduction').each(function(el) {
    var text = el.textContent || el.innerText;
    el.innerHTML = text.replace(/\b(\w)([^\b]*?)/g, function(match, first, remainder) {
      return ['<span class="first-letter">', first, '</span>', remainder].join('');
    });
  });


问:
How to set a context root for all @RestController in Spring Web MVC?
I'm looking to define /api as the root context for all my @RestControllers and don't want to specify it for each of them.

For instance, I would like to write @RestController("/clients") instead of @RestController("/api/clients") and make my request mappings available at /api/clients but have my static resources (in /main/resources/static) still served at /**.

So, setting server.servlet.contextPath=/api in application.properties is not a solution for my use case because the static resources will be served at /api, which I don't want.

In brief, I would like to have the same feature as JAX-RS @ApplicationPath("/api") in Spring Web MVC, is this possible?

答:
One of the possible <s>solution</s>(work around) is to use Parent Class with mapping

```<code>@RequestMapping(path="/api")
abstract class BaseController{
    ....
}
</code>```

Other controllers can extend it

```<code>class OtherController extends BaseController {
  @RequestMapping(path="/clients")
  public ....clients(....){
   .....
  }
}
</code>```

Please note that @RequestMapping will get overridden if you place it on top of any child class. Like explained here and here

Body:
One of the possible <s>solution</s>(work around) is to use Parent Class with mapping

@RequestMapping(path="/api")
abstract class BaseController{
    ....
}

Other controllers can extend it

class OtherController extends BaseController {
  @RequestMapping(path="/clients")
  public ....clients(....){
   .....
  }
}

Please note that @RequestMapping will get overridden if you place it on top of any child class. Like explained here and here


问:
How to Set OnClickListener to Card in PlaceholderView?
I am using PlaceHolderView library to show an Infinite List of contents like the Facebook Android app. I was using InfinitePlaceHolderView for it. It looks like this:

And here is how it looks like output

Now If the story is large then a user can click on the card view and it will take him to a new activity where there will be a detail of that story. For this, I need to add a Listener. But I could not find any documentation at all, how to implement it. The documentation shows that all those cards are dynamically created and not any of those cards have any id so that I can put a listener.

How to implement it?

答:
In step three of the documentation you have an example of the Event Bind:

```<code>@Animate(Animation.ENTER_LEFT_DESC)
@NonReusable
@Layout(R.layout.gallery_item_big)
public class ImageTypeBig {

    @View(R.id.imageView)
    private ImageView imageView;

    private String mUrl;
    private Context mContext;
    private PlaceHolderView mPlaceHolderView;

    public ImageTypeBig(Context context, PlaceHolderView placeHolderView, String url) {
        mContext = context;
        mPlaceHolderView = placeHolderView;
        mUrl = url;
    }

    @Resolve
    private void onResolved() {
        Glide.with(mContext).load(mUrl).into(imageView);
    }

    @LongClick(R.id.imageView)
    private void onLongClick(){
        mPlaceHolderView.removeView(this);
    }

}
</code>```

More information:
https://github.com/janishar/PlaceHolderView#step-3-create-item-class-to-bind-and-define-view-operations

Body:
In step three of the documentation you have an example of the Event Bind:

@Animate(Animation.ENTER_LEFT_DESC)
@NonReusable
@Layout(R.layout.gallery_item_big)
public class ImageTypeBig {

    @View(R.id.imageView)
    private ImageView imageView;

    private String mUrl;
    private Context mContext;
    private PlaceHolderView mPlaceHolderView;

    public ImageTypeBig(Context context, PlaceHolderView placeHolderView, String url) {
        mContext = context;
        mPlaceHolderView = placeHolderView;
        mUrl = url;
    }

    @Resolve
    private void onResolved() {
        Glide.with(mContext).load(mUrl).into(imageView);
    }

    @LongClick(R.id.imageView)
    private void onLongClick(){
        mPlaceHolderView.removeView(this);
    }

}

More information:
https://github.com/janishar/PlaceHolderView#step-3-create-item-class-to-bind-and-define-view-operations


答:
import org.apache.spark.sql

val marketingproj5DF2 = marketingproj5DF.withColumn("age", $"age".cast(sql.types.IntegerType))

Title: Cast from String to Int in DF results in null instead of numbers

Body:
Here's my code for an example:

import org.apache.spark.sql.functions._
import org.apache.spark.sql.types.IntegerType
val marketingproj5DF2 = marketingproj5DF.withColumn("ageTmp", 'age.cast(IntegerType)).drop("age").withColumnRenamed("ageTmp","age")

Here's what the DF looks like after:

scala> marketingproj5DF2.show(5)

+--------+----------------+-----------+-------------+-----------+-----------+-----------+--------+-----------+-------+---------+------------+------------+---------
+------------+------------+-------+------+
|     age|             job|    marital|    education|    default|    balance|    housing|    loan|    contact|    day|    month|    duration|    campaign|    pdays
|    previous|    poutcome|      y|ageTmp|
+--------+----------------+-----------+-------------+-----------+-----------+-----------+--------+-----------+-------+---------+------------+------------+---------
+------------+------------+-------+------+
|"""age""|         ""job""|""marital""|""education""|""default""|""balance""|""housing""|""loan""|""contact""|""day""|""month""|""duration""|""campaign""|""pdays""
|""previous""|""poutcome""| ""y"""|  null|
|     "58|  ""management""|""married""| ""tertiary""|     ""no""|       2143|    ""yes""|  ""no""|""unknown""|      5|  ""may""|         261|           1|       -1
|           0| ""unknown""|""no"""|  null|
|     "44|  ""technician""| ""single""|""secondary""|     ""no""|         29|    ""yes""|  ""no""|""unknown""|      5|  ""may""|         151|           1|       -1
|           0| ""unknown""|""no"""|  null|
|     "33|""entrepreneur""|""married""|""secondary""|     ""no""|          2|    ""yes""| ""yes""|""unknown""|      5|  ""may""|          76|           1|       -1
|           0| ""unknown""|""no"""|  null|
|     "47| ""blue-collar""|""married""|  ""unknown""|     ""no""|       1506|    ""yes""|  ""no""|""unknown""|      5|  ""may""|          92|           1|       -1
|           0| ""unknown""|""no"""|  null|
+--------+----------------+-----------+-------------+-----------+-----------+-----------+--------+-----------+-------+---------+------------+------------+---------
+------------+------------+-------+------+
only showing top 5 rows

I'm using Spark 1.6 Scala 2.10.5. The first column is my original "age" column and the data is imported from .csv and I couldn't get all of the data into a DF unless I left it as a string, now that I have the "age" column in, I'm trying to convert/cast the field and query against it.


答:
If I understand right, you want to get only one row with lowest price. So, when you have multiple rows with same price in a group, you'd need to decide which row you want. Perhaps with minimum id:

```<code>select min(p.id) as id,
    p.price
from product p
join (
    select product_group_id,
        min(price) as price
    from product
    group by product_group_id
    ) as inp
on  p.product_group_id = inp.product_group_id
    and p.price = inp.price
group by p.price, p.product_group_id;
</code>```

Title: Select product with smallest price when products are group

Body:
Select product with cheapest price, when group by group id.
I managed to get cheapest product when all products in a group have different prices, but when all products in a group have same price it does not work. So

I need help to add a extra filter to with limit Join.

http://sqlfiddle.com/#!9/f9b16c/6

I have created a sample here.

SELECT
    p.id, p.price
FROM
    product p
        JOIN
    (SELECT
        product_group_id, MIN(price) AS price
    FROM
        product
    GROUP BY product_group_id

    ) AS inp ON p.product_group_id = inp.product_group_id
        AND p.price = inp.price;

Sample data

ID |       price |         sku       |          product_group_id

'58', '2800.0000', '1-67-131-72', '44'
'60', '3688.0000', '8-105-82-72', '30'
'61', '2750.0000', '9-105-82-72', '31'
'62', '3400.0000', '10-67-131-72', '45'
'189', '3530.0000', '7-113-114-115', '29'
'190', '3050.0000', '7-113-114-72', '29'
'193', '2980.0000', '7-105-114-115', '29'
'194', '2500.0000', '7-105-114-72', '29'
'196', '4699.0000', '8-116-114-115', '30'
'199', '4069.0000', '8-116-82-72', '30'
'200', '4318.0000', '8-105-114-115', '30'
'205', '3910.0000', '9-117-82-115', '31'
'206', '3230.0000', '9-117-82-72', '31'
'207', '3580.0000', '9-105-114-115', '31'
'256', '3550.0000', '1-135-136-137', '44'
'257', '3070.0000', '1-135-136-72', '44'
'258', '3400.0000', '1-135-131-137', '44'
'259', '2920.0000', '1-135-131-72', '44'
'260', '3430.0000', '1-67-136-137', '44'
'261', '2950.0000', '1-67-136-72', '44'
'262', '3280.0000', '1-67-131-137', '44'
'263', '3880.0000', '10-67-131-137', '45'
'292', '8750.0000', 'HobartAUPs-117-137', '53'
'293', '8750.0000', 'HobartAUP-69-72', '53'
'294', '8750.0000', 'HobartAUP-69-137', '53'
'295', '8750.0000', 'HobartAUP-117-72', '53'

Desired result

ID    |  Price

'194', '2500.0000'
'61', '2750.0000'
'58', '2800.0000'
'62', '3400.0000'
'60', '3688.0000'
'292', '8750.0000'

Body:
If I understand right, you want to get only one row with lowest price. So, when you have multiple rows with same price in a group, you'd need to decide which row you want. Perhaps with minimum id:

select min(p.id) as id,
    p.price
from product p
join (
    select product_group_id,
        min(price) as price
    from product
    group by product_group_id
    ) as inp
on  p.product_group_id = inp.product_group_id
    and p.price = inp.price
group by p.price, p.product_group_id;


问:
firebase.auth.PhoneAuthProvider missing
I have connected my android application with firebase and enabled phone authentication on the console. However when I import

```<code>import com.google.firebase.auth.PhoneAuthProvider;
</code>```

It can't find the class PhoneAuthProvider.
Note that it can find other classes such as EmailAuthProvider and FirebaseAuthProvider.

```<code>compile 'com.google.firebase:firebase-auth:10.0.1'
</code>```

is listed in the app dependencies.

Please let me know if I need to provide any other information to get help as well.

答:
Phone number authentication was added in version 11.0.0.  You will have to upgrade to at least that version.

SDK Version 11.0.0 - June 7, 2017

Added the getPhoneNumber() and updatePhoneNumber() methods to the FirebaseUser class, and also added the getPhoneNumber() method to the
  UserInfo class. These methods get and update the phone numbers of
  users.

Added the PhoneAuthCredential, PhoneAuthProvider, PhoneAuthProvider.ForceResendingToken, and
  PhoneAuthProvider.OnVerificationStateChangedCallbacks classes to
  support authentication using phone numbers.

Title: firebase.auth.PhoneAuthProvider missing

Body:
I have connected my android application with firebase and enabled phone authentication on the console. However when I import

import com.google.firebase.auth.PhoneAuthProvider;

It can't find the class PhoneAuthProvider.
Note that it can find other classes such as EmailAuthProvider and FirebaseAuthProvider.

compile 'com.google.firebase:firebase-auth:10.0.1'

is listed in the app dependencies.

Please let me know if I need to provide any other information to get help as well.


问:
malloc : error double free with printf and a NULL wchar_t*
I'm trying to port an application from Linux to Mac Os X (leopard), but when I execute it, I have this error message : malloc: *** error for object 0x100160 : double free.

I've reproduced this issue with the code below :

```<code>//main.cpp
#include <stdio.h>
#include <wchar.h>

int main(int argc, char*argv[])
{
    wchar_t *b=NULL;
    printf("a=%ls, b=%ls \n", L"a", b);
}
</code>```

Compiled with gcc:

```<code>gcc main.cpp -o test
</code>```

The output of the execution:

```<code>a=a, b=(null)
test (5337) malloc: *** error for object 0x100160 : double free
*** set a breakpoint in malloc_error_break to debug
</code>```

It's strange because if I use this line : printf("a=%ls, b=%ls", b, b), no error are printed.
Furthermore, I can't use wprintf(L"a=%ls, b=%ls", a, b).
On Fedora 13, this program don't print any error.

Is it a printf bug?
How can I remove this error?

答: On Ubuntu it prints a=a, b=(null), but in general it is not a good idea to try to print NULL strings.

Body:
I'm trying to port an application from Linux to Mac Os X (leopard), but when I execute it, I have this error message : malloc: *** error for object 0x100160 : double free.

I've reproduced this issue with the code below :

//main.cpp
#include <stdio.h>
#include <wchar.h>

int main(int argc, char*argv[])
{
    wchar_t *b=NULL;
    printf("a=%ls, b=%ls \n", L"a", b);
}

Compiled with gcc:

gcc main.cpp -o test

The output of the execution:

a=a, b=(null)
test (5337) malloc: *** error for object 0x100160 : double free
*** set a breakpoint in malloc_error_break to debug

It's strange because if I use this line : printf("a=%ls, b=%ls", b, b), no error are printed.
Furthermore, I can't use wprintf(L"a=%ls, b=%ls", a, b).
On Fedora 13, this program don't print any error.

Is it a printf bug?
How can I remove this error?


问:
change hostname from text in .txt file
I am making a script that if the computer starts up, the hostname has to change to a specific name. That name is in a test.txt file.

Currently I have a test.txt file in my documents.

If I do :

setlocal
set /p hostname=< test.txt
echo %hostname%
SBB-TEST
```

<p>So I can have the text from the .txt file into a variable.
But If I try :</p>

<pre class="lang-dos prettyprint-override"><code>WMIC computersystem where name="%computername%" rename name =%hostname%
</code>```

I get the error : Invalid Verb Switch

That is my first question.

My second question is, If I do this directly from a batch file.. I get following error on my screen :

set /p hostname= 0<test.txt
The system cannot find the file specified
```

Why does he change the set /p hostname=< test.txt to set /p hostname= 0

The 0 is nowhere specified.

答:
Use a CALL on the rename. You will still need to reboot the system for the new hostname to take effect.

```<code>WMIC computersystem where name="%computername%" CALL rename name =%hostname%
</code>```

https://blogs.technet.microsoft.com/askds/2009/02/19/renaming-a-computer-using-wmic-and-how-to-get-around-that-aggravating-invalid-global-switch-error/

Also, HOSTNAME is already an environment variable under UNIX/Linux/Cygwin. I would call this one something else. Perhaps NEW_HOSTNAME.

Title: change hostname from text in .txt file

Body:
I am making a script that if the computer starts up, the hostname has to change to a specific name. That name is in a test.txt file.

Currently I have a test.txt file in my documents.

If I do :

setlocal
set /p hostname=< test.txt
echo %hostname%
SBB-TEST

So I can have the text from the .txt file into a variable.
But If I try :

WMIC computersystem where name="%computername%" rename name =%hostname%

I get the error : Invalid Verb Switch

That is my first question.

My second question is, If I do this directly from a batch file.. I get following error on my screen :

set /p hostname= 0<test.txt
The system cannot find the file specified

Why does he change the set /p hostname=< test.txt to set /p hostname= 0

The 0 is nowhere specified.

Body:
Use a CALL on the rename. You will still need to reboot the system for the new hostname to take effect.

WMIC computersystem where name="%computername%" CALL rename name =%hostname%

https://blogs.technet.microsoft.com/askds/2009/02/19/renaming-a-computer-using-wmic-and-how-to-get-around-that-aggravating-invalid-global-switch-error/

Also, HOSTNAME is already an environment variable under UNIX/Linux/Cygwin. I would call this one something else. Perhaps NEW_HOSTNAME.


问:
Grid with RowSpacing(Xamarin Forms) and navigation
Now I'm working on updating the UI of my app(XF for Android). I found this UI solution for appbar(from source code Evolve 2016):

It looks beautiful and is implemented simply:

```<code><ContentPage.Content>
<Grid RowSpacing="0" >
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <StackLayout BackgroundColor={StaticResource Primary}, Grid.Row=0/>
       <SearchBar/>
    </StackLayout>
    <StackLayout Grid.Row=1>
       //other content
   </StackLayout>
 .....
</code>```

For existing navigation(Master-Detail) it works fine. But I click by item (on this page) - than  open new page(no Master Detail). Work like this:

```<code> await Navigation.PushAsync(new SessionDetailPage(), true);
</code>```

I click back on toolbar - return to Session page than I get a white line display for a short time

it does not last long, a split second. then the white line disappears. But it's unpleasant to use.
Any ideas? How can I improve this?

答: Might be RowDefinition Height="Auto" calculating and resizing itself, try use absolute value to check if this is the cause.</p>

Body:
Now I'm working on updating the UI of my app(XF for Android). I found this UI solution for appbar(from source code Evolve 2016):

It looks beautiful and is implemented simply:

<ContentPage.Content>
<Grid RowSpacing="0" >
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <StackLayout BackgroundColor={StaticResource Primary}, Grid.Row=0/>
       <SearchBar/>
    </StackLayout>
    <StackLayout Grid.Row=1>
       //other content
   </StackLayout>
 .....

For existing navigation(Master-Detail) it works fine. But I click by item (on this page) - than  open new page(no Master Detail). Work like this:

 await Navigation.PushAsync(new SessionDetailPage(), true);

I click back on toolbar - return to Session page than I get a white line display for a short time

it does not last long, a split second. then the white line disappears. But it's unpleasant to use.
Any ideas? How can I improve this?


问:
value as string in dynamic sql
I am creating dynamic sql and have the following query

```<code>set @sql = '
             IF (NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = ''dbo'' AND  TABLE_NAME =' + @tableName +'))
             BEGIN
             create table [dbo].[' + @tableName + '] ( calendarYear int, calendarQuarter int, companyid bigint not null, dataitemid bigint not null, dataitemvalue numeric(28,6), fiscalyear int, fiscalquarter int, periodenddate datetime, filingdate datetime, latestforfinancialperiodflag bit, latestfilingforinstanceflag bit );
             END'
            PRINT  @sql
</code>```

Output if the print statement is

```<code> IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND  TABLE_NAME =FinData2000_1))
         BEGIN
         create table [dbo].[FinData2000_1] ( calendarYear int, calendarQuarter int, companyid bigint not null, dataitemid bigint not null, dataitemvalue numeric(28,6), fiscalyear int, fiscalquarter int, periodenddate datetime, filingdate datetime, latestforfinancialperiodflag bit, latestfilingforinstanceflag bit );
         END
</code>```

I am looking having the condition of the table_name condition in string

For e.g

```<code>AND  TABLE_NAME = 'FinData2000_1'
</code>```

How do I achieve that in initial dynamic query

答:
You need to put a couple of apostrophes inside your string, surrounding the table name. To do this, double up the apostrophes so that instead of being interpreted as "end of string" they are interpreted as "apostrophe character":

```<code>set @textWithApostrophes = 'it''s ten o''clock'
</code>```

Hence

```<code>@sql = '... and table_name = ''' + @tablename + ''' blah blah rest of query here'
                             ^^                  ^^
</code>```

I put carets ^^ under everything that "becomes an apostrophe inside an sql string", the other apostrophes are "start or end of a string"

Title: value as string in dynamic sql

Body:
I am creating dynamic sql and have the following query

set @sql = '
             IF (NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = ''dbo'' AND  TABLE_NAME =' + @tableName +'))
             BEGIN
             create table [dbo].[' + @tableName + '] ( calendarYear int, calendarQuarter int, companyid bigint not null, dataitemid bigint not null, dataitemvalue numeric(28,6), fiscalyear int, fiscalquarter int, periodenddate datetime, filingdate datetime, latestforfinancialperiodflag bit, latestfilingforinstanceflag bit );
             END'
            PRINT  @sql

Output if the print statement is

 IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND  TABLE_NAME =FinData2000_1))
         BEGIN
         create table [dbo].[FinData2000_1] ( calendarYear int, calendarQuarter int, companyid bigint not null, dataitemid bigint not null, dataitemvalue numeric(28,6), fiscalyear int, fiscalquarter int, periodenddate datetime, filingdate datetime, latestforfinancialperiodflag bit, latestfilingforinstanceflag bit );
         END

I am looking having the condition of the table_name condition in string

For e.g

AND  TABLE_NAME = 'FinData2000_1'

How do I achieve that in initial dynamic query

Body:
You need to put a couple of apostrophes inside your string, surrounding the table name. To do this, double up the apostrophes so that instead of being interpreted as "end of string" they are interpreted as "apostrophe character":

set @textWithApostrophes = 'it''s ten o''clock'

Hence

@sql = '... and table_name = ''' + @tablename + ''' blah blah rest of query here'
                             ^^                  ^^

I put carets ^^ under everything that "becomes an apostrophe inside an sql string", the other apostrophes are "start or end of a string"


问:
Escaping single quote in php laravel
I have an address field in the locations database, with a value Shop 2197 - Block 1014 - Road 90 - Al-Delaa' Complex - Hamala, the website was working great until I added the location with this address, the google maps plugin no longer works because this single quote has caused a javascript error in the console,

My location controller get function:

```<code>public static function get() {
    $locations = Location::with('country')->get();

    return $locations;
}
</code>```

My script for loading locations into google maps:

```<code>var locations = JSON.parse('{!! $locations !!}');
  var lang = "{{ App::getLocale() }}";
  $(locations).each(function(key, value) {
    allLocationsPins.push({lat: parseInt(value.latitude), lng: parseInt(value.longitude)});
  });
</code>```

The single quote in the address value is causing this error because it's not escaped. I tried adding the JSON encode function to the locations array before returning it from the controller but nothing happened, I think escaping the single quote by Json_encode is not working because of the {!! $locations !!} in the script file, but if I tried to remove the {!!  !!} every character in the string change.

How can I fix this? If json_encode is not working what else can I use ?

I tried to add \ before the single quote in a forloop, but it is not doing anything for some reason, here is the forloop and the output.

```<code>public static function get() {
        $locations = Location::with('country')->get();

        foreach ($locations as $location) {
            $location["address"] = str_replace("'","\'",$location["address"]);
        }
        var_dump($locations);
        return $locations;
    }

// PART OF VAR DUMP OUTPUT..

array(14) {
        ["id"]=>
        int(7)
        ["title"]=>
        string(6) "Hamala"
        ["title_ar"]=>
        NULL
        ["address"]=>
        string(62) "Shop 2197 - Block 1014 - Road 90 - Al-Delaa\' Complex - Hamala"
        ["address_ar"]=>
        NULL
        ["latitude"]=>
        string(9) "26.166246"
        ["longitude"]=>
        string(9) "50.468510"
        ["phone_numbers"]=>
        string(13) "+973 17610612"
        ["customer_service_email"]=>
        string(28) "Marketing@aljasser-group.net"
        ["working_hours"]=>
        string(84) "From 09:00 AM to 01:00 PM | Evening Shift: From 04:00 PM to 08:00 PM | Friday is off"
        ["working_hours_ar"]=>
        NULL
        ["country_id"]=>
        int(3)
        ["created_at"]=>
        string(19) "2017-11-13 16:21:15"
        ["updated_at"]=>
        string(19) "2017-11-06 19:01:54"
      }
      ["original":protected]=>
      array(14) {
        ["id"]=>
        int(7)
        ["title"]=>
        string(6) "Hamala"
        ["title_ar"]=>
        NULL
        ["address"]=>
        string(61) "Shop 2197 - Block 1014 - Road 90 - Al-Delaa' Complex - Hamala"
        ["address_ar"]=>
        NULL
        ["latitude"]=>
        string(9) "26.166246"
        ["longitude"]=>
        string(9) "50.468510"
        ["phone_numbers"]=>
        string(13) "+973 17610612"
        ["customer_service_email"]=>
        string(28) "Marketing@aljasser-group.net"
        ["working_hours"]=>
        string(84) "From 09:00 AM to 01:00 PM | Evening Shift: From 04:00 PM to 08:00 PM | Friday is off"
        ["working_hours_ar"]=>
        NULL
        ["country_id"]=>
        int(3)
        ["created_at"]=>
        string(19) "2017-11-13 16:21:15"
        ["updated_at"]=>
        string(19) "2017-11-06 19:01:54"
      }
</code>```

As you can see the address location array is found twice the first one which was changed as expected and the second one which is protected and did not change the problem is with is line right here

```<code>["address"]=>
        string(61) "Shop 2197 - Block 1014 - Road 90 - Al-Delaa' Complex - Hamala"
</code>```

答:
If your string has a single quote, the string variable you are passing to JSON.parse() wont work because the method doesnt accept them.

Try first declaring the '{!! $locations !!}' into a variable before parsing it and see if that works, it shouldnt.

You will have to manually escape the single quote with \'

Example:

```<code>var aString = '{ "name":"John", "age":30, "city":"New\'York"}'
var aJson = JSON.parse(aString)
</code>```

Title: Escaping single quote in php laravel

Body:
I have an address field in the locations database, with a value Shop 2197 - Block 1014 - Road 90 - Al-Delaa' Complex - Hamala, the website was working great until I added the location with this address, the google maps plugin no longer works because this single quote has caused a javascript error in the console,

My location controller get function:

public static function get() {
    $locations = Location::with('country')->get();

    return $locations;
}

My script for loading locations into google maps:

var locations = JSON.parse('{!! $locations !!}');
  var lang = "{{ App::getLocale() }}";
  $(locations).each(function(key, value) {
    allLocationsPins.push({lat: parseInt(value.latitude), lng: parseInt(value.longitude)});
  });

The single quote in the address value is causing this error because it's not escaped. I tried adding the JSON encode function to the locations array before returning it from the controller but nothing happened, I think escaping the single quote by Json_encode is not working because of the {!! $locations !!} in the script file, but if I tried to remove the {!!  !!} every character in the string change.

How can I fix this? If json_encode is not working what else can I use ?

I tried to add \ before the single quote in a forloop, but it is not doing anything for some reason, here is the forloop and the output.

public static function get() {
        $locations = Location::with('country')->get();

        foreach ($locations as $location) {
            $location["address"] = str_replace("'","\'",$location["address"]);
        }
        var_dump($locations);
        return $locations;
    }

// PART OF VAR DUMP OUTPUT..

array(14) {
        ["id"]=>
        int(7)
        ["title"]=>
        string(6) "Hamala"
        ["title_ar"]=>
        NULL
        ["address"]=>
        string(62) "Shop 2197 - Block 1014 - Road 90 - Al-Delaa\' Complex - Hamala"
        ["address_ar"]=>
        NULL
        ["latitude"]=>
        string(9) "26.166246"
        ["longitude"]=>
        string(9) "50.468510"
        ["phone_numbers"]=>
        string(13) "+973 17610612"
        ["customer_service_email"]=>
        string(28) "Marketing@aljasser-group.net"
        ["working_hours"]=>
        string(84) "From 09:00 AM to 01:00 PM | Evening Shift: From 04:00 PM to 08:00 PM | Friday is off"
        ["working_hours_ar"]=>
        NULL
        ["country_id"]=>
        int(3)
        ["created_at"]=>
        string(19) "2017-11-13 16:21:15"
        ["updated_at"]=>
        string(19) "2017-11-06 19:01:54"
      }
      ["original":protected]=>
      array(14) {
        ["id"]=>
        int(7)
        ["title"]=>
        string(6) "Hamala"
        ["title_ar"]=>
        NULL
        ["address"]=>
        string(61) "Shop 2197 - Block 1014 - Road 90 - Al-Delaa' Complex - Hamala"
        ["address_ar"]=>
        NULL
        ["latitude"]=>
        string(9) "26.166246"
        ["longitude"]=>
        string(9) "50.468510"
        ["phone_numbers"]=>
        string(13) "+973 17610612"
        ["customer_service_email"]=>
        string(28) "Marketing@aljasser-group.net"
        ["working_hours"]=>
        string(84) "From 09:00 AM to 01:00 PM | Evening Shift: From 04:00 PM to 08:00 PM | Friday is off"
        ["working_hours_ar"]=>
        NULL
        ["country_id"]=>
        int(3)
        ["created_at"]=>
        string(19) "2017-11-13 16:21:15"
        ["updated_at"]=>
        string(19) "2017-11-06 19:01:54"
      }

As you can see the address location array is found twice the first one which was changed as expected and the second one which is protected and did not change the problem is with is line right here

["address"]=>
        string(61) "Shop 2197 - Block 1014 - Road 90 - Al-Delaa' Complex - Hamala"

Body:
If your string has a single quote, the string variable you are passing to JSON.parse() wont work because the method doesnt accept them.

Try first declaring the '{!! $locations !!}' into a variable before parsing it and see if that works, it shouldnt.

You will have to manually escape the single quote with \'

Example:

var aString = '{ "name":"John", "age":30, "city":"New\'York"}'
var aJson = JSON.parse(aString)


问:
Loop for variables (Xcode 9 - swift 4)
I have I think a stupid question for you, but I start Xcode just one week ago and I have a problem with a loop condition.

```<code>for index in 1...4 {
    AvatarPlayer1.layer.borderWidth = 4
    AvatarPlayer1.layer.cornerRadius = 8
    AvatarPlayer1.layer.borderColor = UIColor.white.cgColor
    AvatarPlayer1.layer.masksToBounds = false
    AvatarPlayer1.clipsToBounds = true //Mask for picture
}
</code>```

How can I change the 1 value by for number in the loop.
I have try + , + \(index), + index.

答:
You cannot change a variable name in code. Instead, start with an array of your four AvatarPlayer objects and cycle through the array:

```<code>let myArrayOfAvatarPlayers = [AvatarPlayer1, AvatarPlayer2, AvatarPlayer3, AvatarPlayer4]
for thisPlayer in myArrayOfAvatarPlayers {
    thisPlayer.layer.borderWidth = 4
    thisPlayer.layer.cornerRadius = 8
    thisPlayer.layer.borderColor = UIColor.white.cgColor
    thisPlayer.layer.masksToBounds = false
    thisPlayer.clipsToBounds = true //Mask for picture
}
</code>```

Title: Loop for variables (Xcode 9 - swift 4)

Body:
I have I think a stupid question for you, but I start Xcode just one week ago and I have a problem with a loop condition.

for index in 1...4 {
    AvatarPlayer1.layer.borderWidth = 4
    AvatarPlayer1.layer.cornerRadius = 8
    AvatarPlayer1.layer.borderColor = UIColor.white.cgColor
    AvatarPlayer1.layer.masksToBounds = false
    AvatarPlayer1.clipsToBounds = true //Mask for picture
}

How can I change the 1 value by for number in the loop.
I have try + , + \(index), + index.

Body:
You cannot change a variable name in code. Instead, start with an array of your four AvatarPlayer objects and cycle through the array:

let myArrayOfAvatarPlayers = [AvatarPlayer1, AvatarPlayer2, AvatarPlayer3, AvatarPlayer4]
for thisPlayer in myArrayOfAvatarPlayers {
    thisPlayer.layer.borderWidth = 4
    thisPlayer.layer.cornerRadius = 8
    thisPlayer.layer.borderColor = UIColor.white.cgColor
    thisPlayer.layer.masksToBounds = false
    thisPlayer.clipsToBounds = true //Mask for picture
}


问:
NSURL doesn't like get variables
I'm getting an error when I pass a string to an NSURL.

```<code>Entity: line 6: parser error : EntityRef: expecting ';'
zzzzzzz.com/feeds/rss/zzzz/zzzz/get_feed.php?c=zzzz&s=zzzz&f
</code>```

It doesn't stop the app or anything but I feel like it should be addressed.  Looks like it doesn't like the & symbol.  I tried replacing with & but that doesn't do the trick.

```<code>NSString *blogAddress = @"http://zzzzzz.com/feeds/rss/zzzz/zzzz/get_feed.php?c=zzzz&s=zzzz&f=most_recent";
NSURL *url = [NSURL URLWithString: blogAddress];
CXMLDocument *rssParser = [[[CXMLDocument alloc] initWithContentsOfURL:url options:0 error:nil] autorelease];
</code>```

答:
You need to URLEncode your String.  I used a category to do it:

URLUtils.h:

```<code>@interface NSString (URLUtils)

- (NSString *) urlEncodeValue;

@end
</code>```

URLUtils.m:

```<code>#import "URLUtils.h"

@implementation NSString (URLUtils)

- (NSString *) urlEncodeValue {
    return (NSString *) CFURLCreateStringByAddingPercentEscapes(NULL,
                                                               (CFStringRef) self,
                                                               NULL,
                                                               (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                               kCFStringEncodingUTF8 );
}

@end
</code>```

Then after including URLUtils.h in your class, you can do this:

```<code>NSURL *url = [NSURL URLWithString: [blogAddress urlEncodeValue]];
</code>```

That should do it.

Good Luck!

Title: NSURL doesn't like get variables

Body:
I'm getting an error when I pass a string to an NSURL.

Entity: line 6: parser error : EntityRef: expecting ';'
zzzzzzz.com/feeds/rss/zzzz/zzzz/get_feed.php?c=zzzz&s=zzzz&f

It doesn't stop the app or anything but I feel like it should be addressed.  Looks like it doesn't like the & symbol.  I tried replacing with & but that doesn't do the trick.

NSString *blogAddress = @"http://zzzzzz.com/feeds/rss/zzzz/zzzz/get_feed.php?c=zzzz&s=zzzz&f=most_recent";
NSURL *url = [NSURL URLWithString: blogAddress];
CXMLDocument *rssParser = [[[CXMLDocument alloc] initWithContentsOfURL:url options:0 error:nil] autorelease];

Body:
You need to URLEncode your String.  I used a category to do it:

URLUtils.h:

@interface NSString (URLUtils)

- (NSString *) urlEncodeValue;

@end

URLUtils.m:

#import "URLUtils.h"

@implementation NSString (URLUtils)

- (NSString *) urlEncodeValue {
    return (NSString *) CFURLCreateStringByAddingPercentEscapes(NULL,
                                                               (CFStringRef) self,
                                                               NULL,
                                                               (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                               kCFStringEncodingUTF8 );
}

@end

Then after including URLUtils.h in your class, you can do this:

NSURL *url = [NSURL URLWithString: [blogAddress urlEncodeValue]];

That should do it.

Good Luck!


问:
What exactly Looper and Handler used for?
I'm learning about Looper Handler and I found that mostly this is being used for working with UI thread. Then I'm little confused when we need child class of Handler and use of handleMessage method.

Example we can work with UI thread by just simple example.

```<code>Handler handler = new Handler();
handler.post(new Runnable(){
  public void run(){
    // update UI here
  }
});
</code>```

We can easily communicate with UI thread by just short code. Here handler will automatically will be connected with MainLooper.

Then when wee need to use child class of Handler and working with handleMessage(Message msg) method.

答:
Looper is a class used to run a message loop for a thread. Threads by
default do not have a message loop associated with them; to create
one, call prepare() in the thread that is to run the loop, and then
loop() to have it process messages until the loop is stopped.

Read more about Looper class here.

There are two main uses for a Handler: (1) to schedule messages and
runnables to be executed as some point in the future; and (2) to
enqueue an action to be performed on a different thread than your own.

Read more about Handler class here.

Body:
I'm learning about Looper Handler and I found that mostly this is being used for working with UI thread. Then I'm little confused when we need child class of Handler and use of handleMessage method.

Example we can work with UI thread by just simple example.

Handler handler = new Handler();
handler.post(new Runnable(){
  public void run(){
    // update UI here
  }
});

We can easily communicate with UI thread by just short code. Here handler will automatically will be connected with MainLooper.

Then when wee need to use child class of Handler and working with handleMessage(Message msg) method.


问:
Cluster bounding boxes and draw line on them (OpenCV, Python)
With this code I created some bounding boxes around the characters in the below image:

```<code>import csv
import cv2
from pytesseract import pytesseract as pt

pt.run_tesseract('bb.png', 'output', lang=None, boxes=True, config="hocr")

# To read the coordinates
boxes = []
with open('output.box', 'rt') as f:
    reader = csv.reader(f, delimiter=' ')
    for row in reader:
        if len(row) == 6:
            boxes.append(row)

# Draw the bounding box
img = cv2.imread('bb.png')
h, w, _ = img.shape
for b in boxes:
    img = cv2.rectangle(img, (int(b[1]), h-int(b[2])), (int(b[3]), h-int(b[4])), (0, 255, 0), 2)

cv2.imshow('output', img)
cv2.waitKey(0)
</code>```

OUTPUT

What I would like to have is this:

The program should draw a perpendicular line on the X axis of the bounding box (only for the first and third text-area. The one in the middle must not be interested in the process).

The goal is this (and of there is another way to achieve it, please explain): once I have this two lines (or, better, group of coordinates), using a mask to cover this two areas.

Is it possible ?

Source image:

CSV as requested:
print(boxes)

```<code>[['l', '56', '328', '63', '365', '0'], ['i', '69', '328', '76', '365', '0'], ['n', '81', '328', '104', '354', '0'], ['e', '108', '328', '130', '354', '0'], ['1', '147', '328', '161', '362', '0'], ['m', '102', '193', '151', '227', '0'], ['i', '158', '193', '167', '242', '0'], ['d', '173', '192', '204', '242', '0'], ['d', '209', '192', '240', '242', '0'], ['l', '247', '193', '256', '242', '0'], ['e', '262', '192', '292', '227', '0'], ['t', '310', '192', '331', '235', '0'], ['e', '334', '192', '364', '227', '0'], ['x', '367', '193', '398', '227', '0'], ['t', '399', '192', '420', '235', '0'], ['-', '440', '209', '458', '216', '0'], ['n', '481', '193', '511', '227', '0'], ['o', '516', '192', '548', '227', '0'], ['n', '553', '193', '583', '227', '0'], ['t', '602', '192', '623', '235', '0'], ['o', '626', '192', '658', '227', '0'], ['t', '676', '192', '697', '235', '0'], ['o', '700', '192', '732', '227', '0'], ['u', '737', '192', '767', '227', '0'], ['c', '772', '192', '802', '227', '0'], ['h', '806', '193', '836', '242', '0'], ['l', '597', '49', '604', '86', '0'], ['i', '610', '49', '617', '86', '0'], ['n', '622', '49', '645', '75', '0'], ['e', '649', '49', '671', '75', '0'], ['2', '686', '49', '710', '83', '0']]
</code>```

EDIT:

To use zindarod answer, you need tesserocr. Installation through pip install tesserocr can give you various errors.
I found wheel version of it (after hours trying to install and solve errors, see my comment below the answer...): here you can find/download it.

Hope this helps..

答:
Googles tesseract-ocr already has this functionality in page segmentation method(psm). You just need to use a better python wrapper, which exposes more of tesseract's functionalities than pytesseract does. One of the better ones is tesserocr.

A simple example with your image:

```<code>  import cv2
  import numpy as np
  import tesserocr as tr
  from PIL import Image

  cv_img = cv2.imread('text.png', cv2.IMREAD_UNCHANGED)

  # since tesserocr accepts PIL images, converting opencv image to pil
  pil_img = Image.fromarray(cv2.cvtColor(cv_img,cv2.COLOR_BGR2RGB))

  #initialize api
  api = tr.PyTessBaseAPI()
  try:
    # set pil image for ocr
    api.SetImage(pil_img)
    # Google tesseract-ocr has a page segmentation methos(psm) option for specifying ocr types
    # psm values can be: block of text, single text line, single word, single character etc.
    # api.GetComponentImages method exposes this functionality
    # function returns:
    # image (:class:`PIL.Image`): Image object.
    # bounding box (dict): dict with x, y, w, h keys.
    # block id (int): textline block id (if blockids is ``True``). ``None`` otherwise.
    # paragraph id (int): textline paragraph id within its block (if paraids is True).
    # ``None`` otherwise.
    boxes = api.GetComponentImages(tr.RIL.TEXTLINE,True)
    # get text
    text = api.GetUTF8Text()
    # iterate over returned list, draw rectangles
    for (im,box,_,_) in boxes:
      x,y,w,h = box['x'],box['y'],box['w'],box['h']
      cv2.rectangle(cv_img, (x,y), (x+w,y+h), color=(0,0,255))
  finally:
    api.End()

  cv2.imshow('output', cv_img)
  cv2.waitKey(0)
  cv2.destroyAllWindows()
</code>```

Body:
With this code I created some bounding boxes around the characters in the below image:

import csv
import cv2
from pytesseract import pytesseract as pt

pt.run_tesseract('bb.png', 'output', lang=None, boxes=True, config="hocr")

# To read the coordinates
boxes = []
with open('output.box', 'rt') as f:
    reader = csv.reader(f, delimiter=' ')
    for row in reader:
        if len(row) == 6:
            boxes.append(row)

# Draw the bounding box
img = cv2.imread('bb.png')
h, w, _ = img.shape
for b in boxes:
    img = cv2.rectangle(img, (int(b[1]), h-int(b[2])), (int(b[3]), h-int(b[4])), (0, 255, 0), 2)

cv2.imshow('output', img)
cv2.waitKey(0)

OUTPUT

What I would like to have is this:

The program should draw a perpendicular line on the X axis of the bounding box (only for the first and third text-area. The one in the middle must not be interested in the process).

The goal is this (and of there is another way to achieve it, please explain): once I have this two lines (or, better, group of coordinates), using a mask to cover this two areas.

Is it possible ?

Source image:

CSV as requested:
print(boxes)

[['l', '56', '328', '63', '365', '0'], ['i', '69', '328', '76', '365', '0'], ['n', '81', '328', '104', '354', '0'], ['e', '108', '328', '130', '354', '0'], ['1', '147', '328', '161', '362', '0'], ['m', '102', '193', '151', '227', '0'], ['i', '158', '193', '167', '242', '0'], ['d', '173', '192', '204', '242', '0'], ['d', '209', '192', '240', '242', '0'], ['l', '247', '193', '256', '242', '0'], ['e', '262', '192', '292', '227', '0'], ['t', '310', '192', '331', '235', '0'], ['e', '334', '192', '364', '227', '0'], ['x', '367', '193', '398', '227', '0'], ['t', '399', '192', '420', '235', '0'], ['-', '440', '209', '458', '216', '0'], ['n', '481', '193', '511', '227', '0'], ['o', '516', '192', '548', '227', '0'], ['n', '553', '193', '583', '227', '0'], ['t', '602', '192', '623', '235', '0'], ['o', '626', '192', '658', '227', '0'], ['t', '676', '192', '697', '235', '0'], ['o', '700', '192', '732', '227', '0'], ['u', '737', '192', '767', '227', '0'], ['c', '772', '192', '802', '227', '0'], ['h', '806', '193', '836', '242', '0'], ['l', '597', '49', '604', '86', '0'], ['i', '610', '49', '617', '86', '0'], ['n', '622', '49', '645', '75', '0'], ['e', '649', '49', '671', '75', '0'], ['2', '686', '49', '710', '83', '0']]

EDIT:

To use zindarod answer, you need tesserocr. Installation through pip install tesserocr can give you various errors.
I found wheel version of it (after hours trying to install and solve errors, see my comment below the answer...): here you can find/download it.

Hope this helps..

Body:
Googles tesseract-ocr already has this functionality in page segmentation method(psm). You just need to use a better python wrapper, which exposes more of tesseract's functionalities than pytesseract does. One of the better ones is tesserocr.

A simple example with your image:

  import cv2
  import numpy as np
  import tesserocr as tr
  from PIL import Image

  cv_img = cv2.imread('text.png', cv2.IMREAD_UNCHANGED)

  # since tesserocr accepts PIL images, converting opencv image to pil
  pil_img = Image.fromarray(cv2.cvtColor(cv_img,cv2.COLOR_BGR2RGB))

  #initialize api
  api = tr.PyTessBaseAPI()
  try:
    # set pil image for ocr
    api.SetImage(pil_img)
    # Google tesseract-ocr has a page segmentation methos(psm) option for specifying ocr types
    # psm values can be: block of text, single text line, single word, single character etc.
    # api.GetComponentImages method exposes this functionality
    # function returns:
    # image (:class:`PIL.Image`): Image object.
    # bounding box (dict): dict with x, y, w, h keys.
    # block id (int): textline block id (if blockids is ``True``). ``None`` otherwise.
    # paragraph id (int): textline paragraph id within its block (if paraids is True).
    # ``None`` otherwise.
    boxes = api.GetComponentImages(tr.RIL.TEXTLINE,True)
    # get text
    text = api.GetUTF8Text()
    # iterate over returned list, draw rectangles
    for (im,box,_,_) in boxes:
      x,y,w,h = box['x'],box['y'],box['w'],box['h']
      cv2.rectangle(cv_img, (x,y), (x+w,y+h), color=(0,0,255))
  finally:
    api.End()

  cv2.imshow('output', cv_img)
  cv2.waitKey(0)
  cv2.destroyAllWindows()


问:
No matching client found for package name (Google Analytics) - multiple productFlavors & buildTypes
Context:

I'm trying to set up Google Analytics for my app. (having 4 custom buildTypes and more than a few productFlavors)

It works fine when I select the Build Variant which has the applicationId set to com.my.app.package.name (the package name used when generating the google-services.json). But, my other flavors have different applicationIds.

I followed the offical devguide to set it up.

Error I get when any another build variant is selected in Build Variants Tab (which has a different applicationId (package name) is as follows:

Error:Execution failed for task
  ':app:processAllcategoriesDebugfreeGoogleServices'.

No matching client found for package name 'com.my.app.package.name.debug'

Explanation of Error Message:

In the task name in the error message above Debugfree is my custom buildType and Allcategories is one of my productFlavors.

I understand the error and know the package name is different from what i used when generating the json, but that is what I'm trying to figure a way around.

Problem:

Now, the google-services.json resides in the app folder and hence I am not being able to separate them out for each product flavor by dropping them in the flavor specific source set folder.

Questions:

My custom byildType for debugging suffixes .debug to the applicationId (package name). Is there a way I can make it work with the google-services.json which has my release applicationId (i.e. without the suffix .debug)

Is there a way to have multiple product flavors configured in the same google-services.json file without using separate files and tasks to copy the required file to app folder. I know it can be done using task as mentioned in this post. Is there a simpler way to just have one file or pick right file based on gradle configuration?

I see the package_name field in google-services.json has the package name com.my.app.package.name. Can I add multiple package names manually to work for all build variants? If yes, how to do that? Could not find any instructions in documentations.

答: go your project directory and create folders on app/src path that named your product flavors (like Alpha, Beta, Store or what ever your flavor's name is). then copy your google-services.json file to each folder. don't forget to change "package_name" field on your each product flavor's google-services.json file that you subfoldered.</p>


问:
OSError: Unable to locate Ghostscript on paths
I tried to open an EPS image with Pyzo, I have installed PIL and Ghostscript (as I saw that it is necessary on some other website topics), my code is:

```<code>from PIL import Image
im = Image.open('''myimage.eps''')
im.show()
</code>```

but when I run the code, Pyzo return me:

OSError: Unable to locate Ghostscript on paths

I tried to look into it on several websites but it seems pretty complicated for a novice coding student.

答:
In case someone else encounters this issue: It seems that Ghostscript has not been added to the paths properly. For those running Win7, here is a fix:

Go to:
Control Panel -> System -> Advanced system settings -> Environment Variables...

Find the variable "PATH" -> Edit... -> add the path to your ghostscript binary folder, e.g.

C:\Program Files\gs\gs9.22\bin\;

to the end of the variable. It should be separated from the previous entry by a semicolon.

I had to restart for the changes to take effect.

ContentLicense: CC BY-SA 4.0

Body:
I tried to open an EPS image with Pyzo, I have installed PIL and Ghostscript (as I saw that it is necessary on some other website topics), my code is:

from PIL import Image
im = Image.open('''myimage.eps''')
im.show()

but when I run the code, Pyzo return me:

OSError: Unable to locate Ghostscript on paths

I tried to look into it on several websites but it seems pretty complicated for a novice coding student.


问:
Command Prompt cannot find or run my Java File
New programmer here, in terms of actually using an editor and running it. I have created a simple program that states this.

```<code>public class HelloWorld {

    public static void main(String[] args) {
        // Prints "Hello, World" to the terminal window.
        System.out.println("Hello, World");
    }
}
</code>```

I have already set the path to "C:\Program Files\Java\jdk1.8.0_151\bin\".(current version"1.8.0_151"). In the cmd input, "java" and "javac" work until I attempt to find a file name either "HelloWorld.java" or "HelloWorld". How do I get cmd to find and run my java file? Thank you!

答:
I did the following steps with your code and it worked:

Open a command prompt in the folder where your HelloWorld.java is saved

Make sure the class name is the same as the file name.

Check if you have added java executable/folder to your system path, you can try: java -version (this should print information about your installed java version)

Compile your code: javac HelloWorld.java

Now there should be a class file generated: HelloWorld.class

Run you main class: java HelloWorld

Note: Without the .class extenstion

Note: use dir instead of ls on Windows to see the files in the current directory

Note: Do you have a package name specified?

Body:
New programmer here, in terms of actually using an editor and running it. I have created a simple program that states this.

public class HelloWorld {

    public static void main(String[] args) {
        // Prints "Hello, World" to the terminal window.
        System.out.println("Hello, World");
    }
}

I have already set the path to "C:\Program Files\Java\jdk1.8.0_151\bin\".(current version"1.8.0_151"). In the cmd input, "java" and "javac" work until I attempt to find a file name either "HelloWorld.java" or "HelloWorld". How do I get cmd to find and run my java file? Thank you!


问:
Spring update scheduler
I have a scheduled job in Spring, I get its cron from my database.
Every time it is executed, the next execution time is updated. So, if it is configured to run every 10 minutes, I can change the value into the database to schedule that job every 15 minutes.

The problem is that I have to wait for the execution to get the updated cron: if a job is scheduled every 15 minutes and I want to change this value to be every 2 minutes, I have to wait for the next execution (up to 15 minutes) to have this job every 2 minutes.

Is there a way to get this job rescheduled after I update the database?

I thought to destroy and refresh this bean, but it is not working (maybe it is not possible or something was wrong in my implementation). Maybe there is a way to trigger an event to execute method configureTask.

Here the snippet of my scheduled job.

```<code>@EnableScheduling
@Component
public class MyClass implements SchedulingConfigurer {

    private static final String JOB = "My personal task";

    @Autowired
    JobRepository jobRepository;

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        scheduledTaskRegistrar.addTriggerTask(new Runnable() {
            @Override
            public void run() {
                System.out.println("Hello World!");
            }
        }, new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
                JobScheduled byJobNameIgnoreCase = jobRepository.findByJobNameIgnoreCase(JOB); // read from database
                String cron = byJobNameIgnoreCase.getCrontab();
                CronTrigger trigger = new CronTrigger(cron);
                return trigger.nextExecutionTime(triggerContext);
            }
        });
    }

}
</code>```

答:
Consider this approach. Instead of adding and deletion scheduled tasks, you may check every minute (or with another precision) actual moment against your views and run necessary tasks immediately. This will be easier. Check Quartz Scheduler, its CronExpression has isSatisfiedBy(Date date) method.</p>

```<code>@Scheduled(cron = "5 * * * * *) // do not set seconds to zero, cause it may fit xx:yy:59
public void runTasks() {
     LocalTime now = LocalTime.now(); // or Date now = new Date();
    // check and run
}
</code>```

Title: Spring update scheduler

Body:
I have a scheduled job in Spring, I get its cron from my database.
Every time it is executed, the next execution time is updated. So, if it is configured to run every 10 minutes, I can change the value into the database to schedule that job every 15 minutes.

The problem is that I have to wait for the execution to get the updated cron: if a job is scheduled every 15 minutes and I want to change this value to be every 2 minutes, I have to wait for the next execution (up to 15 minutes) to have this job every 2 minutes.

Is there a way to get this job rescheduled after I update the database?

I thought to destroy and refresh this bean, but it is not working (maybe it is not possible or something was wrong in my implementation). Maybe there is a way to trigger an event to execute method configureTask.

Here the snippet of my scheduled job.

@EnableScheduling
@Component
public class MyClass implements SchedulingConfigurer {

    private static final String JOB = "My personal task";

    @Autowired
    JobRepository jobRepository;

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        scheduledTaskRegistrar.addTriggerTask(new Runnable() {
            @Override
            public void run() {
                System.out.println("Hello World!");
            }
        }, new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
                JobScheduled byJobNameIgnoreCase = jobRepository.findByJobNameIgnoreCase(JOB); // read from database
                String cron = byJobNameIgnoreCase.getCrontab();
                CronTrigger trigger = new CronTrigger(cron);
                return trigger.nextExecutionTime(triggerContext);
            }
        });
    }

}

Body:
Consider this approach. Instead of adding and deletion scheduled tasks, you may check every minute (or with another precision) actual moment against your views and run necessary tasks immediately. This will be easier. Check Quartz Scheduler, its CronExpression has isSatisfiedBy(Date date) method.

@Scheduled(cron = "5 * * * * *) // do not set seconds to zero, cause it may fit xx:yy:59
public void runTasks() {
     LocalTime now = LocalTime.now(); // or Date now = new Date();
    // check and run
}


问:
JavaScript Tag Cloud with IBM Cognos - IE is null or not an object
I followed a tutorial/modified the code to get a javascript tag cloud working in IBM Cognos (BI software). The tag cloud works fine in FireFox but in Internet Explorer I get the error:

"Message: '1' is null or not an object"

The line of code where this is present is 225 which is:

```<code>var B = b[1].toLowerCase();
</code>```

I have tried many different solutions that I have seen but have been unable to get this working correctly, the rest of the code is as follows:

```<code><script>
// JavaScript Document
// ====================================
// params that might need changin.
// DON'T forget to include a drill url in the href section below (see ###) if you want this report to be drillable
var delimit = "|";
var subdelimit = "[]"; // change this as needed (ex: Smith, Michael[]$500,000.00|)
var labelColumnNumber = 0; // first column is 0
var valueColumnNumber = 1;
var columnCount = 2; // how many columns are there in the list?
// ====================================

/*
function formatCurrency(num) {
num = num.toString().replace(/\$|\,/g,'');
if(isNaN(num))
num = "0";
sign = (num == (num = Math.abs(num)));
num = Math.floor(num*100+0.50000000001);
cents = num%100;
num = Math.floor(num/100).toString();
if(cents<10)
cents = "0" + cents;
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
num = num.substring(0,num.length-(4*i+3))+','+ num.substring(num.length-(4*i+3));
return (((sign)?'':'-') + '$' + num + '.' + cents);
}
*/
function formatCurrency(num) {
num = num.toString().replace(/\$|\,/g,'');
if(isNaN(num))
num = "0";
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
num = num.substring(0,num.length-(4*i+3))+','+ num.substring(num.length-(4*i+3));
return ( num );
}

function filterNum(str) {
re = /\$|,|@|#|~|`|\%|\*|\^|\&|\(|\)|\+|\=|\[|\-|\_|\]|\[|\}|\{|\;|\:|\'|\"|\<|\>|\?|\||\\|\!|\$|/g;
// remove special characters like "$" and "," etc...
return str.replace(re, "");
}

table = document.getElementById("dg");

if ( table.style.visibility != 'hidden'){ //only for visible
/*alert('Visible');*/

tags = document.getElementById("dg").getElementsByTagName("SPAN");

txt = "";
var newText = "a";
    for (var i=columnCount; i<tags.length; i++) {
/*
valu = filterNum(tags[i+valueColumnNumber].innerHTML);
txt += valu;
txt += subdelimit+tags[i+labelColumnNumber].innerHTML+delimit;
i = i+columnCount;
*/
        if(i%2!=0){
            var newValue = filterNum(tags[i].innerHTML);
        }else var newName =tags[i].innerHTML;

                if((i>2) & (i%2!=0)){
                    newText = newText+newValue+subdelimit+newName+delimit;
                        if(typeof newText != 'undefined'){
                            txt = newText;
                            txt = txt.substr(9);
                    /*      alert(txt);*/
                        }
                }
    }

}/*else alert ('Hidden');*/

function getFontSize(min,max,val) {
return Math.round((150.0*(1.0+(1.5*val-max/2)/max)));
}

function generateCloud(txt) {
//var txt = "48.1[]Google|28.1[]Yahoo!|10.5[]Live/MSN|4.9[]Ask|5[]AOL";
var logarithmic = false;
var lines = txt.split(delimit);
var min = 10000000000;
var max = 0;
for(var i=0;i<lines.length;i++) {
var line = lines[i];
var data = line.split(subdelimit);
if(data.length != 2) {
lines.splice(i,1);
continue;
}
data[0] = parseFloat(data[0]);
lines[i] = data;
if(data[0] > max)
max = data[0];
if(data[0] < min)
min = data[0];
}lines.sort(function (a,b) {
var A = a[1].toLowerCase();
var B = b[1].toLowerCase();
return A>B ? 1 : (A<B ? -1 : 0);
});

var html = "<style type='text/css'>#jscloud a:hover { text-decoration: underline; }</style> <div id='jscloud'>";
if(logarithmic) {
max = Math.log(max);
min = Math.log(min);
}
for(var i=0;i<lines.length;i++) {
var val = lines[i][0];
if(logarithmic) val = Math.log(val);
var fsize = getFontSize(min,max,val);
dollar = formatCurrency(lines[i][0]);
html += " <a href='###Some drillthrough url which includes the param "+lines[i][1]+"' style='font-size:"+fsize+"%;' title='"+dollar+"'>"+lines[i][1]+"</a> ";
}
html += "</div>";
var cloud = document.getElementById("cloud");
cloud.innerHTML = html;
var cloudhtml = document.getElementById("cloudhtml");
cloudhtml.value = html;
}
function setClass(layer,cls) {
layer.setAttribute("class",cls);
layer.setAttribute("className",cls);
}
function show(display) {
var cloud = document.getElementById("cloud");
var cloudhtml = document.getElementById("cloudhtml");if(display == "cloud") {
setClass(cloud,"visible");
setClass(cloudhtml,"hidden");
}
else if(display == "html") {
setClass(cloud,"hidden");
setClass(cloudhtml,"visible");
}
}
generateCloud(txt);
</script>
</code>```

Any help or explanations is much appreciated

答: Sorry, I'm not seeing where a[] and b[] are defined, is this done elsewhere?  Firefox and IE may be responding differently to the problem of an undefined array.</p>

Body:
I followed a tutorial/modified the code to get a javascript tag cloud working in IBM Cognos (BI software). The tag cloud works fine in FireFox but in Internet Explorer I get the error:

"Message: '1' is null or not an object"

The line of code where this is present is 225 which is:

var B = b[1].toLowerCase();

I have tried many different solutions that I have seen but have been unable to get this working correctly, the rest of the code is as follows:

Any help or explanations is much appreciated


问:
Handling Unicode sequences in postgresql
I have some JSON data stored in a JSON (not JSONB) column in my postgresql database (9.4.1). Some of these JSON structures contain unicode sequences in their attribute values. For example:

```<code>{"client_id": 1, "device_name": "FooBar\ufffd\u0000\ufffd\u000f\ufffd" }
</code>```

When I try to query this JSON column (even if I'm not directly trying to access the device_name attribute), I get the following error:

ERROR: unsupported Unicode escape sequence

  Detail: \u0000 cannot be converted to text.

You can recreate this error by executing the following command on a postgresql server:

```<code>select '{"client_id": 1, "device_name": "FooBar\ufffd\u0000\ufffd\u000f\ufffd" }'::json->>'client_id'
</code>```

The error makes sense to me - there is simply no way to represent the unicode sequence NULL in a textual result.

Is there any way for me to query the same JSON data without having to perform "sanitation" on the incoming data? These JSON structures change regularly so scanning a specific attribute (device_name in this case) would not be a good solution since there could easily be other attributes that might hold similar data.

After some more investigations, it seems that this behavior is new for version 9.4.1 as mentioned in the changelog:

...Therefore \u0000 will now also be rejected in json values when conversion to de-escaped form is required. This change does not break the ability to store \u0000 in json columns so long as no processing is done on the values...

Was this really the intention? Is a downgrade to pre 9.4.1 a viable option here?

As a side note, this property is taken from the name of the client's mobile device - it's the user that entered this text into the device. How on earth did a user insert NULL and REPLACEMENT CHARACTER values?!

答:
The solution by Patrick didn't work out of the box for me. Regardless there was always an error thrown. I then researched a little more and was able to write a small custom function that fixed the issue for me.

First I could reproduce the error by writing:

```<code>select json '{ "a":  "null \u0000 escape" }' ->> 'a' as fails
</code>```

Then I added a custom function which I used in my query:

```<code>CREATE OR REPLACE FUNCTION null_if_invalid_string(json_input JSON, record_id UUID)
  RETURNS JSON AS $$
DECLARE json_value JSON DEFAULT NULL;
BEGIN
  BEGIN
    json_value := json_input ->> 'location';
    EXCEPTION WHEN OTHERS
    THEN
      RAISE NOTICE 'Invalid json value: "%".  Returning NULL.', record_id;
      RETURN NULL;
  END;
  RETURN json_input;
END;
$$ LANGUAGE plpgsql;
</code>```

To call the function do this. You should not receive an error.

```<code>select null_if_invalid_string('{ "a":  "null \u0000 escape" }', id) from my_table
</code>```

Whereas this should return the json as expected:

```<code>select null_if_invalid_string('{ "a":  "null" }', id) from my_table
</code>```

Body:
I have some JSON data stored in a JSON (not JSONB) column in my postgresql database (9.4.1). Some of these JSON structures contain unicode sequences in their attribute values. For example:

{"client_id": 1, "device_name": "FooBar\ufffd\u0000\ufffd\u000f\ufffd" }

When I try to query this JSON column (even if I'm not directly trying to access the device_name attribute), I get the following error:

ERROR: unsupported Unicode escape sequence

  Detail: \u0000 cannot be converted to text.

You can recreate this error by executing the following command on a postgresql server:

select '{"client_id": 1, "device_name": "FooBar\ufffd\u0000\ufffd\u000f\ufffd" }'::json->>'client_id'

The error makes sense to me - there is simply no way to represent the unicode sequence NULL in a textual result.

Is there any way for me to query the same JSON data without having to perform "sanitation" on the incoming data? These JSON structures change regularly so scanning a specific attribute (device_name in this case) would not be a good solution since there could easily be other attributes that might hold similar data.

After some more investigations, it seems that this behavior is new for version 9.4.1 as mentioned in the changelog:

...Therefore \u0000 will now also be rejected in json values when conversion to de-escaped form is required. This change does not break the ability to store \u0000 in json columns so long as no processing is done on the values...

Was this really the intention? Is a downgrade to pre 9.4.1 a viable option here?

As a side note, this property is taken from the name of the client's mobile device - it's the user that entered this text into the device. How on earth did a user insert NULL and REPLACEMENT CHARACTER values?!

Body:
The solution by Patrick didn't work out of the box for me. Regardless there was always an error thrown. I then researched a little more and was able to write a small custom function that fixed the issue for me.

First I could reproduce the error by writing:

select json '{ "a":  "null \u0000 escape" }' ->> 'a' as fails

Then I added a custom function which I used in my query:

CREATE OR REPLACE FUNCTION null_if_invalid_string(json_input JSON, record_id UUID)
  RETURNS JSON AS $$
DECLARE json_value JSON DEFAULT NULL;
BEGIN
  BEGIN
    json_value := json_input ->> 'location';
    EXCEPTION WHEN OTHERS
    THEN
      RAISE NOTICE 'Invalid json value: "%".  Returning NULL.', record_id;
      RETURN NULL;
  END;
  RETURN json_input;
END;
$$ LANGUAGE plpgsql;

To call the function do this. You should not receive an error.

select null_if_invalid_string('{ "a":  "null \u0000 escape" }', id) from my_table

Whereas this should return the json as expected:

select null_if_invalid_string('{ "a":  "null" }', id) from my_table


问:
(Can I?) How can I access the int value of the next node (tree recursion)
So I have a tree defined as follows:

```<code>data Tree = Node Tree Int Tree | Leaf Int
</code>```

The Int for a Node in this case is the value at that Node. I am trying to check that a tree is balanced, and that the tree is increasing as it's traversed left to right.

To do so I have a recursive function that takes a (Node left x right) and checks that the difference in height of left and right (the nodes below it) is no more than one. I then call balanced again for left and right.

Is it possible to access the Int value of left and right?

答:
Of course you can, instead of put variables like left and right, use the constructors again:

Edit, I forget the case of Leaf, it has also an int:

```<code>data Tree = Node Tree Int Tree | Leaf Int

exampleSumNodes (Node left x right) = (treeToInt left) + x + (treeToInt right)

treeToInt (Node _ n _) = n
treeToInt (Leaf n ) = n
</code>```

Body:
So I have a tree defined as follows:

data Tree = Node Tree Int Tree | Leaf Int

The Int for a Node in this case is the value at that Node. I am trying to check that a tree is balanced, and that the tree is increasing as it's traversed left to right.

To do so I have a recursive function that takes a (Node left x right) and checks that the difference in height of left and right (the nodes below it) is no more than one. I then call balanced again for left and right.

Is it possible to access the Int value of left and right?

Body:
Of course you can, instead of put variables like left and right, use the constructors again:

Edit, I forget the case of Leaf, it has also an int:

data Tree = Node Tree Int Tree | Leaf Int

exampleSumNodes (Node left x right) = (treeToInt left) + x + (treeToInt right)

treeToInt (Node _ n _) = n
treeToInt (Leaf n ) = n