问:
How to add a RGBA color to google line chart?
I am trying to embed google line chart in a client's website, which will be generated on basis of some php variables in run-time. The issue that I am facing is, the chart's parent's background  ( on which the chart is kept) that I am using is in rgba(0,0,0,.7) format, which gives a transparent feel to the background not to the content, and the background that google api gives is a white one, I tried to change the color of the background, but it accepts hex values "#000", which do not provide transparency. Can anyone suggest a way to give a rgba() as color to google chart. Sorry I cannot share the exact code, but the below can be taken as reference.

```<code>  <html>
  <head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
      google.charts.load('current', {'packages':['corechart']});
      google.charts.setOnLoadCallback(drawChart);

      function drawChart() {
        var data = google.visualization.arrayToDataTable([
          ['Year', 'Sales', 'Expenses'],
          ['2004',  1000,      400],
          ['2005',  1170,      460],
          ['2006',  660,       1120],
          ['2007',  1030,      540]
        ]);

        var options = {
          title: 'Company Performance',
          curveType: 'function',
          legend: { position: 'bottom' },
          backgroundColor:'#000';
        };

        var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));

        chart.draw(data, options);
      }
    </script>
  </head>
  <body>
    <div id="curve_chart" style="width: 900px; height: 500px"></div>
  </body>
</html>
</code>```

I went through this and this but cannot find an answer to my question. Please suggest a simple way out.

答:
try with

```<code>    backgroundColor: {
      'fill': '#000',
      'fillOpacity': 0.1
    },
</code>```

this uses hex color with opacity for transparent

```

Body:
I am trying to embed google line chart in a client's website, which will be generated on basis of some php variables in run-time. The issue that I am facing is, the chart's parent's background  ( on which the chart is kept) that I am using is in rgba(0,0,0,.7) format, which gives a transparent feel to the background not to the content, and the background that google api gives is a white one, I tried to change the color of the background, but it accepts hex values "#000", which do not provide transparency. Can anyone suggest a way to give a rgba() as color to google chart. Sorry I cannot share the exact code, but the below can be taken as reference.

I went through this and this but cannot find an answer to my question. Please suggest a simple way out.

Body:
try with

    backgroundColor: {
      'fill': '#000',
      'fillOpacity': 0.1
    },

this uses hex color with opacity for transparent

<html>

<head>
  <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
  <script type="text/javascript">
    google.charts.load('current', {
      'packages': ['corechart']
    });
    google.charts.setOnLoadCallback(drawChart);

    function drawChart() {
      var data = google.visualization.arrayToDataTable([
        ['Year', 'Sales', 'Expenses'],
        ['2004', 1000, 400],
        ['2005', 1170, 460],
        ['2006', 660, 1120],
        ['2007', 1030, 540]
      ]);

      var options = {
        title: 'Company Performance',
        curveType: 'function',
        legend: {
          position: 'bottom'
        },
        backgroundColor: {
          'fill': '#000',
          'fillOpacity': 0.1
        },

      };

      var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));

      chart.draw(data, options);
    }
  </script>
</head>

<body>
  <div id="curve_chart" style="width: 900px; height: 500px"></div>
</body>

</html>


来源: stackexchange

问:
Custom Theano Op to do numerical integration
I'm attempting to write a custom Theano Op which numerically integrates a function between two values. The Op is a custom likelihood for PyMC3 which involves the numerical evaluation of some integrals. I can't simply use the @as_op decorator as I need to use HMC to do the MCMC step. Any help would be much appreciated, as this question seems to have come up several times but has never been solved (e.g. https://stackoverflow.com/questions/36853015/using-theano-with-numerical-integration, Theano: implementing an integral function).

Clearly one solution would be to write a numerical integrator within Theano, but this seems like a waste of effort when very good integrators are already available, for example through scipy.integrate.

To keep this as a minimal example, let's just try and integrate a function between 0 and 1 inside an Op. The following integrates a Theano function outside of an Op, and produces correct results as far as my testing has gone.

```<code>import theano
import theano.tensor as tt
from scipy.integrate import quad

x = tt.dscalar('x')
y = x**4 # integrand
f = theano.function([x], y)

print f(0)
print f(1)

ans = integrate.quad(f, 0, 1)[0]

print ans
</code>```

However, attempting to do integration within an Op appears much harder. My current best effort is:

```<code>import numpy as np
import theano
import theano.tensor as tt
from scipy import integrate

class IntOp(theano.Op):
    __props__ = ()

    def make_node(self, x):
        x = tt.as_tensor_variable(x)
        return theano.Apply(self, [x], [x.type()])

    def perform(self, node, inputs, output_storage):
        x = inputs[0]
        z = output_storage[0]

        f_to_int = theano.function([x], x)
        z[0] = tt.as_tensor_variable(integrate.quad(f_to_int, 0, 1)[0])

    def infer_shape(self, node, i0_shapes):
        return i0_shapes

    def grad(self, inputs, output_grads):
        ans = integrate.quad(output_grads[0], 0, 1)[0]
        return [ans]

intOp = IntOp()

x = tt.dmatrix('x')
y = intOp(x)

f = theano.function([x], y)

inp = np.asarray([[2, 4], [6, 8]], dtype=theano.config.floatX)
out = f(inp)

print inp
print out
</code>```

Which gives the following error:

```<code>Traceback (most recent call last):
  File "stackoverflow.py", line 35, in <module>
    out = f(inp)
  File "/usr/local/lib/python2.7/dist-packages/theano/compile/function_module.py", line 871, in __call__
    storage_map=getattr(self.fn, 'storage_map', None))
  File "/usr/local/lib/python2.7/dist-packages/theano/gof/link.py", line 314, in raise_with_op
    reraise(exc_type, exc_value, exc_trace)
  File "/usr/local/lib/python2.7/dist-packages/theano/compile/function_module.py", line 859, in __call__
    outputs = self.fn()
  File "/usr/local/lib/python2.7/dist-packages/theano/gof/op.py", line 912, in rval
    r = p(n, [x[0] for x in i], o)
  File "stackoverflow.py", line 17, in perform
    f_to_int = theano.function([x], x)
  File "/usr/local/lib/python2.7/dist-packages/theano/compile/function.py", line 320, in function
    output_keys=output_keys)
  File "/usr/local/lib/python2.7/dist-packages/theano/compile/pfunc.py", line 390, in pfunc
    for p in params]
  File "/usr/local/lib/python2.7/dist-packages/theano/compile/pfunc.py", line 489, in _pfunc_param_to_in
    raise TypeError('Unknown parameter type: %s' % type(param))
TypeError: Unknown parameter type: <type 'numpy.ndarray'>
Apply node that caused the error: IntOp(x)
Toposort index: 0
Inputs types: [TensorType(float64, matrix)]
Inputs shapes: [(2, 2)]
Inputs strides: [(16, 8)]
Inputs values: [array([[ 2.,  4.],
       [ 6.,  8.]])]
Outputs clients: [['output']]

Backtrace when the node is created(use Theano flag traceback.limit=N to make it longer):
  File "stackoverflow.py", line 30, in <module>
    y = intOp(x)
  File "/usr/local/lib/python2.7/dist-packages/theano/gof/op.py", line 611, in __call__
    node = self.make_node(*inputs, **kwargs)
  File "stackoverflow.py", line 11, in make_node
    return theano.Apply(self, [x], [x.type()])

HINT: Use the Theano flag 'exception_verbosity=high' for a debugprint and storage map footprint of this apply node.
</code>```

I'm surprised by this, especially the TypeError, as I thought I had converted the output_storage variable into a tensor but it appears to believe here that it is still an ndarray.

答:
I found your question because I'm trying to build a random variable in PyMC3 that represents a general point process (Hawkes, Cox, Poisson, etc) and the likelihood function has an integral. I really want to be able to use Hamiltonian Monte Carlo or NUTS samplers, so I needed that integral with respect to time to be differentiable.

Starting off of your attempt, I made an integrateOut theano Op that seems to work correctly with the behavior I need. I've tested it out on a few different inputs (not on my stats model just yet, but it appears promising!). I'm a total theano n00b, so pardon any stupidity. I would greatly appreciate feedback if anyone has any. Not sure it's exactly what you're looking for, but here's my solution (example at the bottom and in the doc strings). *EDIT: simplified some remnants of screwing around with ways to do this.

```<code>import theano
import theano.tensor as T
from scipy.integrate import quad

class integrateOut(theano.Op):
    """
    Integrate out a variable from an expression, computing
    the definite integral w.r.t. the variable specified
    !!! Only implemented in this for scalars !!!

    Parameters
    ----------
    f : scalar
        input 'function' to integrate
    t : scalar
        the variable to integrate out
    t0: float
        lower integration limit
    tf: float
        upper integration limit

    Returns
    -------
    scalar
        a new scalar with the 't' integrated out

    Notes
    -----

    usage of this looks like:
    x = T.dscalar('x')
    y = T.dscalar('y')
    t = T.dscalar('t')

    z = (x**2 + y**2)*t

    # integrate z w.r.t. t as a function of (x,y)
    intZ = integrateOut(z,t,0.0,5.0)(x,y)
    gradIntZ = T.grad(intZ,[x,y])

    funcIntZ = theano.function([x,y],intZ)
    funcGradIntZ = theano.function([x,y],gradIntZ)

    """
    def __init__(self,f,t,t0,tf,*args,**kwargs):
        super(integrateOut,self).__init__()
        self.f = f
        self.t = t
        self.t0 = t0
        self.tf = tf

    def make_node(self,*inputs):
        self.fvars=list(inputs)
        # This will fail when taking the gradient... don't be concerned
        try:
            self.gradF = T.grad(self.f,self.fvars)
        except:
            self.gradF = None
        return theano.Apply(self,self.fvars,[T.dscalar().type()])

    def perform(self,node, inputs, output_storage):
        # Everything else is an argument to the quad function
        args = tuple(inputs)
        # create a function to evaluate the integral
        f = theano.function([self.t]+self.fvars,self.f)
        # actually compute the integral
        output_storage[0][0] = quad(f,self.t0,self.tf,args=args)[0]

    def grad(self,inputs,grads):
        return [integrateOut(g,self.t,self.t0,self.tf)(*inputs)*grads[0] \
            for g in self.gradF]

x = T.dscalar('x')
y = T.dscalar('y')
t = T.dscalar('t')

z = (x**2+y**2)*t

intZ = integrateOut(z,t,0,1)(x,y)
gradIntZ = T.grad(intZ,[x,y])
funcIntZ = theano.function([x,y],intZ)
funcGradIntZ = theano.function([x,y],gradIntZ)
print funcIntZ(2,2)
print funcGradIntZ(2,2)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm attempting to write a custom Theano Op which numerically integrates a function between two values. The Op is a custom likelihood for PyMC3 which involves the numerical evaluation of some integrals. I can't simply use the @as_op decorator as I need to use HMC to do the MCMC step. Any help would be much appreciated, as this question seems to have come up several times but has never been solved (e.g. https://stackoverflow.com/questions/36853015/using-theano-with-numerical-integration, Theano: implementing an integral function).

Clearly one solution would be to write a numerical integrator within Theano, but this seems like a waste of effort when very good integrators are already available, for example through scipy.integrate.

To keep this as a minimal example, let's just try and integrate a function between 0 and 1 inside an Op. The following integrates a Theano function outside of an Op, and produces correct results as far as my testing has gone.

import theano
import theano.tensor as tt
from scipy.integrate import quad

x = tt.dscalar('x')
y = x**4 # integrand
f = theano.function([x], y)

print f(0)
print f(1)

ans = integrate.quad(f, 0, 1)[0]

print ans

However, attempting to do integration within an Op appears much harder. My current best effort is:

import numpy as np
import theano
import theano.tensor as tt
from scipy import integrate

class IntOp(theano.Op):
    __props__ = ()

    def make_node(self, x):
        x = tt.as_tensor_variable(x)
        return theano.Apply(self, [x], [x.type()])

    def perform(self, node, inputs, output_storage):
        x = inputs[0]
        z = output_storage[0]

        f_to_int = theano.function([x], x)
        z[0] = tt.as_tensor_variable(integrate.quad(f_to_int, 0, 1)[0])

    def infer_shape(self, node, i0_shapes):
        return i0_shapes

    def grad(self, inputs, output_grads):
        ans = integrate.quad(output_grads[0], 0, 1)[0]
        return [ans]

intOp = IntOp()

x = tt.dmatrix('x')
y = intOp(x)

f = theano.function([x], y)

inp = np.asarray([[2, 4], [6, 8]], dtype=theano.config.floatX)
out = f(inp)

print inp
print out

Which gives the following error:

Traceback (most recent call last):
  File "stackoverflow.py", line 35, in <module>
    out = f(inp)
  File "/usr/local/lib/python2.7/dist-packages/theano/compile/function_module.py", line 871, in __call__
    storage_map=getattr(self.fn, 'storage_map', None))
  File "/usr/local/lib/python2.7/dist-packages/theano/gof/link.py", line 314, in raise_with_op
    reraise(exc_type, exc_value, exc_trace)
  File "/usr/local/lib/python2.7/dist-packages/theano/compile/function_module.py", line 859, in __call__
    outputs = self.fn()
  File "/usr/local/lib/python2.7/dist-packages/theano/gof/op.py", line 912, in rval
    r = p(n, [x[0] for x in i], o)
  File "stackoverflow.py", line 17, in perform
    f_to_int = theano.function([x], x)
  File "/usr/local/lib/python2.7/dist-packages/theano/compile/function.py", line 320, in function
    output_keys=output_keys)
  File "/usr/local/lib/python2.7/dist-packages/theano/compile/pfunc.py", line 390, in pfunc
    for p in params]
  File "/usr/local/lib/python2.7/dist-packages/theano/compile/pfunc.py", line 489, in _pfunc_param_to_in
    raise TypeError('Unknown parameter type: %s' % type(param))
TypeError: Unknown parameter type: <type 'numpy.ndarray'>
Apply node that caused the error: IntOp(x)
Toposort index: 0
Inputs types: [TensorType(float64, matrix)]
Inputs shapes: [(2, 2)]
Inputs strides: [(16, 8)]
Inputs values: [array([[ 2.,  4.],
       [ 6.,  8.]])]
Outputs clients: [['output']]

Backtrace when the node is created(use Theano flag traceback.limit=N to make it longer):
  File "stackoverflow.py", line 30, in <module>
    y = intOp(x)
  File "/usr/local/lib/python2.7/dist-packages/theano/gof/op.py", line 611, in __call__
    node = self.make_node(*inputs, **kwargs)
  File "stackoverflow.py", line 11, in make_node
    return theano.Apply(self, [x], [x.type()])

HINT: Use the Theano flag 'exception_verbosity=high' for a debugprint and storage map footprint of this apply node.

I'm surprised by this, especially the TypeError, as I thought I had converted the output_storage variable into a tensor but it appears to believe here that it is still an ndarray.

Body:
I found your question because I'm trying to build a random variable in PyMC3 that represents a general point process (Hawkes, Cox, Poisson, etc) and the likelihood function has an integral. I really want to be able to use Hamiltonian Monte Carlo or NUTS samplers, so I needed that integral with respect to time to be differentiable.

Starting off of your attempt, I made an integrateOut theano Op that seems to work correctly with the behavior I need. I've tested it out on a few different inputs (not on my stats model just yet, but it appears promising!). I'm a total theano n00b, so pardon any stupidity. I would greatly appreciate feedback if anyone has any. Not sure it's exactly what you're looking for, but here's my solution (example at the bottom and in the doc strings). *EDIT: simplified some remnants of screwing around with ways to do this.

import theano
import theano.tensor as T
from scipy.integrate import quad

class integrateOut(theano.Op):
    """
    Integrate out a variable from an expression, computing
    the definite integral w.r.t. the variable specified
    !!! Only implemented in this for scalars !!!

    Parameters
    ----------
    f : scalar
        input 'function' to integrate
    t : scalar
        the variable to integrate out
    t0: float
        lower integration limit
    tf: float
        upper integration limit

    Returns
    -------
    scalar
        a new scalar with the 't' integrated out

    Notes
    -----

    usage of this looks like:
    x = T.dscalar('x')
    y = T.dscalar('y')
    t = T.dscalar('t')

    z = (x**2 + y**2)*t

    # integrate z w.r.t. t as a function of (x,y)
    intZ = integrateOut(z,t,0.0,5.0)(x,y)
    gradIntZ = T.grad(intZ,[x,y])

    funcIntZ = theano.function([x,y],intZ)
    funcGradIntZ = theano.function([x,y],gradIntZ)

    """
    def __init__(self,f,t,t0,tf,*args,**kwargs):
        super(integrateOut,self).__init__()
        self.f = f
        self.t = t
        self.t0 = t0
        self.tf = tf

    def make_node(self,*inputs):
        self.fvars=list(inputs)
        # This will fail when taking the gradient... don't be concerned
        try:
            self.gradF = T.grad(self.f,self.fvars)
        except:
            self.gradF = None
        return theano.Apply(self,self.fvars,[T.dscalar().type()])

    def perform(self,node, inputs, output_storage):
        # Everything else is an argument to the quad function
        args = tuple(inputs)
        # create a function to evaluate the integral
        f = theano.function([self.t]+self.fvars,self.f)
        # actually compute the integral
        output_storage[0][0] = quad(f,self.t0,self.tf,args=args)[0]

    def grad(self,inputs,grads):
        return [integrateOut(g,self.t,self.t0,self.tf)(*inputs)*grads[0] \
            for g in self.gradF]

x = T.dscalar('x')
y = T.dscalar('y')
t = T.dscalar('t')

z = (x**2+y**2)*t

intZ = integrateOut(z,t,0,1)(x,y)
gradIntZ = T.grad(intZ,[x,y])
funcIntZ = theano.function([x,y],intZ)
funcGradIntZ = theano.function([x,y],gradIntZ)
print funcIntZ(2,2)
print funcGradIntZ(2,2)


问:
Sort json array by value using PHP
I am trying to sort the array using usort().But my function does not seem to work. I want to sort it by partners_order of each object i.e, $myJson[0] and then $myJson1 separately

The Json array is decoded using $myJson = json_decode($jsonData);

PHP function to sort is written below.

```<code>usort($myJson, function($a, $b) {
return $a->partners->partners_order < $b->partners->partners_order ? -1 : 1;
});
</code>```

Due to restrictions in this site, I cant post the array here. Hence I am forced to use 3rd party site fiddle https://jsfiddle.net/z8s18c21/

any help please ?

答:
I think it might work if you loop over your objects with foreach.

```<code>$myJson = '[
{
    "title":"1st Inning",
    "inning_order":0,
    "partners":[
        {"partners_order":3,"partner_1":{"id":1927312,"runs":31},"partner_2":{"id":1462508,"runs":32}},
        {"partners_order":1,"partner_1":{"id":1927311,"runs":11},"partner_2":{"id":1462508,"runs":12}},
        {"partners_order":2,"partner_1":{"id":1927311,"runs":21},"partner_2":{"id":1462507,"runs":22}}
    ]
},
{
    "title":"2nd Inning",
    "inning_order":1,
    "partners":[
        {"partners_order":2,"partner_1":{"id":927312,"runs":21},"partner_2":{"id":462508,"runs":22}},
        {"partners_order":1,"partner_1":{"id":927311,"runs":11},"partner_2":{"id":462508,"runs":21}},
        {"partners_order":3,"partner_1":{"id":927311,"runs":31},"partner_2":{"id":462507,"runs":32}}
    ]

}
]';

$read_json = json_decode($myJson);

foreach ($read_json as $myJson1) {
  usort($myJson1->partners,function($a, $b) {
    return $a->partners_order <=> $b->partners_order;
  });
}

echo '```';
print_r($read_json);
echo '```';
</code>```

Code has now been tested, because you provided the data objects.

ContentLicense: CC BY-SA 4.0

Title: Sort json array by value using PHP

Body:
I am trying to sort the array using usort().But my function does not seem to work. I want to sort it by partners_order of each object i.e, $myJson[0] and then $myJson1 separately

The Json array is decoded using $myJson = json_decode($jsonData);

PHP function to sort is written below.

usort($myJson, function($a, $b) {
return $a->partners->partners_order < $b->partners->partners_order ? -1 : 1;
});

Due to restrictions in this site, I cant post the array here. Hence I am forced to use 3rd party site fiddle https://jsfiddle.net/z8s18c21/

any help please ?

Body:
I think it might work if you loop over your objects with foreach.

$myJson = '[
{
    "title":"1st Inning",
    "inning_order":0,
    "partners":[
        {"partners_order":3,"partner_1":{"id":1927312,"runs":31},"partner_2":{"id":1462508,"runs":32}},
        {"partners_order":1,"partner_1":{"id":1927311,"runs":11},"partner_2":{"id":1462508,"runs":12}},
        {"partners_order":2,"partner_1":{"id":1927311,"runs":21},"partner_2":{"id":1462507,"runs":22}}
    ]
},
{
    "title":"2nd Inning",
    "inning_order":1,
    "partners":[
        {"partners_order":2,"partner_1":{"id":927312,"runs":21},"partner_2":{"id":462508,"runs":22}},
        {"partners_order":1,"partner_1":{"id":927311,"runs":11},"partner_2":{"id":462508,"runs":21}},
        {"partners_order":3,"partner_1":{"id":927311,"runs":31},"partner_2":{"id":462507,"runs":32}}
    ]

}
]';

$read_json = json_decode($myJson);

foreach ($read_json as $myJson1) {
  usort($myJson1->partners,function($a, $b) {
    return $a->partners_order <=> $b->partners_order;
  });
}

echo '<pre>';
print_r($read_json);
echo '</pre>';

Code has now been tested, because you provided the data objects.


问:
SQL Cannot resolve the collation conflict between "Arabic_100_CI_AI" and "SQL_Latin1_General_CP1_CI_AS" in the equal to operation
When i clicked right on my DB , this error appears
"SQL Cannot resolve the collation conflict between "Arabic_100_CI_AI" and "SQL_Latin1_General_CP1_CI_AS" in the equal to operation. Could not use view or function 'dbo.sysdac_instances' because of binding error"

I don't know to change the collation

UPDATE
I tried this code to change default collation of DB But it gives an error

Update2

Please help me to solve this issue.

Thanks in advance.

答:
Try below syntax :</p>

```<code>  SELECT * FROM Table1 PT
  JOIN Table2 TA ON PT.Value COLLATE DATABASE_DEFAULT = TA.Value COLLATE DATABASE_DEFAULT
</code>```

Body:
Try below syntax :

  SELECT * FROM Table1 PT
  JOIN Table2 TA ON PT.Value COLLATE DATABASE_DEFAULT = TA.Value COLLATE DATABASE_DEFAULT


问:
Display under sub-comment according to parent sub-comment
I have a problem to display sub-comments based on a parent sub-comment. I do not know if it's a twig or query problem or other.

I have a reply table that contains sub-comments that are linked to the comments in my comments table with the field (com_id).

Only the com_id field of my reply table also refers to the reply_id field of the same table if the reply_level is equal to 1 (see image, red line diagonal).

How do I make a query to select the reply_level (1), reply_id(6) based on the reply_id parent (reply_id (4)?

My twig code:

Comments

    {% for comment in comments %}

 {{ comment.author }} {{ comment.content }}

        <button type="button" class="btn-primary btn-xs buttonAnswer btnLevel0" value="{{ comment.id }}"  > answer </button>

        {% if replys is defined %}
            {% for reply in replys %}
                {% if reply.getComParent() == comment.id and reply.level == 0%}

 {{ reply.author }} {{ reply.content }}

                    <button type="button" class="btn-primary btn-xs buttonAnswer btnLevel1" value="{{ reply.id }}" data-level="{{ reply.level1 }}" > answer </button>
                {% endif %}

                    {% if reply.getComParent() ==  reply.id  and reply.level ==1 %}

 {{ reply.author }} {{ reply.content }}

                        <button type="button" class="btn-primary btn-xs buttonAnswer btnLevel2" value="{{ reply.id }}" data-level="{{ reply.level2 }}" > answer </button>
                    {% endif %}

            {% endfor %}
        {% endif %}

    {% else %}
       no comment(s).
    {% endfor %}```

result :

The child sub How does not appear. It appears that if I add a fourth main comment. It works from sub comment to comment but I can not call a sub-comment based on the parent sub-comment.

Thank you

答:
Recursivity is the magic word to do an arbitrary number of loops according to the deepness of something.

In your case, you can try something like this:

```<code><h3 class="titleComments">Comments</h3>

{# imports macros contained in this file inside "me" variable #}
{% import _self as me %}

{# makes the variable exists and loopable whatever the case #}
{% set replies = replies|default([]) %}

{% for comment in comments %}
    <p><strong>{{ comment.author }}</strong> {{ comment.content }}</p>
    <button type="button" class="btn-primary btn-xs buttonAnswer btnLevel0" value="{{ comment.id }}"> answer</button>

    {# fixes the non-unique id issue in your current code #}
    <div id="reply-{{ comment.id }}">
         {% if replies|length %}
             {% for reply in replies %}
                 {% if reply.getComParent() == comment.id and reply.level == 0 %}
                     <p> <strong>{{ reply.author }}</strong> {{ reply.content }}</p>
                     <button type="button" class="btn-primary btn-xs buttonAnswer btnLevel{{ level }}" value="{{ reply.id }}" data-level="{{ reply.level1 }}" > answer </button>

                     {# here begins the magic #}
                     {{ me.displayReplies(replies, reply, 1) }}

                 {% endif %}
             {% endfor %}
        {% else %}
            no comment(s).
        {% endif %}
     </div>
{% endfor %}

{# macros are similar to functions in php and can call themselves recursivly #}
{% macro displayReplies(replyParent, replies, level) %}

    {# reimports macros to make this macro able to call himself #}
    {% import _self as me %}

    {% for replyChild in replies %}

    <div id="underReply{{ replyParent.id }}">
        {% if replyChild.getComParent() == replyParent.id and replyChild.level == level %}
            <p> <strong>{{ replyChild.author }}</strong> {{ replyChild.content }}</p>
            <button type="button" class="btn-primary btn-xs buttonAnswer btnLevel2" value="{{ replyChild.id }}" data-level="{{ replyChild.level2 }}" > answer </button>

            {# and we get deeper if needed #}
            {{ me.displayReplies(replyChild, replies, level + 1) }}

        {% endif %}
    </div>
    {% endfor %}

{% endmacro %}
</code>```

By the way, a simpler approach should be to use the same table for comments and replies:

Considering the following context:

```<code>comments:
    -
        id: 1
        parent_id: null
        content: comment 1
    -
        id: 2
        parent_id: null
        content: comment 2
    -
        id: 3
        parent_id: null
        content: comment 3
    -
        id: 4
        parent_id: 1
        content: reply comment 1
    -
        id: 5
        parent_id: 2
        content: reply comment 2
    -
        id: 6
        parent_id: 3
        content: reply comment 3
    -
        id: 7
        parent_id: 3
        content: reply comment 3
    -
        id: 8
        parent_id: 4
        content: reply of reply comment 3
    -
        id: 9
        parent_id: 8
        content: reply of reply of reply comment 3
</code>```

And the following twig code:

```<code>{% import _self as me %}

{% macro displayComment(comments, parentComment, deepness = 0) %}

  {% if parentComment.parent_id is null %}
  Comment #{{ parentComment.id }} (deepness = {{ deepness }}): {{ parentComment.content }}
  {% else %}
    {% for i in 0..deepness %}  {% endfor %}Reply #{{ parentComment.id }} of #{{ parentComment.parent_id }} (deepness = {{ deepness }}): {{ parentComment.content }}
  {% endif %}

  {% import _self as me %}
  {% for childComment in comments if childComment.parent_id == parentComment.id %}
  {{ me.displayComment(comments, childComment, deepness + 1) }}
  {% endfor %}

{% endmacro %}

{% for comment in comments if comment.parent_id is null %}
{{ me.displayComment(comments, comment) }}
{% endfor %}
</code>```

You will end up with:

```<code>Comment #1 (deepness = 0): comment 1

    Reply #4 of #1 (deepness = 1): reply comment 1

        Reply #8 of #4 (deepness = 2): reply of reply comment 3

            Reply #9 of #8 (deepness = 3): reply of reply of reply comment 3

Comment #2 (deepness = 0): comment 2

    Reply #5 of #2 (deepness = 1): reply comment 2

Comment #3 (deepness = 0): comment 3

    Reply #6 of #3 (deepness = 1): reply comment 3

    Reply #7 of #3 (deepness = 1): reply comment 3
</code>```

See fiddle

Body:
I have a problem to display sub-comments based on a parent sub-comment. I do not know if it's a twig or query problem or other.

I have a reply table that contains sub-comments that are linked to the comments in my comments table with the field (com_id).

Only the com_id field of my reply table also refers to the reply_id field of the same table if the reply_level is equal to 1 (see image, red line diagonal).

How do I make a query to select the reply_level (1), reply_id(6) based on the reply_id parent (reply_id (4)?

My twig code:

Comments

    {% for comment in comments %}

 {{ comment.author }} {{ comment.content }}

        <button type="button" class="btn-primary btn-xs buttonAnswer btnLevel0" value="{{ comment.id }}"  > answer </button>

        {% if replys is defined %}
            {% for reply in replys %}
                {% if reply.getComParent() == comment.id and reply.level == 0%}

 {{ reply.author }} {{ reply.content }}

                    <button type="button" class="btn-primary btn-xs buttonAnswer btnLevel1" value="{{ reply.id }}" data-level="{{ reply.level1 }}" > answer </button>
                {% endif %}

                    {% if reply.getComParent() ==  reply.id  and reply.level ==1 %}

 {{ reply.author }} {{ reply.content }}

                        <button type="button" class="btn-primary btn-xs buttonAnswer btnLevel2" value="{{ reply.id }}" data-level="{{ reply.level2 }}" > answer </button>
                    {% endif %}

            {% endfor %}
        {% endif %}

    {% else %}
       no comment(s).
    {% endfor %}

result :

The child sub How does not appear. It appears that if I add a fourth main comment. It works from sub comment to comment but I can not call a sub-comment based on the parent sub-comment.

Thank you

Body:
Recursivity is the magic word to do an arbitrary number of loops according to the deepness of something.

In your case, you can try something like this:

<h3 class="titleComments">Comments</h3>

{# imports macros contained in this file inside "me" variable #}
{% import _self as me %}

{# makes the variable exists and loopable whatever the case #}
{% set replies = replies|default([]) %}

{% for comment in comments %}
    <p><strong>{{ comment.author }}</strong> {{ comment.content }}</p>
    <button type="button" class="btn-primary btn-xs buttonAnswer btnLevel0" value="{{ comment.id }}"> answer</button>

    {# fixes the non-unique id issue in your current code #}
    <div id="reply-{{ comment.id }}">
         {% if replies|length %}
             {% for reply in replies %}
                 {% if reply.getComParent() == comment.id and reply.level == 0 %}
                     <p> <strong>{{ reply.author }}</strong> {{ reply.content }}</p>
                     <button type="button" class="btn-primary btn-xs buttonAnswer btnLevel{{ level }}" value="{{ reply.id }}" data-level="{{ reply.level1 }}" > answer </button>

                     {# here begins the magic #}
                     {{ me.displayReplies(replies, reply, 1) }}

                 {% endif %}
             {% endfor %}
        {% else %}
            no comment(s).
        {% endif %}
     </div>
{% endfor %}

{# macros are similar to functions in php and can call themselves recursivly #}
{% macro displayReplies(replyParent, replies, level) %}

    {# reimports macros to make this macro able to call himself #}
    {% import _self as me %}

    {% for replyChild in replies %}

    <div id="underReply{{ replyParent.id }}">
        {% if replyChild.getComParent() == replyParent.id and replyChild.level == level %}
            <p> <strong>{{ replyChild.author }}</strong> {{ replyChild.content }}</p>
            <button type="button" class="btn-primary btn-xs buttonAnswer btnLevel2" value="{{ replyChild.id }}" data-level="{{ replyChild.level2 }}" > answer </button>

            {# and we get deeper if needed #}
            {{ me.displayReplies(replyChild, replies, level + 1) }}

        {% endif %}
    </div>
    {% endfor %}

{% endmacro %}

By the way, a simpler approach should be to use the same table for comments and replies:

Considering the following context:

comments:
    -
        id: 1
        parent_id: null
        content: comment 1
    -
        id: 2
        parent_id: null
        content: comment 2
    -
        id: 3
        parent_id: null
        content: comment 3
    -
        id: 4
        parent_id: 1
        content: reply comment 1
    -
        id: 5
        parent_id: 2
        content: reply comment 2
    -
        id: 6
        parent_id: 3
        content: reply comment 3
    -
        id: 7
        parent_id: 3
        content: reply comment 3
    -
        id: 8
        parent_id: 4
        content: reply of reply comment 3
    -
        id: 9
        parent_id: 8
        content: reply of reply of reply comment 3

And the following twig code:

{% import _self as me %}

{% macro displayComment(comments, parentComment, deepness = 0) %}

  {% if parentComment.parent_id is null %}
  Comment #{{ parentComment.id }} (deepness = {{ deepness }}): {{ parentComment.content }}
  {% else %}
    {% for i in 0..deepness %}  {% endfor %}Reply #{{ parentComment.id }} of #{{ parentComment.parent_id }} (deepness = {{ deepness }}): {{ parentComment.content }}
  {% endif %}

  {% import _self as me %}
  {% for childComment in comments if childComment.parent_id == parentComment.id %}
  {{ me.displayComment(comments, childComment, deepness + 1) }}
  {% endfor %}

{% endmacro %}

{% for comment in comments if comment.parent_id is null %}
{{ me.displayComment(comments, comment) }}
{% endfor %}

You will end up with:

Comment #1 (deepness = 0): comment 1

    Reply #4 of #1 (deepness = 1): reply comment 1

        Reply #8 of #4 (deepness = 2): reply of reply comment 3

            Reply #9 of #8 (deepness = 3): reply of reply of reply comment 3

Comment #2 (deepness = 0): comment 2

    Reply #5 of #2 (deepness = 1): reply comment 2

Comment #3 (deepness = 0): comment 3

    Reply #6 of #3 (deepness = 1): reply comment 3

    Reply #7 of #3 (deepness = 1): reply comment 3

See fiddle


问:
Best practice for securing sensitive data in plain text file?
Currently I am working on a C linux daemon that takes user input for an SQL connection string, then stores the information into a local conf file (client side). The purpose of the daemon is to submit data to an SQL database at a set interval in that every time the daemon is loaded it will look to the local conf for the SQL connection string. Also by using the command line argument -c, the user can reconfigure the SQL connection string in the event that the information changes. Would anyone be willing to share a way of securing this conf file so that it is not plain text. Keep in mind that I still need to be able to access and read in from the conf file as there is other conf settings present. Thanks in advance guys.

Edit: I do eventually plan to use SSL to submit the data between the client side and the SQL server.

答:
The (only?) way to secure the file is to change its permissions to make it readable only to the user that runs the daemon.

Eg. if you are running the daemon as user 'foo' and group 'foo', you should:

```<code>chown foo.foo my-conf-file
chmod 600 my-conf-file
</code>```

(Or even chmod it to 400 to prevent accidental modification, but I guess in this case you'll lose the -c option functionality).

NOTE: Also remember that it is quite dangerous to pass connection strings on the command line since they will be visible from the process listing!

You could also use some GPG stuff to encrypt the file, but I don't see the point there since then you have to protect the key you use to decript the file, and you get the exact same problem as before.

ContentLicense: CC BY-SA 2.5

Body:
The (only?) way to secure the file is to change its permissions to make it readable only to the user that runs the daemon.

Eg. if you are running the daemon as user 'foo' and group 'foo', you should:

chown foo.foo my-conf-file
chmod 600 my-conf-file

(Or even chmod it to 400 to prevent accidental modification, but I guess in this case you'll lose the -c option functionality).

NOTE: Also remember that it is quite dangerous to pass connection strings on the command line since they will be visible from the process listing!

You could also use some GPG stuff to encrypt the file, but I don't see the point there since then you have to protect the key you use to decript the file, and you get the exact same problem as before.


问:
Vue list items not re-rendered on state change
I have some array of object, when user click button I fetch new array and display display some results.

It works fine until I fetch second array. When I fetch first array with one element and then fetch array with two elements it change (add or remove) only second element.

How I change array value:

```<code>fetchAsync(result){
  this.issue = result.body;
}
</code>```

How issues looks like?

```<code>const issues = [
  {
    "id":100,
    "key":"DEMO-123",
    "summary":"Demo issue description",
    "devices":[
      {
        "id":100,
        "name":"iPhone6S",
        "browsers":[
          {
            "id":100,
            "name":"Safari",
            "displayVariants":[
              {
                "id":100,
                "issueKey":"DEMO-123",
                "state":1,
                "browserName":"safari",
                "user":"user-1",
                "landScope":false
              }
            ]
          }
        ]
      }
    ]
  }
]
</code>```

and the value which was changed is issues[].devices[].browsers[].displayVariants[].state

How to force Vue to rerender this component when nested change appear?

[ EDIT ]

I render issues like this:

```<code>  <tr v-for="issue in issues">
    <td>
      <div>{{ issue.key }}</div>
      <div class="issue-description">[ {{ issue.summary }} ]</div>
    </td>
    <template v-for="d in issue.devices">
      <td v-for="browser in d.browsers">
        <!--{{ d }}-->
          <device v-for="variant in browser.displayVariants"
                  :variant="variant"
                  :browserId="browser.id"
                  :issueKey="issue.key"
                  :issueId="issue.id"
                  :deviceId="d.id"></device>
      </td>
    </template>
  </tr>
</code>```

and device template

```<code><template>
  <svg viewBox="0 0 30 30" class="mobileSVG" @click="changeState" :class="[state, {landscape: variant.landScope}]">
    <use xlink:href="#mobile"/>
  </svg>
</template>
</code>```

答:
I think adding keys to your list will solve the problem:

https://v2.vuejs.org/v2/guide/list.html#key

Vue tries to make minimum changes to the DOM, and think that the first item has not changed, so it is not re-rendered. In your case you already have the id, using that as key should solve the issue.

Body:
I have some array of object, when user click button I fetch new array and display display some results.

It works fine until I fetch second array. When I fetch first array with one element and then fetch array with two elements it change (add or remove) only second element.

How I change array value:

fetchAsync(result){
  this.issue = result.body;
}

How issues looks like?

const issues = [
  {
    "id":100,
    "key":"DEMO-123",
    "summary":"Demo issue description",
    "devices":[
      {
        "id":100,
        "name":"iPhone6S",
        "browsers":[
          {
            "id":100,
            "name":"Safari",
            "displayVariants":[
              {
                "id":100,
                "issueKey":"DEMO-123",
                "state":1,
                "browserName":"safari",
                "user":"user-1",
                "landScope":false
              }
            ]
          }
        ]
      }
    ]
  }
]

and the value which was changed is issues[].devices[].browsers[].displayVariants[].state

How to force Vue to rerender this component when nested change appear?

[ EDIT ]

I render issues like this:

{{ issue.key }}

[ {{ issue.summary }} ]

    <template v-for="d in issue.devices">

          <device v-for="variant in browser.displayVariants"
                  :variant="variant"
                  :browserId="browser.id"
                  :issueKey="issue.key"
                  :issueId="issue.id"
                  :deviceId="d.id"></device>

    </template>

and device template

<template>
  <svg viewBox="0 0 30 30" class="mobileSVG" @click="changeState" :class="[state, {landscape: variant.landScope}]">
    <use xlink:href="#mobile"/>
  </svg>
</template>


问:
unable to create express-generator project using webstorm
I am new to nodejs. while creating nodejs express-generator form webstorm getting following error:</p>

```<code>Error creating Node.js Express App. Cannot find /tmp/intellij-express-generator253/node_modules/express-generator/bin/express
</code>```

答:
To Add a bit more to @Weiyi Ma's answer

Cause

The issue is caused by recent changes in express-generator structure: express.js has been renamed to express-cli.js

To Fix

1.npm install -g express-generator

express project_name

cd project_name, npm install

in webstorm, File | open, choose project_name folder

Body:
I am new to nodejs. while creating nodejs express-generator form webstorm getting following error:

Error creating Node.js Express App. Cannot find /tmp/intellij-express-generator253/node_modules/express-generator/bin/express


问:
In c++, how to send data fetched by dll to exe
I'm a beginner in C++, fed up with errors faced during Data transmission from dll to exe.

Problem :
I have an exe in which i had bundled a dll... Now the exe wanna initiate the dll to fetch some datas from Active Directory.. This is performed by using Function pointer call from exe to dll.. Now, dll fetches data from AD and whenever it attains a Limit (100 data ), it should go to exe to print this data(Only in exe i needed to perform this printing of datas)... and again it should return to dll and continue to fetch datas,,

How to transfer data from dll to exe...??????????

FYI : I had tried using Structure and a class which is common for both exe and dll...
but the memory clean up process crashes my program,, As the heap for dll and exe are different.. the data which i give inside dll are tried to cleanup in exe... (This is a different topic and this needs more explanation... and inorder not to waste ur valuable time kindly help me with the easiest way to transfer data from dll to exe)

I couldnt post my program because of restrictions in my organisation.. Kindly give me a better solution to this...

答:
You can allocate a memory block in exe, pass the address to dll, dll can fill data into the memory, then you can release the buffer in exe.

In your dll, you can export an interface like:

```<code>void fill_buffer( char * p_buff, int buff_size );
</code>```

In your exe, you can allocate a buffer and pass it to the dll, then cleanup it:

```<code>char * the_buff = new char[1024];

while (...) {
    fill_buffer( the_buff, 1024 );

    //do something to the_buff
    print(the_buff)
}

delete []the_buff;
</code>```

When you pass structure or class between dll and exe, be careful that the byte alignment should be consistent in them.

And for your question, maybe you can paste some fake code, then your problem will be clearer.

Body:
You can allocate a memory block in exe, pass the address to dll, dll can fill data into the memory, then you can release the buffer in exe.

In your dll, you can export an interface like:

void fill_buffer( char * p_buff, int buff_size );

In your exe, you can allocate a buffer and pass it to the dll, then cleanup it:

char * the_buff = new char[1024];

while (...) {
    fill_buffer( the_buff, 1024 );

    //do something to the_buff
    print(the_buff)
}

delete []the_buff;

When you pass structure or class between dll and exe, be careful that the byte alignment should be consistent in them.

And for your question, maybe you can paste some fake code, then your problem will be clearer.


问:
Is there an easy way to create a command alias in mysql?
This question is similar to what I'm asking:
Is there a way to create an SQL "alias"?

But not quite the same - I'm learning mysql and am going to be running the select command a lot as I screw with different commands.  Is there a way I can alias something like:

select * from testdb

to

ls

Or something equally similar?  Ideally, I'd be able to alias "select * from" to something like "show" and then just type "show testdb".

答:
using alias with function can help you pass parameter to a alias like
example query = select * from testdb where param = 'test param'
 created alias = sftb test param
 to create such alias you can write something like this in your bashrc file.
 alias sftb='function sftb(){ mysql -e "select * from testdb where param = '$1'"; };sftb'


问:
Textarea adjust size based on content (with form-control class) using Jquery
Hiii Everyone,

I want to resize my textarea based on content.For that I tried code like

```<code><div class="form-group">
    <label class="control-label col-sm-2" for="pwd">Sample Answer</label>
    <div class="col-sm-10">
     <textarea class="form-control" name="answer_sample" id="answer_sample" rows="5" onkeyup="textAreaAdjust(this)"></textarea>
      <br/>
    </div>
  </div>
</code>```

And using jquery

```<code> function textAreaAdjust(o) {
  o.style.height = "1px";
  o.style.height = (25+o.scrollHeight)+"px";
}
</code>```

And what is the issue I am facing is even for backspace,delete for any press textarea is expanding like verylong.It keeps working like textarea will increase for any key press.If I tried textarea without 'class="form-control"' its working fine.But the responsiveness is not well.Please anyone help me to get out of this issue.Thanks in advance.

答:
You can detect the key, if it is backspace don't do anything so you can try this

```<code>$('#answer_sample').bind('keypress', function(e) {
   var code = e.keyCode || e.which;
   if(code != 8) { //Backspace keycode
     $(this).css('height', '1px');
     $(this).css('height', 25+o.scrollHeight)+'px');
   }

});
</code>```

and remove the function from HTML also

```<code><div class="form-group">
    <label class="control-label col-sm-2" for="pwd">Sample Answer</label>
    <div class="col-sm-10">
     <textarea class="form-control" name="answer_sample" id="answer_sample" rows="5" ></textarea>
      <br/>
    </div>
</div>
</code>```

Body:
Hiii Everyone,

I want to resize my textarea based on content.For that I tried code like

    Sample Answer

     <textarea class="form-control" name="answer_sample" id="answer_sample" rows="5" onkeyup="textAreaAdjust(this)"></textarea>

And using jquery

 function textAreaAdjust(o) {
  o.style.height = "1px";
  o.style.height = (25+o.scrollHeight)+"px";
}

And what is the issue I am facing is even for backspace,delete for any press textarea is expanding like verylong.It keeps working like textarea will increase for any key press.If I tried textarea without 'class="form-control"' its working fine.But the responsiveness is not well.Please anyone help me to get out of this issue.Thanks in advance.

Body:
You can detect the key, if it is backspace don't do anything so you can try this

$('#answer_sample').bind('keypress', function(e) {
   var code = e.keyCode || e.which;
   if(code != 8) { //Backspace keycode
     $(this).css('height', '1px');
     $(this).css('height', 25+o.scrollHeight)+'px');
   }

});

and remove the function from HTML also

<div class="form-group">
    <label class="control-label col-sm-2" for="pwd">Sample Answer</label>
    <div class="col-sm-10">
     <textarea class="form-control" name="answer_sample" id="answer_sample" rows="5" ></textarea>
      <br/>
    </div>
</div>


问:
Jackson databind working in IDE environment but not in jar
I am trying to use jackson databind using Maven. It works fine in my IDE environment (I'm using IntelliJ IDEA), but when I try to make a jar with it, it produces an error on startup and instantly crashes. Specifically, the error is this :

```<code>java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/JsonFactory
</code>```

This is specific to the JAR, and I don't know why it does that at all.
What did I do wrong ?

Here is the pom file :

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>me.zam</groupId>
    <artifactId>jackson</artifactId>
    <version>1.0-SNAPSHOT</version>

    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.2.3</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-yaml</artifactId>
            <version>2.3.0</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <!-- Make this jar executable -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifest>
                            <!-- Jar file entry point -->
                            <mainClass>me.Main</mainClass>
                            <addClasspath>true</addClasspath>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

And here is the Main object

```<code>package me;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;

/**
 * Created by Martin on 31/03/2017.
 */
public class Main
{
    public static void main(String[] args)
    {
        ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
        try {
            User user = mapper.readValue(new File("user.yaml"), User.class);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
</code>```

答: Can you please check whether the generated jar contains the specified dependencies such as jackson-databind and jackson-dataformat-yaml? I'm not sure the jar plugin exports the maven dependencies. I normally use maven assembly plugin or shade plugin to generate jar with dependencies.

Body:
I am trying to use jackson databind using Maven. It works fine in my IDE environment (I'm using IntelliJ IDEA), but when I try to make a jar with it, it produces an error on startup and instantly crashes. Specifically, the error is this :

java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/JsonFactory

This is specific to the JAR, and I don't know why it does that at all.
What did I do wrong ?

Here is the pom file :

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>me.zam</groupId>
    <artifactId>jackson</artifactId>
    <version>1.0-SNAPSHOT</version>

    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.2.3</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-yaml</artifactId>
            <version>2.3.0</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifest>

                            <mainClass>me.Main</mainClass>
                            <addClasspath>true</addClasspath>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

And here is the Main object

package me;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;

/**
 * Created by Martin on 31/03/2017.
 */
public class Main
{
    public static void main(String[] args)
    {
        ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
        try {
            User user = mapper.readValue(new File("user.yaml"), User.class);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}


问:
bootstrap button group text shrinking on page resize
I have a group of buttons in a justified button group.

When I resize the page I get something like this:

What can I do to not let the button text shrink? Maybe stop the page from resizing at a certain limit, or let the buttons become vertical. (Same behavior of default bootstrap behavior)

```<code><div class="btn-group btn-group-justified" role="group">
  <div class="btn-group" role="group">
    <button type="button" class="btn btn-default">
      Group A
    </button>
  </div>
  <div class="btn-group" role="group">
    <button type="button" class="btn btn-default">
      Group B
    </button>
  </div>
  ....
</code>```

A running example on plnkr

答:
Set your font size inside <button> using vw(viewport width) size unit.
Just include this custom css in your style.css file :

```<code>.btn-group > button {
    font-size: 1.5vw;
}
</code>```

For your information 1vw = 1% of viewport width. Learn more about it here

Hope this answer your question.

/* Styles go here */

.btn-group > button {
    font-size: 1.5vw;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
  <link data-require="bootstrap@3.3.7" data-semver="3.3.7" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
  <div class="container" style="margin-top:20px">
    <div class="btn-group btn-group-justified" role="group">
      <div class="btn-group" role="group">
        <button type="button" class="btn btn-default">
          Group A
        </button>
      </div>
      <div class="btn-group" role="group">
        <button type="button" class="btn btn-default">
          Group B
        </button>
      </div>
      <div class="btn-group" role="group">
        <button type="button" class="btn btn-default">
          Group C
        </button>
      </div>
      <div class="btn-group" role="group">
        <button type="button" class="btn btn-default">
          Group D
        </button>
      </div>
      <div class="btn-group" role="group">
        <button type="button" class="btn btn-default">
          Group E
        </button>
      </div>
      <div class="btn-group" role="group">
        <button type="button" class="btn btn-default">
          Group F
        </button>
      </div>
    </div>
  </div>
</body>
</html></code>```

Body:
I have a group of buttons in a justified button group.

When I resize the page I get something like this:

What can I do to not let the button text shrink? Maybe stop the page from resizing at a certain limit, or let the buttons become vertical. (Same behavior of default bootstrap behavior)

    <button type="button" class="btn btn-default">
      Group A
    </button>

    <button type="button" class="btn btn-default">
      Group B
    </button>

  ....

A running example on plnkr

Body:
Set your font size inside <button> using vw(viewport width) size unit.
Just include this custom css in your style.css file :

.btn-group > button {
    font-size: 1.5vw;
}

For your information 1vw = 1% of viewport width. Learn more about it here

Hope this answer your question.

/* Styles go here */

.btn-group > button {
    font-size: 1.5vw;
}

<!DOCTYPE html>
<html>
<head>
  <link data-require="bootstrap@3.3.7" data-semver="3.3.7" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
  <div class="container" style="margin-top:20px">
    <div class="btn-group btn-group-justified" role="group">
      <div class="btn-group" role="group">
        <button type="button" class="btn btn-default">
          Group A
        </button>
      </div>
      <div class="btn-group" role="group">
        <button type="button" class="btn btn-default">
          Group B
        </button>
      </div>
      <div class="btn-group" role="group">
        <button type="button" class="btn btn-default">
          Group C
        </button>
      </div>
      <div class="btn-group" role="group">
        <button type="button" class="btn btn-default">
          Group D
        </button>
      </div>
      <div class="btn-group" role="group">
        <button type="button" class="btn btn-default">
          Group E
        </button>
      </div>
      <div class="btn-group" role="group">
        <button type="button" class="btn btn-default">
          Group F
        </button>
      </div>
    </div>
  </div>
</body>
</html>


问:
How to access method from view inside a Xamarin Forms custom renderer?
I have the following code:

```<code>public partial class PhrasesFrameRendererClass : Frame
{
    .....
    void getRandomWords() {
       // more code here that involves getting random numbers
       // and updating a grid's bindingcontext
    }
}
</code>```

In my custom renderer I want to be able to call the getRandomWords on swipe left gesture like below:

```<code>public class PhraseFrameCustomRenderer : FrameRenderer
{
   UISwipeGestureRecognizer leftSwipeGestureRecognizer;
   protected override void OnElementChanged(ElementChangedEventArgs<Frame> e)
   {
       base.OnElementChanged(e);
       leftSwipeGestureRecognizer = new UISwipeGestureRecognizer();
       leftSwipeGestureRecognizer.Direction = UISwipeGestureRecognizerDirection.Left;
       leftSwipeGestureRecognizer.NumberOfTouchesRequired = 1;
       leftSwipeGestureRecognizer.AddTarget((obj) =>
       {
          // Call getRandomWords() here
       });
   }
}
</code>```

Is this possible? Any ideas on how this could be done?

答:
You can create a BindableProperty of type Command in your custom frame class, call that Command from your renderer and bind your ViewModel's getRandomWords method as a Command

```<code>//Your custom control in your PCL project
public partial class PhrasesFrameRendererClass : Frame
{
    public static readonly BindableProperty SwipeLeftCommandProperty =
    BindableProperty.Create(nameof(SwipeLeftCommand), typeof(ICommand), typeof(PhrasesFrameRendererClass ), null);

    public ICommand SwipeLeftCommand
    {
        get { return (ICommand)GetValue(CommandProperty); }
        set { SetValue(CommandProperty, value); }
    }
}

//Your custom control renderer
public class PhraseFrameCustomRenderer : FrameRenderer
{
   UISwipeGestureRecognizer leftSwipeGestureRecognizer;
   protected override void OnElementChanged(ElementChangedEventArgs<Frame> e)
   {
       base.OnElementChanged(e);
       leftSwipeGestureRecognizer = new UISwipeGestureRecognizer();
       leftSwipeGestureRecognizer.Direction = UISwipeGestureRecognizerDirection.Left;
       leftSwipeGestureRecognizer.NumberOfTouchesRequired = 1;
       leftSwipeGestureRecognizer.AddTarget((obj) =>
       {
           var myFrame = Element as PhrasesFrameRendererClassl
           if(myFrame != null){
               if(myFrame.SwipeLeftCommand != null && myFrame.SwipeLeftCommand.CanExecute()){
                   myFrame.SwipeLeftCommand.Execute();
               }
           }
       });
   }
}

//Your ViewModel
public class PhrasesViewModel{

    public Command GetRandomWordsCommand {get;set;}

    public PhrasesViewModel(){
        GetRandomWordsCommand = new Command(ExecuteGetRandomWords);
    }

    private void ExecuteGetRandomWords(){

    //Your method goes here

    }

}

//Your XAML
<yourControls:PhrasesFrameRendererClass SwipeLeftCommand="{Binding GetRandomWordsCommand }"/>
</code>```

It may seem more complicated this way, but using commands allows you to separate your application code (Such as getting random phrases) from your rendering code

Body:
I have the following code:

public partial class PhrasesFrameRendererClass : Frame
{
    .....
    void getRandomWords() {
       // more code here that involves getting random numbers
       // and updating a grid's bindingcontext
    }
}

In my custom renderer I want to be able to call the getRandomWords on swipe left gesture like below:

public class PhraseFrameCustomRenderer : FrameRenderer
{
   UISwipeGestureRecognizer leftSwipeGestureRecognizer;
   protected override void OnElementChanged(ElementChangedEventArgs<Frame> e)
   {
       base.OnElementChanged(e);
       leftSwipeGestureRecognizer = new UISwipeGestureRecognizer();
       leftSwipeGestureRecognizer.Direction = UISwipeGestureRecognizerDirection.Left;
       leftSwipeGestureRecognizer.NumberOfTouchesRequired = 1;
       leftSwipeGestureRecognizer.AddTarget((obj) =>
       {
          // Call getRandomWords() here
       });
   }
}

Is this possible? Any ideas on how this could be done?

Body:
You can create a BindableProperty of type Command in your custom frame class, call that Command from your renderer and bind your ViewModel's getRandomWords method as a Command

//Your custom control in your PCL project
public partial class PhrasesFrameRendererClass : Frame
{
    public static readonly BindableProperty SwipeLeftCommandProperty =
    BindableProperty.Create(nameof(SwipeLeftCommand), typeof(ICommand), typeof(PhrasesFrameRendererClass ), null);

    public ICommand SwipeLeftCommand
    {
        get { return (ICommand)GetValue(CommandProperty); }
        set { SetValue(CommandProperty, value); }
    }
}

//Your custom control renderer
public class PhraseFrameCustomRenderer : FrameRenderer
{
   UISwipeGestureRecognizer leftSwipeGestureRecognizer;
   protected override void OnElementChanged(ElementChangedEventArgs<Frame> e)
   {
       base.OnElementChanged(e);
       leftSwipeGestureRecognizer = new UISwipeGestureRecognizer();
       leftSwipeGestureRecognizer.Direction = UISwipeGestureRecognizerDirection.Left;
       leftSwipeGestureRecognizer.NumberOfTouchesRequired = 1;
       leftSwipeGestureRecognizer.AddTarget((obj) =>
       {
           var myFrame = Element as PhrasesFrameRendererClassl
           if(myFrame != null){
               if(myFrame.SwipeLeftCommand != null && myFrame.SwipeLeftCommand.CanExecute()){
                   myFrame.SwipeLeftCommand.Execute();
               }
           }
       });
   }
}

//Your ViewModel
public class PhrasesViewModel{

    public Command GetRandomWordsCommand {get;set;}

    public PhrasesViewModel(){
        GetRandomWordsCommand = new Command(ExecuteGetRandomWords);
    }

    private void ExecuteGetRandomWords(){

    //Your method goes here

    }

}

//Your XAML
<yourControls:PhrasesFrameRendererClass SwipeLeftCommand="{Binding GetRandomWordsCommand }"/>

It may seem more complicated this way, but using commands allows you to separate your application code (Such as getting random phrases) from your rendering code


答:
Your two tables are using different collation. You can tell your query to use a specific collation like this:

```<code>SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE SQL_Latin1_General_CP1_CI_AS
</code>```

Or if you prefer to use the database default collation:

```<code>SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE DATABASE_DEFAULT
</code>```

Updated

I think you need to set the database to single user mode

```<code>use master
ALTER DATABASE yourDB SET SINGLE_USER WITH ROLLBACK IMMEDIATE
ALTER DATABASE yourDB MODIFY NAME = [yourDBNew]
ALTER DATABASE yourDBNew SET MULTI_USER
</code>```

Body:
When i clicked right on my DB , this error appears
"SQL Cannot resolve the collation conflict between "Arabic_100_CI_AI" and "SQL_Latin1_General_CP1_CI_AS" in the equal to operation. Could not use view or function 'dbo.sysdac_instances' because of binding error"

I don't know to change the collation

UPDATE
I tried this code to change default collation of DB But it gives an error

Update2

Please help me to solve this issue.

Thanks in advance.

Body:
Your two tables are using different collation. You can tell your query to use a specific collation like this:

SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE SQL_Latin1_General_CP1_CI_AS

Or if you prefer to use the database default collation:

SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE DATABASE_DEFAULT

Updated

I think you need to set the database to single user mode

use master
ALTER DATABASE yourDB SET SINGLE_USER WITH ROLLBACK IMMEDIATE
ALTER DATABASE yourDB MODIFY NAME = [yourDBNew]
ALTER DATABASE yourDBNew SET MULTI_USER


问:
A java application with J2V8 crashes when an exception happened in a some deferred section (e.g. setTimeout or process.nextTick)
I use amazing J2V8 java library which allows execute any Javascript code in your Java application furthermore it can integrates a nodeJS engine.

But i have encountered with a next issue. This code interrupts a Java application immediately after nodejs invokes a callback function of setTimeout which throw an exception although there is a try..carch block. The exception doesn't even enter into the try..catch block.

```<code>// It is an example, in real case it can be a some erorr in a code.
nodeJS = NodeJS.createNodeJS();
try {
    nodeJS.getRuntime().executeVoidScript("setTimeout(function(){throw 'Error'}, 1000);");
} catch (Exception e) {
    e.printStackTrace();
}
</code>```

The application is interrupted with message:

```<code>undefined:1
setTimeout(function(){throw 'Error'}, 10000);
                  ^
Error
Process finished with exit code 1
</code>```

Another example shows that exceptions are not a cause of interruption of an application  always and it is a 'normal' case.

```<code>nodeJS = NodeJS.createNodeJS();
try {
    nodeJS.getRuntime().executeVoidScript("throw 'Error'");
} catch (Exception e) {
    e.printStackTrace();
}
</code>```

In this case we see the only a error message in console but the application still works.

```<code>Exception in thread "Thread-2" undefined:1: Error
throw 'Error'
^
com.eclipsesource.v8.V8ScriptExecutionException
    at com.eclipsesource.v8.V8._executeScript(Native Method)
    at com.eclipsesource.v8.V8.executeScript(V8.java:940)
    at com.eclipsesource.v8.V8.executeScript(V8.java:595)
    at com.eclipsesource.v8.V8.executeObjectScript(V8.java:625)
    at com.eclipsesource.v8.V8.executeObjectScript(V8.java:608)
    at org.efc.origamiapp.v8.V8Environment.run(V8Environment.java:383)
</code>```

The examples above are in the try..catch blocks, and you can see trace stack below it. So the interruption is fired in Native Method (the secod example), but in the first case the JS exception just kills the Java  application without any explanations in a console or in a trace log.

答:
This is the best and correct solution.

```<code>process.on('unhandledRejection', (err) => {
    console.error('Unhandled promise rejection',err);
});
process.on('uncaughtException', (err) => {
    console.error('Uncaught exception',err);
});
</code>```

For more information see the nodeJS documentation: Event: 'uncaughtException'

Body:
I use amazing J2V8 java library which allows execute any Javascript code in your Java application furthermore it can integrates a nodeJS engine.

But i have encountered with a next issue. This code interrupts a Java application immediately after nodejs invokes a callback function of setTimeout which throw an exception although there is a try..carch block. The exception doesn't even enter into the try..catch block.

// It is an example, in real case it can be a some erorr in a code.
nodeJS = NodeJS.createNodeJS();
try {
    nodeJS.getRuntime().executeVoidScript("setTimeout(function(){throw 'Error'}, 1000);");
} catch (Exception e) {
    e.printStackTrace();
}

The application is interrupted with message:

undefined:1
setTimeout(function(){throw 'Error'}, 10000);
                  ^
Error
Process finished with exit code 1

Another example shows that exceptions are not a cause of interruption of an application  always and it is a 'normal' case.

nodeJS = NodeJS.createNodeJS();
try {
    nodeJS.getRuntime().executeVoidScript("throw 'Error'");
} catch (Exception e) {
    e.printStackTrace();
}

In this case we see the only a error message in console but the application still works.

Exception in thread "Thread-2" undefined:1: Error
throw 'Error'
^
com.eclipsesource.v8.V8ScriptExecutionException
    at com.eclipsesource.v8.V8._executeScript(Native Method)
    at com.eclipsesource.v8.V8.executeScript(V8.java:940)
    at com.eclipsesource.v8.V8.executeScript(V8.java:595)
    at com.eclipsesource.v8.V8.executeObjectScript(V8.java:625)
    at com.eclipsesource.v8.V8.executeObjectScript(V8.java:608)
    at org.efc.origamiapp.v8.V8Environment.run(V8Environment.java:383)

The examples above are in the try..catch blocks, and you can see trace stack below it. So the interruption is fired in Native Method (the secod example), but in the first case the JS exception just kills the Java  application without any explanations in a console or in a trace log.

Body:
This is the best and correct solution.

process.on('unhandledRejection', (err) => {
    console.error('Unhandled promise rejection',err);
});
process.on('uncaughtException', (err) => {
    console.error('Uncaught exception',err);
});

For more information see the nodeJS documentation: Event: 'uncaughtException'


问:
a simple one with java calassCastException
```<code>package Medium;

import java.util.ArrayList;
import java.util.Scanner;

public class Demo5 {
    public static void main(String[] args) {
        System.out.println("input end when you want to stop:");

        ArrayList<Double> arr = new ArrayList<Double>();
        while(true){
            Scanner in = new Scanner(System.in);
            //String d = in.nextLine();
            double d = in.nextDouble();
            arr.add(d);
            if (d==0) {
                break;
            }
        }
        Double[] array =(Double[]) arr.toArray();   //I hava already change the type to double
        int outter,inner,max;
         for(outter=0;outter<array.length-1;outter++){
             max = outter;
             for(inner=outter+1;inner<array.length;inner++){
                 if (array[inner]>array[max]) {
                    inner = max;
                }
             }
             double temp =array[outter];
             array[outter] =array[inner];
            array[inner]=temp;
         }
         System.out.println(array);
    }
}
</code>```

Description:Find K-th largest element in an array.
I want to input a arrayList and change it into array,then use selectSort.However,prints out ClassCastException on"Double[] array =(Double[]) arr.toArray();",what's wrong?thank you for your time.

Exception:

```<code>Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Double;
    at Medium.Demo5.main(Demo5.java:31)
</code>```

答:
The toArray() method without passing any argument gives you back Object[].

Just to fix the issue you have to pass an array as an argument with type and size.

```<code>Double[] array =  list.toArray(new Double[list.size()]);
</code>```

Body:
package Medium;

import java.util.ArrayList;
import java.util.Scanner;

public class Demo5 {
    public static void main(String[] args) {
        System.out.println("input end when you want to stop:");

        ArrayList<Double> arr = new ArrayList<Double>();
        while(true){
            Scanner in = new Scanner(System.in);
            //String d = in.nextLine();
            double d = in.nextDouble();
            arr.add(d);
            if (d==0) {
                break;
            }
        }
        Double[] array =(Double[]) arr.toArray();   //I hava already change the type to double
        int outter,inner,max;
         for(outter=0;outter<array.length-1;outter++){
             max = outter;
             for(inner=outter+1;inner<array.length;inner++){
                 if (array[inner]>array[max]) {
                    inner = max;
                }
             }
             double temp =array[outter];
             array[outter] =array[inner];
            array[inner]=temp;
         }
         System.out.println(array);
    }
}

Description:Find K-th largest element in an array.
I want to input a arrayList and change it into array,then use selectSort.However,prints out ClassCastException on"Double[] array =(Double[]) arr.toArray();",what's wrong?thank you for your time.

Exception:

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Double;
    at Medium.Demo5.main(Demo5.java:31)

Body:
The toArray() method without passing any argument gives you back Object[].

Just to fix the issue you have to pass an array as an argument with type and size.

Double[] array =  list.toArray(new Double[list.size()]);


问:
Stop Wonderlandads,com
I have chrome installed on my windows 7. Whenever i click on any link on any site, the link opens as it should open normally but along with that, a new tab opens and a page open that new tab, which is advertisement page. The url of that page is wonderlandads dot com/afu.php?zoneid=437742 . Even when i click on scroll bar the same page opens in new tab.This is very irritating. I have tried to remove this adware by using Anti Malware Quickheal . I have also scanned my PC with antivirus. I do not have any unwanted software in my PC. I have tried reinstalling chrome and other browsers(IE, firefox) that i have. I am experiencing the same problem in firefox and IE. How can i fix it ?</p>

答:
I had the same problem, but after steps below the problem solved:

try chrome cleanup tool

try malwarebytes

then install an adwclean tool

if the problem isn't solved yet, delete chrome and reinstall it

I hope you get rid of it.

Title: Stop Wonderlandads,com


问:
How do I stitch multiple photos together to create necklace structure with imagemagick?
I want create necklace like structure by stitching images together with image magick, how can I achieve this?

We are using PHP to call imagemagick.

Attaching image here...
These small nuts will be separate images

答: See how you want to synthesize, the basic can use the PHP image processing function to create a canvas, the length of the three pictures of a long, width is the width of the three pictures together</p>


答:
Drop your buttons down on mobile resolution

```<code>@media(max-width: 480px){
  .btn-group {
    display: block !important;
    width: auto !important;
  }
}
</code>```

Title: bootstrap button group text shrinking on page resize

Body:
Drop your buttons down on mobile resolution

@media(max-width: 480px){
  .btn-group {
    display: block !important;
    width: auto !important;
  }
}


问:
limit is not working in subquery
I have saved vehicle types in 'vehicle_types_locales', drivers in 'drivers' and driver's current location in 'drivercurrentlocation' table.

Logic : I am trying to get all vehicle types from main query then trying to select 5 drivers for each category from driver's tables which satisfying conditions as implemented. If records are less than 5 for all categories then it's working fine else it returns all driver's exist in category.(seems limit not working)

My query is :

```<code>SELECT vtl.vehicle_type_id as id ,vtl.name, (
    SELECT GROUP_CONCAT(concat(
        drv.id,'----', drv.firstname, '----', ifnull(drv.lastname,''), '----',
        dll.latitude, '----', dll.longitude) SEPARATOR '--++--')
    FROM drivercurrentlocation as dll LEFT JOIN drivers as drv ON
    (dll.driverid = drv.id) WHERE drv.active_vehicle_id > 0 AND
    current_duty_status='F' and drv.status='A' and drv.onduty='Y' AND
    drv.vehicle_type_id= vtl.vehicle_type_id AND latitude > '".
    $latLongData['minLat']."' AND latitude < '". $latLongData['maxLat'] ."'
    AND longitude > '". $latLongData['minLng'] ."' AND longitude < '".
    $latLongData['maxLng']."' limit 5)
as ddata FROM vehicle_types_locales
WHERE vtl.status  = 'A' AND vtl.language_id = '$languageid'";
</code>```

Please help me to resolve this limit issue.

Thanks in advance

答: I think you need to change from LIMIT 5 to LIMIT 0,5. This is the right way to limit data in MySQL

Title: limit is not working in subquery

Body:
I have saved vehicle types in 'vehicle_types_locales', drivers in 'drivers' and driver's current location in 'drivercurrentlocation' table.

Logic : I am trying to get all vehicle types from main query then trying to select 5 drivers for each category from driver's tables which satisfying conditions as implemented. If records are less than 5 for all categories then it's working fine else it returns all driver's exist in category.(seems limit not working)

My query is :

SELECT vtl.vehicle_type_id as id ,vtl.name, (
    SELECT GROUP_CONCAT(concat(
        drv.id,'----', drv.firstname, '----', ifnull(drv.lastname,''), '----',
        dll.latitude, '----', dll.longitude) SEPARATOR '--++--')
    FROM drivercurrentlocation as dll LEFT JOIN drivers as drv ON
    (dll.driverid = drv.id) WHERE drv.active_vehicle_id > 0 AND
    current_duty_status='F' and drv.status='A' and drv.onduty='Y' AND
    drv.vehicle_type_id= vtl.vehicle_type_id AND latitude > '".
    $latLongData['minLat']."' AND latitude < '". $latLongData['maxLat'] ."'
    AND longitude > '". $latLongData['minLng'] ."' AND longitude < '".
    $latLongData['maxLng']."' limit 5)
as ddata FROM vehicle_types_locales
WHERE vtl.status  = 'A' AND vtl.language_id = '$languageid'";

Please help me to resolve this limit issue.

Thanks in advance


问:
How to count multiple phone number and sms number from editText field in android?
I am facing two problems.
  1. Counting multiple phone number from editText field.
  2. Counting SMS number after crossing specific number of characters.

```<code><android.support.design.widget.TextInputLayout
                android:id="@+id/phoneContainer"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:counterEnabled="true"
                app:counterMaxLength="50">

                <com.andreabaccega.widget.FormEditText
                    android:id="@+id/idContacts"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:hint="Recipients"
                    android:ems="10"
                    android:inputType="phone"
                    android:padding="15dp" />
</android.support.design.widget.TextInputLayout>
</code>```

Here,I can count character of phone number.I need to count the whole phone number.Example: If user types 012346771233,02546547589 in phone edit field,it will count as 2. But in my case ,it is counting single character.I searched lot ,but could not find any solutions.

Secondly,I have a editText field where user can input messages.When user crosses specific numbers(as 160 character) of character,it will do 2 actions.It will increase the sms number and also set character numbers(as 146 character) for next sms.

```<code><android.support.design.widget.TextInputLayout
                    android:id="@+id/textContainer"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    app:counterEnabled="true"
                    app:counterMaxLength="160">

                    <com.andreabaccega.widget.FormEditText
                        android:id="@+id/idMsg"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"

                        android:ems="10"
                        android:hint="@string/message"
                        android:inputType="text|textMultiLine|textAutoCorrect"
                        android:padding="10dp"
                        whatever:emptyErrorString="Message can not be empty."
                        whatever:testType="alpha" />
</android.support.design.widget.TextInputLayout>
</code>```

In my case,I can count characters but how can I count sms numbers and set counterMaxLength for next sms?

答:
for your first question you can do your calculation inside EditText onchange listener

```<code>yourEditText.addTextChangedListener(new TextWatcher() {

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

        if (s.length() >= 0) {

            String []phnArray = s.toString().split(",");
            int phCount  = phnArray.length;
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }
});
</code>```

For your second question it is kind of unclear to me what you actually want.

if you want to check if length crosses 160 then you can check

```<code>if(s.length > 160){
    //do your require changes here
}
</code>```

Body:
I am facing two problems.
  1. Counting multiple phone number from editText field.
  2. Counting SMS number after crossing specific number of characters.

<android.support.design.widget.TextInputLayout
                android:id="@+id/phoneContainer"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:counterEnabled="true"
                app:counterMaxLength="50">

                <com.andreabaccega.widget.FormEditText
                    android:id="@+id/idContacts"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:hint="Recipients"
                    android:ems="10"
                    android:inputType="phone"
                    android:padding="15dp" />
</android.support.design.widget.TextInputLayout>

Here,I can count character of phone number.I need to count the whole phone number.Example: If user types 012346771233,02546547589 in phone edit field,it will count as 2. But in my case ,it is counting single character.I searched lot ,but could not find any solutions.

Secondly,I have a editText field where user can input messages.When user crosses specific numbers(as 160 character) of character,it will do 2 actions.It will increase the sms number and also set character numbers(as 146 character) for next sms.

<android.support.design.widget.TextInputLayout
                    android:id="@+id/textContainer"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    app:counterEnabled="true"
                    app:counterMaxLength="160">

                    <com.andreabaccega.widget.FormEditText
                        android:id="@+id/idMsg"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"

                        android:ems="10"
                        android:hint="@string/message"
                        android:inputType="text|textMultiLine|textAutoCorrect"
                        android:padding="10dp"
                        whatever:emptyErrorString="Message can not be empty."
                        whatever:testType="alpha" />
</android.support.design.widget.TextInputLayout>

In my case,I can count characters but how can I count sms numbers and set counterMaxLength for next sms?

Body:
for your first question you can do your calculation inside EditText onchange listener

yourEditText.addTextChangedListener(new TextWatcher() {

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

        if (s.length() >= 0) {

            String []phnArray = s.toString().split(",");
            int phCount  = phnArray.length;
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }
});

For your second question it is kind of unclear to me what you actually want.

if you want to check if length crosses 160 then you can check

if(s.length > 160){
    //do your require changes here
}


问:
JSON array not working for $http service
I am new to angular and trying to develop an application having nested
   ng-repeat and after submitting the form it should hit the rest api.
    I have been using $http to make rest api calls. The code gets submitted
    with normal data but does not get submitted with nested ng-repeat when i
    click the save button. Below I have provided the code with details.
    The whole data should be shown in the console. I might have made some
    mistake somewhere.Thanks in advance.

JS

```<code> $scope.saveVenFormData = function(vendet){
     console.log($scope.vendet);
     $scope.venFullAddress.push({
        'vendorName': $scope.name,
        'panNum': $scope.panNum,
        'personName': $scope.venBusDetails.personName,
        'mobileNum': $scope.venBusDetails.mobileNum,
        'workNum': $scope.workNum,
        'emailid': $scope.emailid,
        'addressLine1': $scope.addressLine1,
        'addressLine2': $scope.addressLine2,
        'city': $scope.city,
        'state': $scope.state
        });
     var dataObj = $scope.venFullAddress;
    // console.log($scope.dataObj);

     $http.get('/showVendors').success(function(data){
        console.log(angular.toJson(data));
    });
    var res = $http.post('http://localhost:8080/dman/mm', dataObj);
    res.success(function(data, status, headers, config) {
        $scope.message = data;
    });
    res.error(function(data, status, headers, config) {
        alert( "failure message: " + JSON.stringify({data: data}));
    });
 };
</code>```

JSON structure:

```<code>{
 "vendor": {
    "vendorName": "",
    "panNum": "",
    "venBusDetails": [{
            "personName": "",
            "mobileNum": "",
            "workNum": "",
            "emailid": "",
            "venContDetails": [{
                    "addressLine1": "",
                    "addressLine2": "",
                    "city": "",
                    "state": ""
                }]
        }]
   }
}
</code>```

https://plnkr.co/edit/nP8R92KNkz8JEHpvH56S?p=catalogue
    For convenience I have added a json structure. I need to access all the
    data from the form and hit the rest api.
    The above is the link to the plunker. Thank you.

答:
Try this

```<code>$scope.dataObjToPost = {
  "vendor": {
    "vendorName": $scope.vendet.vendorName,
    "panNum": $scope.vendet.panNum,
    "venBusDetails": [{
      "personName": $scope.venBusDetails[0].personName,
      "mobileNum": $scope.venBusDetails[0].mobileNum,
      "workNum": $scope.venBusDetails[0].workNum,
      "emailid": $scope.venBusDetails[0].emailid,
      "venContDetails": [{
        "addressLine1": $scope.venContDetails[0].addressLine1,
        "addressLine2": $scope.venContDetails[0].addressLine2,
        "city": $scope.venContDetails[0].city,
        "state": $scope.venContDetails[0].state
      }]
    }]
  }
} //And send this data to POST method
</code>```

You used $scope.name in JS file but in HTML view you used ng-model="vendet.vendorName". Thats why it is always undefined.

UPDATED ANSWER Plunk LINK IS HERE

Body:
I am new to angular and trying to develop an application having nested
   ng-repeat and after submitting the form it should hit the rest api.
    I have been using $http to make rest api calls. The code gets submitted
    with normal data but does not get submitted with nested ng-repeat when i
    click the save button. Below I have provided the code with details.
    The whole data should be shown in the console. I might have made some
    mistake somewhere.Thanks in advance.

JS

 $scope.saveVenFormData = function(vendet){
     console.log($scope.vendet);
     $scope.venFullAddress.push({
        'vendorName': $scope.name,
        'panNum': $scope.panNum,
        'personName': $scope.venBusDetails.personName,
        'mobileNum': $scope.venBusDetails.mobileNum,
        'workNum': $scope.workNum,
        'emailid': $scope.emailid,
        'addressLine1': $scope.addressLine1,
        'addressLine2': $scope.addressLine2,
        'city': $scope.city,
        'state': $scope.state
        });
     var dataObj = $scope.venFullAddress;
    // console.log($scope.dataObj);

     $http.get('/showVendors').success(function(data){
        console.log(angular.toJson(data));
    });
    var res = $http.post('http://localhost:8080/dman/mm', dataObj);
    res.success(function(data, status, headers, config) {
        $scope.message = data;
    });
    res.error(function(data, status, headers, config) {
        alert( "failure message: " + JSON.stringify({data: data}));
    });
 };

JSON structure:

{
 "vendor": {
    "vendorName": "",
    "panNum": "",
    "venBusDetails": [{
            "personName": "",
            "mobileNum": "",
            "workNum": "",
            "emailid": "",
            "venContDetails": [{
                    "addressLine1": "",
                    "addressLine2": "",
                    "city": "",
                    "state": ""
                }]
        }]
   }
}

https://plnkr.co/edit/nP8R92KNkz8JEHpvH56S?p=catalogue
    For convenience I have added a json structure. I need to access all the
    data from the form and hit the rest api.
    The above is the link to the plunker. Thank you.

Body:
Try this

$scope.dataObjToPost = {
  "vendor": {
    "vendorName": $scope.vendet.vendorName,
    "panNum": $scope.vendet.panNum,
    "venBusDetails": [{
      "personName": $scope.venBusDetails[0].personName,
      "mobileNum": $scope.venBusDetails[0].mobileNum,
      "workNum": $scope.venBusDetails[0].workNum,
      "emailid": $scope.venBusDetails[0].emailid,
      "venContDetails": [{
        "addressLine1": $scope.venContDetails[0].addressLine1,
        "addressLine2": $scope.venContDetails[0].addressLine2,
        "city": $scope.venContDetails[0].city,
        "state": $scope.venContDetails[0].state
      }]
    }]
  }
} //And send this data to POST method

You used $scope.name in JS file but in HTML view you used ng-model="vendet.vendorName". Thats why it is always undefined.

UPDATED ANSWER Plunk LINK IS HERE


问:
Javascript/Angular2 How can I toggle button based on the form field values
I have a form with mandatory fields as -
1. First Name
2. Last Name
3. Phone
4. State
5. City
6. Date of Birth
 I have a button which should toggle to complete/Incomplete based on the form inputs.The button should toggle to  'complete' only when all the fields have proper values.If I remove any of the value again,the button should toggle to Incomplete.

In my ts file-

```<code>formCompleteOrIncomplete(person,index) {
   if (person.dateOfBirth !== "" && person.phone!== "" &&
      (person.firstName !== undefined || person.firstName !== "") && (person.lastName !== undefined || person.lastName !== "") && (person.state !== undefined || person.state !== "") && (person.city !== undefined || person.city !== "" )) {
      person.status = true;

    }
    else {
      person.status = false;
    }
}
</code>```

In my html file-

```<code><div class="tag">
   <div class="success" *ngIf="person.status">Complete</div>
   <div class="failed" *ngIf="!person.status">Incomplete</div>
</div>
</code>```

form fields-

```<code>   <md-input required [(ngModel)]="person.firstName" (ngModelChange) = "formCompleteOrIncomplete(person, index)" aria-placeholder="First Name" placeholder="First Name" name="firstName" #firstName="ngModel"></md-input>
</code>```

On page load the button shows 'Incomplete' as none of the field values are entered and when I enter all the fields, button is getting toggled to 'Complete' but when I try to empty any of the field again, it does not get toggled to 'Incomplete' again.

Also, when i do not include a check for 'undefined' and include only "" check, on page load the button shows 'complete'.NOt sure why is this happening.

Can someone tell me where I am going wrong?

答:
I believe that your problem is in the parts of your if statement that are using the || (or) operator. They should be using the && (and) operator as you don't want them to be either of those values to be filled in. When you change the first name field to be empty after you filled in the rest of the fields, the first part of the check will pass because an empty string is not undefined.

You should be able to clean that up a bit since you are checking for falsey values in both parts of your checks on the form fields. An empty string, undefined, and null will all convert to a false boolean value (you can check it out in your console by putting ! (not) operators before the value and see that when converted to a boolean, each will be false - i.e. !'' will convert the empty string to a boolean value and then do a not operation, so you will see true in your console).

formCompleteOrIncomplete(person,index) {
    // Inverted the order of your true/false portions to match if statement
    if (!person.dateOfBirth || !person.phone || !person.firstName ||
        !person.lastName || !person.state || !person.city) {
        person.status = false;
    }
    else {
        person.status = true;
    }

    // Or you could do this to keep the same structure of your if statement
    if (!!person.dateOfBirth && !!person.phone && !!person.firstName &&
        !!person.lastName && !!person.state && !!person.city) {
        person.status = true;
    }
    else {
        person.status = false;
    }

    // You could even set the status using your check if you feel comfortable doing that
    person.status =
        !!person.dateOfBirth && !!person.phone && !!person.firstName &&
        !!person.lastName && !!person.state && !!person.city;
}
```

Body:
I have a form with mandatory fields as -
1. First Name
2. Last Name
3. Phone
4. State
5. City
6. Date of Birth
 I have a button which should toggle to complete/Incomplete based on the form inputs.The button should toggle to  'complete' only when all the fields have proper values.If I remove any of the value again,the button should toggle to Incomplete.

In my ts file-

formCompleteOrIncomplete(person,index) {
   if (person.dateOfBirth !== "" && person.phone!== "" &&
      (person.firstName !== undefined || person.firstName !== "") && (person.lastName !== undefined || person.lastName !== "") && (person.state !== undefined || person.state !== "") && (person.city !== undefined || person.city !== "" )) {
      person.status = true;

    }
    else {
      person.status = false;
    }
}

In my html file-

Complete

Incomplete

form fields-

   <md-input required [(ngModel)]="person.firstName" (ngModelChange) = "formCompleteOrIncomplete(person, index)" aria-placeholder="First Name" placeholder="First Name" name="firstName" #firstName="ngModel"></md-input>

On page load the button shows 'Incomplete' as none of the field values are entered and when I enter all the fields, button is getting toggled to 'Complete' but when I try to empty any of the field again, it does not get toggled to 'Incomplete' again.

Also, when i do not include a check for 'undefined' and include only "" check, on page load the button shows 'complete'.NOt sure why is this happening.

Can someone tell me where I am going wrong?