问:
POST method is not set
During debug, I realize that all the request property and method I set is not executed at all. Can anyone explain why?

Because of this, whenever I request an output from URLConnection, that line will create a runtime error.

```<code>protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    try {
        url = new URL("https://ussouthcentral.services.azureml.net/workspaces/80b0369fe0df48308d956e2ddce52806/services/6379155db28f4c91b84e78d268a927f9/execute?api-version=2.0&format=swagger");
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    try {
        urlConnection = (URLConnection) url.openConnection();
        urlConnection.setDoOutput(true);
       // urlConnection.setRequestMethod("POST");

        String api_key = "Bearer api_key";
        urlConnection.setDoInput(true);

        urlConnection.addRequestProperty("Authorization", api_key);
        urlConnection.addRequestProperty("Content-Type", "application/json");
        urlConnection.addRequestProperty("Accept", "application/json");
         } catch (IOException e) {
        e.printStackTrace();
    }

   try {
        urlConnection.connect();
        urlConnection.getContent();
    } catch (IOException e) {
        e.printStackTrace();
    }
</code>```

答:
try the following the send post request</p>

```<code>try {
    url = new URL("https://ussouthcentral.services.azureml.net/workspaces/80b0369fe0df48308d956e2ddce52806/services/6379155db28f4c91b84e78d268a927f9/execute");

} catch (MalformedURLException e) {
    e.printStackTrace();
}
try {
    String requestBody = "api-version=2.0&format=swagger"
    urlConnection = (URLConnection) url.openConnection();
    String api_key = "Bearer api_key";

    urlConnection.addRequestProperty("Authorization", api_key);
    urlConnection.addRequestProperty("Content-Type", "application/json");
    urlConnection.addRequestProperty("Accept", "application/json");
    urlConnection.setDoOutput(true);
    OutputStreamWriter writer = new OutputStreamWriter(urlConnection.getOutputStream(),"UTF-8");
    writer.write(requestBody);
    writer.flush();
    if (urlconnection.getResponseCode() == 200)
     {
            InputStream input = urlconnection.getInputStream();
            //parse the response
     }

  } catch (IOException e) {
    e.printStackTrace();
}
</code>```

Title: POST method is not set

Body:
During debug, I realize that all the request property and method I set is not executed at all. Can anyone explain why?

Because of this, whenever I request an output from URLConnection, that line will create a runtime error.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    try {
        url = new URL("https://ussouthcentral.services.azureml.net/workspaces/80b0369fe0df48308d956e2ddce52806/services/6379155db28f4c91b84e78d268a927f9/execute?api-version=2.0&format=swagger");
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    try {
        urlConnection = (URLConnection) url.openConnection();
        urlConnection.setDoOutput(true);
       // urlConnection.setRequestMethod("POST");

        String api_key = "Bearer api_key";
        urlConnection.setDoInput(true);

        urlConnection.addRequestProperty("Authorization", api_key);
        urlConnection.addRequestProperty("Content-Type", "application/json");
        urlConnection.addRequestProperty("Accept", "application/json");
         } catch (IOException e) {
        e.printStackTrace();
    }

   try {
        urlConnection.connect();
        urlConnection.getContent();
    } catch (IOException e) {
        e.printStackTrace();
    }

Body:
try the following the send post request

try {
    url = new URL("https://ussouthcentral.services.azureml.net/workspaces/80b0369fe0df48308d956e2ddce52806/services/6379155db28f4c91b84e78d268a927f9/execute");

} catch (MalformedURLException e) {
    e.printStackTrace();
}
try {
    String requestBody = "api-version=2.0&format=swagger"
    urlConnection = (URLConnection) url.openConnection();
    String api_key = "Bearer api_key";

    urlConnection.addRequestProperty("Authorization", api_key);
    urlConnection.addRequestProperty("Content-Type", "application/json");
    urlConnection.addRequestProperty("Accept", "application/json");
    urlConnection.setDoOutput(true);
    OutputStreamWriter writer = new OutputStreamWriter(urlConnection.getOutputStream(),"UTF-8");
    writer.write(requestBody);
    writer.flush();
    if (urlconnection.getResponseCode() == 200)
     {
            InputStream input = urlconnection.getInputStream();
            //parse the response
     }

  } catch (IOException e) {
    e.printStackTrace();
}


来源: stackexchange

问:
sending data from controller to a typeclass in symfony 3
i'm trying to get data from the database and pas it to the form's drop down list

this is the Entity from where i'm looking to get the data from, specifically the type column

```<code><?php

namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;

/**
* @ORM\Entity(repositoryClass="AppBundle\Repository\TypesRepository")
* @ORM\Table(name="types")
*/
class Types
{

 /**
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 * @ORM\Column(name="idtype",type="integer")
 */
 private $idtype;
 /**
 * @ORM\Column(type="string", length=100)
 */
 private $type;
</code>```

and this is the type class that holds the form,as you can see i created a construct based on some internet cherche that i have done, the constructer adds the passed value to the variable, then it's called in the EntityType

```<code>class sell_form extends AbstractType
{

protected $cat;

public function __construct (Types $cat)
{
$this->cat = $cat;
}

public function buildForm(FormBuilderInterface $builder, array $options)
{

$builder

->add('categorie',EntityType::class,array(
                       "required"=>false,
                        'class' => 'AppBundle\Entity\Types',
                        'choices' => $cat
                        ))

                        ;
                ;
 }
 }
</code>```

and finaly this is the controller where i inisialize the $cat variable from the database using a repository function

```<code>/**
  * @Route("/Old/buy", name="old_buy")
*/
public function Old_buyAction()
{

return $this->render('/user_module/Old Views/Old_buy.html.twig');
        }
/**
   * @Route("/Old/sell", name="old_sell")
   *@Method({"GET","POST"})
*/
public function Old_sellAction()
{
$cat = $this->getDoctrine()->getManager()->getRepository('AppBundle:Types')-
>tn();

 /*line 122 */

$form = $this->createForm(new sell_form($cat));
 //$form = $this->createForm(sell_form::class,$cat);
 return $this->render("user_module/Old Views/old_sell.html.twig",array(
                                          "myForm"=>  $form->createView(),

                                    ));
</code>```

this is the error that it's shown

```<code>Catchable Fatal Error: Argument 1 passed to
AppBundle\Forms\sell_form::__construct() must be an instance of
AppBundle\Entity\Types, array given, called in
C...\OldController.php
on line 122 and defined`
</code>```

Many Thanks in advance

答:
$cat is an array of AppBundle\Entity\Types instances. You pass them into form constructor:

```<code>public function __construct (Types $cat)
{
    $this->cat = $cat;
}
</code>```

At this moment your code expects that $cat is a single Types instance, so it crashes:

AppBundle\Forms\sell_form::__construct() must be an instance of
  AppBundle\Entity\Types, array given

You need to expect an array:

```<code>public function __construct (array $cat)
{
    $this->cat = $cat;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i'm trying to get data from the database and pas it to the form's drop down list

this is the Entity from where i'm looking to get the data from, specifically the type column

<?php

namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;

/**
* @ORM\Entity(repositoryClass="AppBundle\Repository\TypesRepository")
* @ORM\Table(name="types")
*/
class Types
{

 /**
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 * @ORM\Column(name="idtype",type="integer")
 */
 private $idtype;
 /**
 * @ORM\Column(type="string", length=100)
 */
 private $type;

and this is the type class that holds the form,as you can see i created a construct based on some internet cherche that i have done, the constructer adds the passed value to the variable, then it's called in the EntityType

class sell_form extends AbstractType
{

protected $cat;

public function __construct (Types $cat)
{
$this->cat = $cat;
}

public function buildForm(FormBuilderInterface $builder, array $options)
{

$builder

->add('categorie',EntityType::class,array(
                       "required"=>false,
                        'class' => 'AppBundle\Entity\Types',
                        'choices' => $cat
                        ))

                        ;
                ;
 }
 }

and finaly this is the controller where i inisialize the $cat variable from the database using a repository function

/**
  * @Route("/Old/buy", name="old_buy")
*/
public function Old_buyAction()
{

return $this->render('/user_module/Old Views/Old_buy.html.twig');
        }
/**
   * @Route("/Old/sell", name="old_sell")
   *@Method({"GET","POST"})
*/
public function Old_sellAction()
{
$cat = $this->getDoctrine()->getManager()->getRepository('AppBundle:Types')-
>tn();

 /*line 122 */

$form = $this->createForm(new sell_form($cat));
 //$form = $this->createForm(sell_form::class,$cat);
 return $this->render("user_module/Old Views/old_sell.html.twig",array(
                                          "myForm"=>  $form->createView(),

                                    ));

this is the error that it's shown

Catchable Fatal Error: Argument 1 passed to
AppBundle\Forms\sell_form::__construct() must be an instance of
AppBundle\Entity\Types, array given, called in
C...\OldController.php
on line 122 and defined`

Many Thanks in advance

Body:
$cat is an array of AppBundle\Entity\Types instances. You pass them into form constructor:

public function __construct (Types $cat)
{
    $this->cat = $cat;
}

At this moment your code expects that $cat is a single Types instance, so it crashes:

AppBundle\Forms\sell_form::__construct() must be an instance of
  AppBundle\Entity\Types, array given

You need to expect an array:

public function __construct (array $cat)
{
    $this->cat = $cat;
}


问:
Atom menu is missing. How do I re-enable
The menu in Atom text editor is gone. I dont know how I disabled it. I tried F1-12 keys. How do I re enable it? Here's how it's looking now:

答:
Get cursor on top, where white header with file name, then press Alt.
To set top menu by default always visible.
You needed in top menu selected:
FILE -> Config... -> autoHideMenuBar: true (change it to autoHideMenuBar: false)
Save it.


问:
How to pass tag id to to onClick function in react?
I want to pass id of th tag  to on click function. Suppose i want to print the id of  in click() function console.log.
here is the code-

```<code><thead>
 <tr>
    <th id='name' onClick={this.click.bind(this)}>Name</th>
    <th id='phone' onClick={this.click.bind(this)}>Phone number</th>
    <th id='email' onClick={this.click.bind(this)}>Email</th>
 </tr>
</thead>
</code>```

the click() function-

```<code>click(){
console.log('the clicked id is:') //here i want the id
}
</code>```

答:
You can do something like this:</p>

```<code>const headers = [
  { id: 'name', label: 'Name' },
  { id: 'phone', label: 'Phone' },
  { id: 'Email', label: 'Name' },
]

const ab = (
  <thead>
    <tr>
      {headers.map(doc => (
        <th onClick={() => { this.click(doc.id) }}>{doc.label}</th>
      ))}
    </tr>
  </thead>
)
</code>```

Body:
I want to pass id of th tag  to on click function. Suppose i want to print the id of  in click() function console.log.
here is the code-

    Name
    Phone number
    Email

the click() function-

click(){
console.log('the clicked id is:') //here i want the id
}

Body:
You can do something like this:

const headers = [
  { id: 'name', label: 'Name' },
  { id: 'phone', label: 'Phone' },
  { id: 'Email', label: 'Name' },
]

const ab = (
  <thead>
    <tr>
      {headers.map(doc => (
        <th onClick={() => { this.click(doc.id) }}>{doc.label}</th>
      ))}
    </tr>
  </thead>
)


问:
what does (: ${foo%%bar}) mean in unix shell
```<code>#!/bin/sh
unset foo
(: ${foo%%bar}) 2> /dev/null
E1="$?"
</code>```

I know foo is a variable, ${foo%%bar} means remove last bar in $foo.

But what does (: ) mean there ?

I'm new to shell, can any one help me? Thanks!

答:
http://tldp.org/LDP/abs/html/special-chars.html

In combination with the >> redirection operator, has no effect on a pre-existing target file (: >> target_file). If the file did not previously exist, creates it.

Body:
#!/bin/sh
unset foo
(: ${foo%%bar}) 2> /dev/null
E1="$?"

I know foo is a variable, ${foo%%bar} means remove last bar in $foo.

But what does (: ) mean there ?

I'm new to shell, can any one help me? Thanks!


问:
Removing the exceeding data from matrices in order to have the same length
I have to matrix A and B with complimentary data of charging and discharging of batteries. Matrix B collect much more points than matrix A. I want to put some columns of these matrices together before processing the data. To do so I have to remove the exceeding points of the matrix B at the end of each charge and discharge.

Here is the code I'm trying to do but I have a problem to put the data in the exact rows in order to have a continuous table.

```<code>A = Matrix1;
B = Matrix2;
phase=sign(B(1,7));
tab(:,1) = A(index_star:index_end,1);
tab(:,3) = naninterp(A( index_star:index_end,5))/1000;
for i =1:150:length(tab)
    if  tab(i,3) >=x &&  sign(B( i,7))==phase %Collect the data corresponding to the charge
        tab(1:i,2) = tab(1:i,8) ;
        tab(1:i,4) = tab(1:i,7)*1000;
        j=i;
        break
    elseif  tab(i,3) <x &&  sign(B( i,7))~=phase %collect the discharge data
        tab(1:i,2) = B(1:i,8) ;
        tab(1:i,4) = B(1:i,7)*1000;
        j=i;
        break
    elseif  tab(i,3) <2  &&  sign(B(i,7))==phase %data dont match, so delete the exceeding B data
        k=i;
        while sign(B( i,7))==phase
            k1=k+1
            break
        end
        tab(j:k1,2) = B(j:k1,8) ;
        tab(i,4) = B(j:k1,7)*1000;
    elseif  tab(i,3) >=x && sign(B( i,7))~=phase %data dont match, so delete the exceeding B data
        k3=i;
        while sign(B( i,7))~=phase
            j=j+1
            break
            k4=k3;
        end
        tab(i,2) = B(k4,8) ;
        tab(i,4) = B(k4,7)*1000;
    end
end
</code>```

Any help is welcome.

答:
You first need to note that you require 2 counters. Something you tried with those i and j (and even k for some reason), but then you used just i in the end.
I used iA as index of A matrix and iB as index of B matrix. Clearer than just i and j.

```<code>for iA = 1 : length(A)
   if (A(iA) and B(iB) datapoint matches)
      tab ...
   else
      while(~datapoint_matches) % Same condition as above.
         iB = iB + 1;
      end
   end
end
</code>```

Alternative that requires a single loop is to go by B and if datapoint matches, add it, else simply continue with the B loop without advancing iA counter.

```<code>for iB = 1 : length(B)
   if (datapoint_matches) % The same as in upper case.
      tab(iA, n:m) = B(iB, :); % or whatever.
      iA = iA + 1;
   else % Data point does not match.
       % NOP - we are ignoring extra B points.
   end
end
</code>```

There are likely way faster Matlab approaches that ditch loops, but the above should be easier to understand and also much faster than any Matlab code if you put it in mex, so I don't think you should bother making your code harder to understand for you.
The only "optimization" I really advise you to do immediately is to first allocate space for a matrix - that you don't extend existing tab when you are adding B data points, but make tab big enough in the first place. It will also be much better if you ever want to port code to say C/C++, which often fails in a nasty way when you are dirtying space outside of the allocated array bounds :)

Body:
I have to matrix A and B with complimentary data of charging and discharging of batteries. Matrix B collect much more points than matrix A. I want to put some columns of these matrices together before processing the data. To do so I have to remove the exceeding points of the matrix B at the end of each charge and discharge.

Here is the code I'm trying to do but I have a problem to put the data in the exact rows in order to have a continuous table.

A = Matrix1;
B = Matrix2;
phase=sign(B(1,7));
tab(:,1) = A(index_star:index_end,1);
tab(:,3) = naninterp(A( index_star:index_end,5))/1000;
for i =1:150:length(tab)
    if  tab(i,3) >=x &&  sign(B( i,7))==phase %Collect the data corresponding to the charge
        tab(1:i,2) = tab(1:i,8) ;
        tab(1:i,4) = tab(1:i,7)*1000;
        j=i;
        break
    elseif  tab(i,3) <x &&  sign(B( i,7))~=phase %collect the discharge data
        tab(1:i,2) = B(1:i,8) ;
        tab(1:i,4) = B(1:i,7)*1000;
        j=i;
        break
    elseif  tab(i,3) <2  &&  sign(B(i,7))==phase %data dont match, so delete the exceeding B data
        k=i;
        while sign(B( i,7))==phase
            k1=k+1
            break
        end
        tab(j:k1,2) = B(j:k1,8) ;
        tab(i,4) = B(j:k1,7)*1000;
    elseif  tab(i,3) >=x && sign(B( i,7))~=phase %data dont match, so delete the exceeding B data
        k3=i;
        while sign(B( i,7))~=phase
            j=j+1
            break
            k4=k3;
        end
        tab(i,2) = B(k4,8) ;
        tab(i,4) = B(k4,7)*1000;
    end
end

Any help is welcome.

Body:
You first need to note that you require 2 counters. Something you tried with those i and j (and even k for some reason), but then you used just i in the end.
I used iA as index of A matrix and iB as index of B matrix. Clearer than just i and j.

for iA = 1 : length(A)
   if (A(iA) and B(iB) datapoint matches)
      tab ...
   else
      while(~datapoint_matches) % Same condition as above.
         iB = iB + 1;
      end
   end
end

Alternative that requires a single loop is to go by B and if datapoint matches, add it, else simply continue with the B loop without advancing iA counter.

for iB = 1 : length(B)
   if (datapoint_matches) % The same as in upper case.
      tab(iA, n:m) = B(iB, :); % or whatever.
      iA = iA + 1;
   else % Data point does not match.
       % NOP - we are ignoring extra B points.
   end
end

There are likely way faster Matlab approaches that ditch loops, but the above should be easier to understand and also much faster than any Matlab code if you put it in mex, so I don't think you should bother making your code harder to understand for you.
The only "optimization" I really advise you to do immediately is to first allocate space for a matrix - that you don't extend existing tab when you are adding B data points, but make tab big enough in the first place. It will also be much better if you ever want to port code to say C/C++, which often fails in a nasty way when you are dirtying space outside of the allocated array bounds :)


问:
Need solution to avoid repeated scanning in huge table
I have a event table which has 40 columns and fill up to 2 billion records. In that event table i would like to query for a combination event i.e Event A with Event B. Sometimes I may want to find more combination like Event A with B and C. It may goes to 5 or 6 combination.

I don't want to scan that table for every event in combination i.e Scanning for event A and scanning for event B. And I need a generic approach for more combination scanning as well.

Note: That 2 billion records is partitioned based on event date and data is been equally split.

Eg:

Need to find id's which has event A,B,C and need to find id's which has only A,B.

This number of combination is dynamic. I don't want to scan that table for each event and finally intersect the result.

答:
The having clause allows you to filter using the result of an aggregate function.  I've used a regular count but you may need a distinct count, depending on your table design.

Example:

```<code>-- Returns ids with 3 or more events.
SELECT
    x.Id,
    COUNT(*) AS EventCount
FROM
(
    VALUES
        (1, '2017-01-01', 'A'),
        (1, '2017-01-01', 'B'),
        (1, '2017-01-03', 'C'),
        (1, '2017-01-04', 'C'),
        (1, '2017-01-05', 'E'),
        (2, '2017-01-01', 'A'),
        (2, '2017-01-01', 'B'),
        (3, '2017-01-01', 'A')
) AS x(Id, [Date], [Event])
GROUP BY
    x.Id
HAVING
    COUNT(*) > 2
;
</code>```

Returns

```<code>Id  EventCount
1   5
</code>```

Body:
The having clause allows you to filter using the result of an aggregate function.  I've used a regular count but you may need a distinct count, depending on your table design.

Example:

-- Returns ids with 3 or more events.
SELECT
    x.Id,
    COUNT(*) AS EventCount
FROM
(
    VALUES
        (1, '2017-01-01', 'A'),
        (1, '2017-01-01', 'B'),
        (1, '2017-01-03', 'C'),
        (1, '2017-01-04', 'C'),
        (1, '2017-01-05', 'E'),
        (2, '2017-01-01', 'A'),
        (2, '2017-01-01', 'B'),
        (3, '2017-01-01', 'A')
) AS x(Id, [Date], [Event])
GROUP BY
    x.Id
HAVING
    COUNT(*) > 2
;

Returns

Id  EventCount
1   5


问:
slick db.run return direct the object
At the moment I do this:

```<code>  def addProcessStepTemplateToProcessTemplate(step: ProcessStepTemplatesModel, processId: Int): Future[Option[ProcessStepTemplatesModel]] = {
    val action = (processStepTemplates returning processStepTemplates.map(_.id)) += ProcessStepTemplatesModel(None, step.title, step.createdat, step.updatedat, step.deadline, step.comment, step.stepType, step.deleted, Some(processId))
    db.run(action).flatMap(id => {
      db.run(processStepTemplates.filter(_.id === id).result.headOption)
    })
  }
</code>```

I have two db.run to return the created record.

Is there a way to achieve this with only one db.run?

答:
You can use actions composition (with for-comprehension or with map/flatMap). For example:</p>

```<code>def addProcessStepTemplateToProcessTemplate(step: ProcessStepTemplatesModel, processId: Int): Future[Option[ProcessStepTemplatesModel]] = {
    val action = (processStepTemplates returning ...)

    val composedAction = action.flatMap { id =>
      processStepTemplates.filter(_.id === id).result.headOption
    }

    db.run(composedAction)
  }
</code>```

Title: slick db.run return direct the object

Body:
At the moment I do this:

  def addProcessStepTemplateToProcessTemplate(step: ProcessStepTemplatesModel, processId: Int): Future[Option[ProcessStepTemplatesModel]] = {
    val action = (processStepTemplates returning processStepTemplates.map(_.id)) += ProcessStepTemplatesModel(None, step.title, step.createdat, step.updatedat, step.deadline, step.comment, step.stepType, step.deleted, Some(processId))
    db.run(action).flatMap(id => {
      db.run(processStepTemplates.filter(_.id === id).result.headOption)
    })
  }

I have two db.run to return the created record.

Is there a way to achieve this with only one db.run?

Body:
You can use actions composition (with for-comprehension or with map/flatMap). For example:

def addProcessStepTemplateToProcessTemplate(step: ProcessStepTemplatesModel, processId: Int): Future[Option[ProcessStepTemplatesModel]] = {
    val action = (processStepTemplates returning ...)

    val composedAction = action.flatMap { id =>
      processStepTemplates.filter(_.id === id).result.headOption
    }

    db.run(composedAction)
  }


问:
Why there are the same variables of mine with a ':' in Visual Studio auto complete list?
What's the difference between myVar and myVar: in VS auto-complete list while working with functions. Why the second one is added to this list ?

答: this is a very cool feature. it allows your code to be more tolerant to parameter ordering changes... </p>

ContentLicense: CC BY-SA 2.5


问:
client side validation in htmlhelper without Model Class
I visited through different links but couldn't find desired answer. I am not using model for this view. Before sending data to server I want to check whether the text input is null or not.How can I validate it?</p>

```<code>@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<div class="container">
    <h2>Student Information</h2>
    @using (Html.BeginForm("insert", "Menu", FormMethod.Post, new { id="target"}))
    {
        <label>First Name:</label>
        <input type="text" class="form-control" name="firstname" id="f_name" />
        <button type="submit" class="btn btn-success" >Insert</button>
    }
</div>

<script>
    $(function () {
        $("#target".submit(function (event) {
            event.preventDefault();
            //return false;
        })
    })
</script>
</code>```

答:
You can get the value with a simple jQuery statement - $("#f_name").val() and then check if it is null  $("#f_name").val() == null

So your complete javascript would be

```<code><script>
    $(function () {
        $("#target".submit(function (event) {
            event.preventDefault();
            if($("#f_name").val() == null){
                return false;
            }
            return true;
        })
    })

</script>
</code>```

Body:
I visited through different links but couldn't find desired answer. I am not using model for this view. Before sending data to server I want to check whether the text input is null or not.How can I validate it?

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

Student Information

    @using (Html.BeginForm("insert", "Menu", FormMethod.Post, new { id="target"}))
    {
        First Name:
        <input type="text" class="form-control" name="firstname" id="f_name" />
        <button type="submit" class="btn btn-success" >Insert</button>
    }

Body:
You can get the value with a simple jQuery statement - $("#f_name").val() and then check if it is null  $("#f_name").val() == null

So your complete javascript would be

<script>
    $(function () {
        $("#target".submit(function (event) {
            event.preventDefault();
            if($("#f_name").val() == null){
                return false;
            }
            return true;
        })
    })

</script>


问:
Modified rat in a maze
It was asked me in an interview.you have given a m*n matrix filled with "1" and "0"."1" means you can use the cell and "0" means the cell is blocked.you can move in 4 directions left, right, top, bottom.every time you move upward direction or downward it cost you  1$.moving left or right will not be added to cost.so you have to write a code to check whether one can reach to destination index (x,y) starting from (0,0). If yes then print the minimum cost if no then print "-1".

I am not able to calculate the cost.
Here is my code

```<code>public class Test {

    /**
     * @param args the command line arguments
     */
    static int dest_x = 0;
    static int dest_y = 0;
    static int cost = 0;
    static int m = 0;
    static int n = 0;

    public static void main(String[] args) {
        // TODO code application logic here
        Scanner in = new Scanner(System.in);
        Test rat = new Test();
        int maze[][] = {
                {1, 1, 1, 1},
                {1, 1, 1, 0},
                {1, 1, 1, 1},
                {0, 0, 1, 1}
        };
        dest_x = in.nextInt();
        dest_y = in.nextInt();
        m = in.nextInt();
        n = in.nextInt();
        if (rat.solveMaze(maze))
            System.out.println("YES");

        else {
            System.out.println("NO");
        }
        System.out.println("cost = " + cost);
    }

    boolean isSafe(int maze[][], int x, int y) {
        // if (x,y outside maze) return false
        return (x >= 0 && x < m && y >= 0 &&
                y < n && maze[x][y] == 1);
    }

    boolean solveMaze(int maze[][]) {
        int sol[][] = {{0, 0, 0, 0},
                {0, 0, 0, 0},
                {0, 0, 0, 0},
                {0, 0, 0, 0}
        };

        if (!solveMazeUtil(maze, 0, 0, sol)) {
            return false;
        }
        return true;
    }

    boolean solveMazeUtil(int maze[][], int x, int y, int sol[][]) {
        // if (x,y is goal) return true
        if (x <= dest_x || y <= dest_y)
            if (x == dest_x && y == dest_y) {
                sol[x][y] = 1;
                return true;
            } else if (sol[x][y] == 1) {
                return false;
            }

            // Check if maze[x][y] is valid
            else if (isSafe(maze, x, y)) {
                // mark x,y as part of solution path
                sol[x][y] = 1;

                // Move forward in x direction
                if (solveMazeUtil(maze, x + 1, y, sol)) {
                    //System.out.println("here at x+1 x = " + x  + " y = " + y);
                    return true;
                }

                // Move down in y direction
                if (solveMazeUtil(maze, x, y + 1, sol)) {
                    //System.out.println("here at y+1 x = " + x  + " y = " + y);
                    cost++;
                    return true;
                }
                cost--;
                if (solveMazeUtil(maze, x - 1, y, sol)) {
                    // System.out.println("here at x-1 x = " + x  + " y = " + y);
                    return true;
                }
                if (solveMazeUtil(maze, x, y - 1, sol)) {
                    //System.out.println("here at y-1 x = " + x  + " y = " + y);
                    cost++;
                    return true;
                }
                cost--;
                /* If no solution then
                   BACKTRACK: unmark x,y as part of solution
                   path */
                sol[x][y] = 0;
                return false;
            }
        return false;
    }
}
</code>```

答:
Turn the maze into a Directed Graph and solve shortest path problem

Cells which are marked by "1" are nodes (marked by "0" should be ignored)

If we can move from one cell (node) to another, connect them with a directed edge; put cost (0 or 1) on the edge (please, notice, that we have a multigraph: two nodes can be connected with two different edges).

Finally, with a help of Dijkstra's algorithm find the shortest path (i.e. min cost) between required nodes.

Title: Modified rat in a maze

Body:
It was asked me in an interview.you have given a m*n matrix filled with "1" and "0"."1" means you can use the cell and "0" means the cell is blocked.you can move in 4 directions left, right, top, bottom.every time you move upward direction or downward it cost you  1$.moving left or right will not be added to cost.so you have to write a code to check whether one can reach to destination index (x,y) starting from (0,0). If yes then print the minimum cost if no then print "-1".

I am not able to calculate the cost.
Here is my code

public class Test {

    /**
     * @param args the command line arguments
     */
    static int dest_x = 0;
    static int dest_y = 0;
    static int cost = 0;
    static int m = 0;
    static int n = 0;

    public static void main(String[] args) {
        // TODO code application logic here
        Scanner in = new Scanner(System.in);
        Test rat = new Test();
        int maze[][] = {
                {1, 1, 1, 1},
                {1, 1, 1, 0},
                {1, 1, 1, 1},
                {0, 0, 1, 1}
        };
        dest_x = in.nextInt();
        dest_y = in.nextInt();
        m = in.nextInt();
        n = in.nextInt();
        if (rat.solveMaze(maze))
            System.out.println("YES");

        else {
            System.out.println("NO");
        }
        System.out.println("cost = " + cost);
    }

    boolean isSafe(int maze[][], int x, int y) {
        // if (x,y outside maze) return false
        return (x >= 0 && x < m && y >= 0 &&
                y < n && maze[x][y] == 1);
    }

    boolean solveMaze(int maze[][]) {
        int sol[][] = {{0, 0, 0, 0},
                {0, 0, 0, 0},
                {0, 0, 0, 0},
                {0, 0, 0, 0}
        };

        if (!solveMazeUtil(maze, 0, 0, sol)) {
            return false;
        }
        return true;
    }

    boolean solveMazeUtil(int maze[][], int x, int y, int sol[][]) {
        // if (x,y is goal) return true
        if (x <= dest_x || y <= dest_y)
            if (x == dest_x && y == dest_y) {
                sol[x][y] = 1;
                return true;
            } else if (sol[x][y] == 1) {
                return false;
            }

            // Check if maze[x][y] is valid
            else if (isSafe(maze, x, y)) {
                // mark x,y as part of solution path
                sol[x][y] = 1;

                // Move forward in x direction
                if (solveMazeUtil(maze, x + 1, y, sol)) {
                    //System.out.println("here at x+1 x = " + x  + " y = " + y);
                    return true;
                }

                // Move down in y direction
                if (solveMazeUtil(maze, x, y + 1, sol)) {
                    //System.out.println("here at y+1 x = " + x  + " y = " + y);
                    cost++;
                    return true;
                }
                cost--;
                if (solveMazeUtil(maze, x - 1, y, sol)) {
                    // System.out.println("here at x-1 x = " + x  + " y = " + y);
                    return true;
                }
                if (solveMazeUtil(maze, x, y - 1, sol)) {
                    //System.out.println("here at y-1 x = " + x  + " y = " + y);
                    cost++;
                    return true;
                }
                cost--;
                /* If no solution then
                   BACKTRACK: unmark x,y as part of solution
                   path */
                sol[x][y] = 0;
                return false;
            }
        return false;
    }
}


问:
How to join two tables using Spring Data JPA
I have two entities similar to the following:

```<code>Doctor:
@Id
@Column(name = "ID", nullable = false, updatable = false)
private Long id;
...

DoctorSpeciality:
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID", nullable = false, updatable = false)
private Long id;

@ManyToOne
@JoinColumn(name = "DOCTOR_ID")
private Doctor doctor;

@ManyToOne
@JoinColumn(name = "SPECIALITY_ID")
private Speciality speciality;
</code>```

I want to join these, to retrieve all Doctors, given the SpecialityId, by DoctorRepository, using JPA Specifications.

Can someone help me with this?

答:
In your DoctorRepository try this

```<code>@Query("Select d from Doctor d where d.speciality.id = :id")
List<Doctor> findAllBySpeciality(@Param("id") long id);
</code>```

Update 1 : With the mappings you provided the following JPQL is working.

```<code>@Query("Select ds.doctor from DoctorSpeciality ds where ds.speciality.id = :id")
List<Doctor> findAllBySpeciality(@Param("id") long id);
</code>```

Body:
I have two entities similar to the following:

Doctor:
@Id
@Column(name = "ID", nullable = false, updatable = false)
private Long id;
...

DoctorSpeciality:
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID", nullable = false, updatable = false)
private Long id;

@ManyToOne
@JoinColumn(name = "DOCTOR_ID")
private Doctor doctor;

@ManyToOne
@JoinColumn(name = "SPECIALITY_ID")
private Speciality speciality;

I want to join these, to retrieve all Doctors, given the SpecialityId, by DoctorRepository, using JPA Specifications.

Can someone help me with this?

Body:
In your DoctorRepository try this

@Query("Select d from Doctor d where d.speciality.id = :id")
List<Doctor> findAllBySpeciality(@Param("id") long id);

Update 1 : With the mappings you provided the following JPQL is working.

@Query("Select ds.doctor from DoctorSpeciality ds where ds.speciality.id = :id")
List<Doctor> findAllBySpeciality(@Param("id") long id);


问:
Mapbox Callout moving on Pan/Zoom.
I have followed the guide here to create custom Callout Views. I added two lines to the custom class:

```<code>var dismissesAutomatically: Bool = false
var isAnchoredToAnnotation: Bool = true
</code>```

These seem to do the job when it comes to keeping the Callout View displayed when panning and zooming, and keeping it anchored to the annotation. However, The Callout seems to drop down about 20 pixels when the user pans or zooms.

Initial View when annotation is tapped, but before panning/zooming:

View immediately after panning/zooming:

答:
From the Mapbox API docs for isAnchoredToAnnotation:

A Boolean value indicating whether the callout view should be anchored to the corresponding annotation. You can adjust the callout view’s precise location by overriding -[UIView setCenter:]. The callout view will not be anchored to the annotation if this optional property is unimplemented.

In Swift that would be: myView.center =

Hope this helps.

EDIT :-
Take a look at this example on the Mapbox website that describes how to implement draggable annotations. The interesting part is in the setDragState method where the drag state (an MGLAnnotationViewDragState) is tested. I'd suggest implementing the callout centre coordinate update in the .dragging case in a similar fashion to the way they have implemented the startDragging() and endDragging() functionality.

Title: Mapbox Callout moving on Pan/Zoom.

Body:
I have followed the guide here to create custom Callout Views. I added two lines to the custom class:

var dismissesAutomatically: Bool = false
var isAnchoredToAnnotation: Bool = true

These seem to do the job when it comes to keeping the Callout View displayed when panning and zooming, and keeping it anchored to the annotation. However, The Callout seems to drop down about 20 pixels when the user pans or zooms.

Initial View when annotation is tapped, but before panning/zooming:

View immediately after panning/zooming:


问:
Chat server for Rails
As it is evident that AJAX based chats do not scale, so what would you use for chats? Custom servers? Or any other methods?

Since with Rails each chat connection will take lots of memory, it won't be feasible to even have Rails run for each message. What do you recommend for use here?

答:
I also tried to implement a sample chat app with AJAX (in built Ajax.updater) but it didn't workout. I'm  sure there might be some good ajax solution.

But since this is based on server push technology, try Juggernaut (http://juggernaut.rubyforge.org/). I personally haven't tried, but it seems like it's good.

Or else consider web sockets (in HTML5) if possible.

ContentLicense: CC BY-SA 4.0

Title: Chat server for Rails


问:
Knockoutjs - Can I use data-bind attr together with i18n?
I'm modifying a template in magento2, which have this chunk of code:

```<code><a href="#"
   class="item-action action-gift"
   data-bind="
   attr: {title: 'Gift Options'}
   ">
    <span data-bind="i18n: 'Gift options'"></span>
</a>
</code>```

I want to be able to translate the title attribute like so

```<code><a href="#"
   class="item-action action-gift"
   data-bind="
   attr: {title: i18n:'Gift Options'}
   ">
    <span data-bind="i18n: 'Gift options'"></span>
</a>
</code>```

But that obviously gives error. Is it possible to have i18n in the attr binding? How to do it properly if it is?

答:
You can create a custom binding handler that calls a default binding by using ko.applyBindingsToNode.

To inject your i18n translation step, you create a ko.pureComputed representation of your settings object inside the init method and call the original attr binding with it.

Say we have a function named i18n that takes a string and returns another string. We'll go from:

```<code>attr: { title: "my string" }
</code>```

To

```<code>attr: { title: i18n("my string") }
</code>```

Here's how we create the computed object that is passed to attr:

```<code>ko.bindingHandlers.i18nAttr = {
  init: function(el, va) {
    var translated = ko.pureComputed(function() {
      // Support observable options objects: unwrap
      var options = ko.unwrap(va());

      return Object
        .keys(options)
        .reduce(function(tOptions, k) {
          // Support observable properties: unwrap
          tOptions[k] = i18n(ko.unwrap(options[k]));
          return tOptions;
        }, {});
    });

    return ko.applyBindingsToNode(el, { attr: translated });
  }
};
</code>```

In a working example: (I created a computed i18n function to support toggling on and off translations/switching languages)

ko.bindingHandlers.i18nAttr = {
  init: function(el, va) {
    var translated = ko.pureComputed(function() {
      var options = ko.unwrap(va());
      var translate = i18n();

      return Object
        .keys(options)
        .reduce(function(tOptions, k) {
          tOptions[k] = translate(ko.unwrap(options[k]));
          return tOptions;
        }, {});
    });

    return ko.applyBindingsToNode(el, { attr: translated });
  }
};

var translate = ko.observable(true);
var i18n = translater(translate);

var vm = {
  title: "Elevator",
  placeholder: "Cookie",
  translate: translate
};

ko.applyBindings(vm);

// Mock i18n method
function translater(doTranslate) {
  return ko.pureComputed(function() {
    return doTranslate()
      ? function(str) { return str; }
      : function(str) {
          return ({
            "Elevator": "Lift",
            "Cookie": "Biscuit"
          })[str];
        };
  });
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<input data-bind="i18nAttr: { placeholder: placeholder }"/>
hover for title

<label><input type="checkbox" data-bind="checked: translate">Translate</label></code>```

Body:
I'm modifying a template in magento2, which have this chunk of code:

I want to be able to translate the title attribute like so

But that obviously gives error. Is it possible to have i18n in the attr binding? How to do it properly if it is?

Body:
You can create a custom binding handler that calls a default binding by using ko.applyBindingsToNode.

To inject your i18n translation step, you create a ko.pureComputed representation of your settings object inside the init method and call the original attr binding with it.

Say we have a function named i18n that takes a string and returns another string. We'll go from:

attr: { title: "my string" }

To

attr: { title: i18n("my string") }

Here's how we create the computed object that is passed to attr:

ko.bindingHandlers.i18nAttr = {
  init: function(el, va) {
    var translated = ko.pureComputed(function() {
      // Support observable options objects: unwrap
      var options = ko.unwrap(va());

      return Object
        .keys(options)
        .reduce(function(tOptions, k) {
          // Support observable properties: unwrap
          tOptions[k] = i18n(ko.unwrap(options[k]));
          return tOptions;
        }, {});
    });

    return ko.applyBindingsToNode(el, { attr: translated });
  }
};

In a working example: (I created a computed i18n function to support toggling on and off translations/switching languages)

ko.bindingHandlers.i18nAttr = {
  init: function(el, va) {
    var translated = ko.pureComputed(function() {
      var options = ko.unwrap(va());
      var translate = i18n();

      return Object
        .keys(options)
        .reduce(function(tOptions, k) {
          tOptions[k] = translate(ko.unwrap(options[k]));
          return tOptions;
        }, {});
    });

    return ko.applyBindingsToNode(el, { attr: translated });
  }
};

var translate = ko.observable(true);
var i18n = translater(translate);

var vm = {
  title: "Elevator",
  placeholder: "Cookie",
  translate: translate
};

ko.applyBindings(vm);

// Mock i18n method
function translater(doTranslate) {
  return ko.pureComputed(function() {
    return doTranslate()
      ? function(str) { return str; }
      : function(str) {
          return ({
            "Elevator": "Lift",
            "Cookie": "Biscuit"
          })[str];
        };
  });
};

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<input data-bind="i18nAttr: { placeholder: placeholder }"/>
<a data-bind="i18nAttr: { title: title }">hover for title</a>

<label><input type="checkbox" data-bind="checked: translate">Translate</label>


问:
How to rapidly press a button to generate sound on Xcode?
Here is my following code for an Xcode project. When I press "play()," a short drum sound occurs. The thing is, when I tap the custom view multiple times in succession, I want quick drum sounds to occur in succession. However, the sound occurs after the full clip (of 2 seconds) as finished, leaving lots of deadspace. I tried many different things but I can't.</p>

```<code>@IBOutlet weak var tabla: TablaHead!

var tablaSoundUrl = NSURL(fileURLWithPath: Bundle.main.path(forResource: "TablaSound", ofType: "mp3")!)
var tablaAudioPlayer = AVAudioPlayer()

override func viewDidLoad() {
    super.viewDidLoad()
    tablaAudioPlayer = try! AVAudioPlayer(contentsOf: tablaSoundUrl as URL)
}

@IBAction func tapped(_ sender: UITapGestureRecognizer) {
    if sender.state == .ended {
        playNoise()
    }
}

public func playNoise() {
    if (tablaAudioPlayer.isPlaying) {
        tablaAudioPlayer.stop()
        tablaAudioPlayer.play()
    } else {
        tablaAudioPlayer.play()
    }
}
</code>```

答:
Try something like this</p>

```<code>@IBOutlet weak var tabla: TablaHead!

var tablaSoundUrl = NSURL(fileURLWithPath: Bundle.main.path(forResource: "TablaSound", ofType: "mp3")!)
var tablaAudioPlayer = AVAudioPlayer()
var tapsCount = 0

override func viewDidLoad() {
    super.viewDidLoad()
    tablaAudioPlayer = try! AVAudioPlayer(contentsOf: tablaSoundUrl as URL)
}

@IBAction func tapped(_ sender: UITapGestureRecognizer) {
    tapsCount += 1
    if sender.state == .ended && tapsCount == 1 {
        playNoise()
    }
}

public func playNoise() {
    tapsCount -= 1
    tablaAudioPlayer.play()
    if tapsCount > 0 {
        playNoise()
    }
}
</code>```

Body:
Here is my following code for an Xcode project. When I press "play()," a short drum sound occurs. The thing is, when I tap the custom view multiple times in succession, I want quick drum sounds to occur in succession. However, the sound occurs after the full clip (of 2 seconds) as finished, leaving lots of deadspace. I tried many different things but I can't.

@IBOutlet weak var tabla: TablaHead!

var tablaSoundUrl = NSURL(fileURLWithPath: Bundle.main.path(forResource: "TablaSound", ofType: "mp3")!)
var tablaAudioPlayer = AVAudioPlayer()

override func viewDidLoad() {
    super.viewDidLoad()
    tablaAudioPlayer = try! AVAudioPlayer(contentsOf: tablaSoundUrl as URL)
}

@IBAction func tapped(_ sender: UITapGestureRecognizer) {
    if sender.state == .ended {
        playNoise()
    }
}

public func playNoise() {
    if (tablaAudioPlayer.isPlaying) {
        tablaAudioPlayer.stop()
        tablaAudioPlayer.play()
    } else {
        tablaAudioPlayer.play()
    }
}

Body:
Try something like this

@IBOutlet weak var tabla: TablaHead!

var tablaSoundUrl = NSURL(fileURLWithPath: Bundle.main.path(forResource: "TablaSound", ofType: "mp3")!)
var tablaAudioPlayer = AVAudioPlayer()
var tapsCount = 0

override func viewDidLoad() {
    super.viewDidLoad()
    tablaAudioPlayer = try! AVAudioPlayer(contentsOf: tablaSoundUrl as URL)
}

@IBAction func tapped(_ sender: UITapGestureRecognizer) {
    tapsCount += 1
    if sender.state == .ended && tapsCount == 1 {
        playNoise()
    }
}

public func playNoise() {
    tapsCount -= 1
    tablaAudioPlayer.play()
    if tapsCount > 0 {
        playNoise()
    }
}


问:
ng-repeat filter either equals to first name or last name
in angularJs is there way to filter ng-repeat by matching two or more fields?
for example I want to list all the person who has letter "J" in either first name or last name.
if I use current function it list out the person who has letter 'J' in both first name and last name</p>

```<code><!DOCTYPE html>
<html ng-app="myApp">

<head>
    <meta name="format-detection" content="telephone=no">
    <meta name="msapplication-tap-highlight" content="no">
    <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
    <title>Welcome To My Homepage</title>
    <link href="css/style.css" rel="stylesheet" />
    <link href="css/bootstrap.min.css" rel="stylesheet" />
</head>

<body ng-controller="MyCtrl">
    <div ng-controller="MyCtrl">
        <input type="text" ng-model="search">{{search}}
        <table border="1">
            <tr ng-repeat="row in list | filter:{firstName:search} | filter:{lastName:search}">
                <td>{{row.firstName}} {{row.lastName}}</td>
            </tr>
        </table>
    </div>

    <script src="js/jquery-2.2.1.js"></script>
    <script src="js/angular.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <script type="text/javascript">

        var myApp = angular.module('myApp',[]);

        myApp.controller('MyCtrl', ['$scope','$http','$filter', function($scope,$http,$filter) {

            $scope.list = [{
                    "id": 1,
                    "address": "New York City",
                    "firstName": "Jennifer",
                    "middleName": null,
                    "lastName": "Aniston"
                    }, {
                        "id": 1,
                        "address": "New York City",
                        "firstName": "Jennifer",
                        "middleName": null,
                        "lastName": "Leela"
                    }, {
                        "id": 2,
                        "address": "Beverley Hills",
                        "firstName": "Angelina",
                        "middleName": null,
                        "lastName": "Jolie"
                    }, {
                    "id": 3,
                    "address": "London",
                    "firstName": "Emma",
                    "middleName": null,
                    "lastName": "Watson"
            }];

        }]);
    </script>

</html>
</code>```

答:
Change your model with this,   ng-model="search.$"

var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', ['$scope','$http','$filter', function($scope,$http,$filter) {
            $scope.list = [{
                    "id": 1,
                    "address": "New York City",
                    "firstName": "Jennifer",
                    "middleName": null,
                    "lastName": "Aniston"
                    }, {
                        "id": 1,
                        "address": "New York City",
                        "firstName": "Jennifer",
                        "middleName": null,
                        "lastName": "Leela"
                    }, {
                        "id": 2,
                        "address": "Beverley Hills",
                        "firstName": "Angelina",
                        "middleName": null,
                        "lastName": "Jolie"
                    }, {
                    "id": 3,
                    "address": "London",
                    "firstName": "Emma",
                    "middleName": null,
                    "lastName": "Watson"
            }];

 $scope.myFilter = function (item) {
    return item === 'red' || item === 'blue';
};
}]);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html ng-app="myApp">

<head>
    <meta name="format-detection" content="telephone=no">
    <meta name="msapplication-tap-highlight" content="no">
    <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
    <title>Welcome To My Homepage</title>
    <link href="css/style.css" rel="stylesheet" />
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
    <link href="css/bootstrap.min.css" rel="stylesheet" />
</head>

<body ng-controller="MyCtrl">
    <div ng-controller="MyCtrl">
     <input type="text" ng-model="search.$">
    <table border="1">
      <tr ng-repeat="row in list | filter:search">
        <td>{{row.firstName}} {{row.lastName}}</td>
      </tr>
    </table>
    </div>

</body>
</html></code>```

Body:
in angularJs is there way to filter ng-repeat by matching two or more fields?
for example I want to list all the person who has letter "J" in either first name or last name.
if I use current function it list out the person who has letter 'J' in both first name and last name

<!DOCTYPE html>

    <meta name="format-detection" content="telephone=no">
    <meta name="msapplication-tap-highlight" content="no">
    <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
    <title>Welcome To My Homepage</title>
    <link href="css/style.css" rel="stylesheet" />
    <link href="css/bootstrap.min.css" rel="stylesheet" />

        <input type="text" ng-model="search">{{search}}

                {{row.firstName}} {{row.lastName}}

Body:
Change your model with this,   ng-model="search.$"

var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', ['$scope','$http','$filter', function($scope,$http,$filter) {
            $scope.list = [{
                    "id": 1,
                    "address": "New York City",
                    "firstName": "Jennifer",
                    "middleName": null,
                    "lastName": "Aniston"
                    }, {
                        "id": 1,
                        "address": "New York City",
                        "firstName": "Jennifer",
                        "middleName": null,
                        "lastName": "Leela"
                    }, {
                        "id": 2,
                        "address": "Beverley Hills",
                        "firstName": "Angelina",
                        "middleName": null,
                        "lastName": "Jolie"
                    }, {
                    "id": 3,
                    "address": "London",
                    "firstName": "Emma",
                    "middleName": null,
                    "lastName": "Watson"
            }];

 $scope.myFilter = function (item) {
    return item === 'red' || item === 'blue';
};
}]);

<!DOCTYPE html>
<html ng-app="myApp">

<head>
    <meta name="format-detection" content="telephone=no">
    <meta name="msapplication-tap-highlight" content="no">
    <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
    <title>Welcome To My Homepage</title>
    <link href="css/style.css" rel="stylesheet" />
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
    <link href="css/bootstrap.min.css" rel="stylesheet" />
</head>

<body ng-controller="MyCtrl">
    <div ng-controller="MyCtrl">
     <input type="text" ng-model="search.$">
    <table border="1">
      <tr ng-repeat="row in list | filter:search">
        <td>{{row.firstName}} {{row.lastName}}</td>
      </tr>
    </table>
    </div>

</body>
</html>


问:
create virtual dynamically subdomain
My application have domain as cool_event whereas it's parent domain is coolacharya.com

So when I hit URL as http://coolacharya.com/cool_event/admin_event. After hitting this URL, if login is successful with user_name shruti then the URL should be like http://shruti.coolacharya.com/cool_event/admin_event Or coolacharya.com/shruti.cool_event/admin_event

I don't want to create separate folder for each user.

My .htaccess file is:

```<code>RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php?/$0 [PT,L]
</code>```

答: It's easy to create the wildcard subdomains. Check my post for create the wildcard subdomains dynamically in Create subdomains on the fly with .htaccess (PHP) .</p>

Title: create virtual dynamically subdomain

Body:
My application have domain as cool_event whereas it's parent domain is coolacharya.com

So when I hit URL as http://coolacharya.com/cool_event/admin_event. After hitting this URL, if login is successful with user_name shruti then the URL should be like http://shruti.coolacharya.com/cool_event/admin_event Or coolacharya.com/shruti.cool_event/admin_event

I don't want to create separate folder for each user.

My .htaccess file is:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php?/$0 [PT,L]


问:
CoreNFC available on which Apple devices
Hi I want to know on which Apple devices CoreNFC works.
On https://developer.apple.com/documentation/corenfc there are only Apple Developer Screen iPhone 7 and 7plus.
iPad or Apple Watch doesn't support yet?</p>

答:
No.. You read is exactly correct

NFC support is added only for iphone 7 and iphone 7 plus. for other device you still need to wait


问:
Insert schemaLocation in the XML File using XSLT v2.0
I'm having a problem inserting a schemaLocation in the XML File. I almost got the expected output but the other elements populates the schemaLocation. Here is my sample file:

INPUT:

```<code><Sync releaseID="9.2">
<Document>
    <Group>
        <Header>
            <Field1>232</Field1>
            <Field2>dfd</Field2>
        </Header>
    </Group>
</Document>
</code>```

And, I want to add the namespace and schemalocation in <Document> tag. Here is my XSLT:

```<code><xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>
<xsl:template match="*[ancestor-or-self::Document]">
    <xsl:element name="{name()}" namespace="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">
        <xsl:attribute name="xsi:schemaLocation">urn:iso:std:iso:20022:tech:xsd:pain.001.001.03</xsl:attribute>
        <xsl:apply-templates select="*"/>
    </xsl:element>
</xsl:template>
</xsl:stylesheet>
</code>```

GENERATED OUTPUT:

```<code><Sync releaseID="9.2">
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">
    <Group xsi:schemaLocation="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">
        <Header xsi:schemaLocation="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">
            <Field1 xsi:schemaLocation="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">232</Field1>
            <Field2 xsi:schemaLocation="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">dfd</Field2>
        </Header>
    </Group>
</Document>
</code>```

EXPECTED OUTPUT:

```<code><Sync releaseID="9.2">
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">
    <Group>
        <Header>
            <Field1>232</Field1>
            <Field2>dfd</Field2>
        </Header>
    </Group>
</Document>
</code>```

How can I remove the schemaLocation in the other elements?

Thanks.

答:
You need to add a template matching Document only and add the attribute there (and only there). Then change your existing template so that it matches only descendants of Document:

```<code><xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="*[ancestor::Document]">
    <xsl:element name="{name()}" namespace="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">
        <xsl:apply-templates select="*"/>
    </xsl:element>
</xsl:template>

<xsl:template match="Document">
    <Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">
        <xsl:apply-templates select="*"/>
    </Document>
</xsl:template>

</xsl:stylesheet>
</code>```

Body:
I'm having a problem inserting a schemaLocation in the XML File. I almost got the expected output but the other elements populates the schemaLocation. Here is my sample file:

INPUT:

<Sync releaseID="9.2">
<Document>
    <Group>

            <Field1>232</Field1>
            <Field2>dfd</Field2>

    </Group>
</Document>

And, I want to add the namespace and schemalocation in <Document> tag. Here is my XSLT:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>
<xsl:template match="*[ancestor-or-self::Document]">
    <xsl:element name="{name()}" namespace="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">
        <xsl:attribute name="xsi:schemaLocation">urn:iso:std:iso:20022:tech:xsd:pain.001.001.03</xsl:attribute>
        <xsl:apply-templates select="*"/>
    </xsl:element>
</xsl:template>
</xsl:stylesheet>

GENERATED OUTPUT:

<Sync releaseID="9.2">
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">
    <Group xsi:schemaLocation="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">

            <Field1 xsi:schemaLocation="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">232</Field1>
            <Field2 xsi:schemaLocation="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">dfd</Field2>

    </Group>
</Document>

EXPECTED OUTPUT:

<Sync releaseID="9.2">
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">
    <Group>

            <Field1>232</Field1>
            <Field2>dfd</Field2>

    </Group>
</Document>

How can I remove the schemaLocation in the other elements?

Thanks.

Body:
You need to add a template matching Document only and add the attribute there (and only there). Then change your existing template so that it matches only descendants of Document:

<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="*[ancestor::Document]">
    <xsl:element name="{name()}" namespace="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">
        <xsl:apply-templates select="*"/>
    </xsl:element>
</xsl:template>

<xsl:template match="Document">
    <Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">
        <xsl:apply-templates select="*"/>
    </Document>
</xsl:template>

</xsl:stylesheet>


问:
Count specific values that belong to the same column SQL Server
I would like to ask for help I would like to count the number of records but having 2 conditions for 2 specific values only from a one single column:

Count the records first:

count(service) as contacts

```<code>service | state | address
service1| 1     |123
service2| 1     |321
service3| 3     |332
service1| 2     |333
service2| 2     |111
service3| 3     |333
</code>```

1st result

```<code>Service | Contacts | status
service1| 1        | 1
service1| 1        | 2
service1| 1        | 3
service2| 1        | 1
service2| 1        | 2
service2| 1        | 3
</code>```

if status = 1 and 2 then add to count else 0 (only count who's "status" is equal to 1 and 2.

Result:

Final result

```<code>Service  | Contacts
Service1 | 2
Service2 | 2
</code>```

sorry for the confusion
Thanks for your big help

答:
This should work for all major databases</p>

```<code>SELECT service,
SUM(CASE WHEN status IN(1,2) THEN contacts ELSE 0 END) as Contacts
FROM (your query) as x
GROUP BY service
</code>```

Body:
I would like to ask for help I would like to count the number of records but having 2 conditions for 2 specific values only from a one single column:

Count the records first:

count(service) as contacts

service | state | address
service1| 1     |123
service2| 1     |321
service3| 3     |332
service1| 2     |333
service2| 2     |111
service3| 3     |333

1st result

Service | Contacts | status
service1| 1        | 1
service1| 1        | 2
service1| 1        | 3
service2| 1        | 1
service2| 1        | 2
service2| 1        | 3

if status = 1 and 2 then add to count else 0 (only count who's "status" is equal to 1 and 2.

Result:

Final result

Service  | Contacts
Service1 | 2
Service2 | 2

sorry for the confusion
Thanks for your big help

Body:
This should work for all major databases

SELECT service,
SUM(CASE WHEN status IN(1,2) THEN contacts ELSE 0 END) as Contacts
FROM (your query) as x
GROUP BY service


问:
Written only dash in apache access log
A normal log looks like this:

111.111.111.111 222.222.222.222 - - [06/Jun/2017:02:19:00 +0900] "GET /monitor/l7check.nhn HTTP/1.1" 200 4 1222 "-" "-"

but some log looks like this:

111.111.111.111 333.333.333.333 - - [06/Jun/2017:02:18:58 +0900] "-" 408 - 13 "-" "-"

I can't understand the meaning of this log.

Why does it have only a 'dash' instead of a 'get URL'?

Is it possible to log to a URL without requesting a URL?

答:
https://www.rfc-editor.org/rfc/rfc7231#section-6.5.7

6.5.7.  408 Request Timeout

The 408 (Request Timeout) status code indicates that the server did not receive a complete request message within the time that it was prepared to wait.  A server SHOULD send the "close" connection option (Section 6.1 of [RFC7230]) in the response, since 408 implies that the server has decided to close the connection rather than continue waiting.  If the client has an outstanding request in transit, the client MAY repeat that request on a new connection.

So, the client connected, but did not send any HTTP request. The server waited, and eventually closed the connection.

Title: Written only dash in apache access log


问:
disable maven execution debug output
Option -X in maven is able to display execution debug output including the parameters. is it possible to configure the maven POM.xml to disable the debug log output for the entire execution process or within the execution of one particular maven plugin even if "-X" option is passed in maven? Thanks</p>

答:
Try:

MAVEN_OPTS="-Dorg.slf4j.simpleLogger.defaultLogLevel=ERROR" mvn --batch-mode dependency:build-classpath
[no output]

To crosscheck, with errors:

MAVEN_OPTS="-Dorg.slf4j.simpleLogger.defaultLogLevel=ERROR" mvn --batch-mode invalid
[ERROR] Could not find goal 'build-classpat' in plugin org.apache.maven.plugins:maven-dependency-plugin:2.10 among available goals analyze, analyze-dep-mgt, analyze-duplicate, analyze-only, analyze-report, build-classpath, copy, copy-dependencies, display-ancestors, get, go-offline, help, list, list-repositories, properties, purge-local-repository, resolve, resolve-plugins, sources, tree, unpack, unpack-dependencies -> [Help 1]

Maybe you also want --batch-mode to disable colors and prompts.

You might set the level according to your needs.

Title: disable maven execution debug output


答:
```<code>select service,
       sum(case when status in(1,2) then contacts else 0 end) as contact_count
from MyTable
group by service
</code>```

What this will do is evaluate each row and include the contacts value in the sum where the status is one that is required. As it is an aggregate, you need to group by the service

Title: Count specific values that belong to the same column SQL Server

Body:
select service,
       sum(case when status in(1,2) then contacts else 0 end) as contact_count
from MyTable
group by service

What this will do is evaluate each row and include the contacts value in the sum where the status is one that is required. As it is an aggregate, you need to group by the service


问:
ggplot with a lot of groups; subplots (facets) for better arrangement
I have a data frame with values for gross profits on assets, 10 Industry classes and e timespan from 1970 to 2015 in the long format. I want to plot each of these time series and the (overall) mean. But the problem is, that the plot gets pretty chaotic. Therefore I thought to split it up into two or three subplots. I am using ggplot and managed to plot the time series, but I cant figure out how to do subplots in the right fashion.

```<code>df <- melt(sic_j[1:11], id.vars='time', variable.name='Industry')
> head(df, 20)
   time                       Industry     value
1  1970 Agriculture, Forestry, Fishing 0.4450458
2  1971 Agriculture, Forestry, Fishing 0.3834808
3  1972 Agriculture, Forestry, Fishing 0.3970010
4  1973 Agriculture, Forestry, Fishing 0.3993006
5  1974 Agriculture, Forestry, Fishing 0.3960956
6  1975 Agriculture, Forestry, Fishing 0.4052760
7  1976 Agriculture, Forestry, Fishing 0.3856735
8  1977 Agriculture, Forestry, Fishing 0.4062286
9  1978 Agriculture, Forestry, Fishing 0.3631151
10 1979 Agriculture, Forestry, Fishing 0.3987136
11 1980 Agriculture, Forestry, Fishing 0.3926147
12 1981 Agriculture, Forestry, Fishing 0.3207508
13 1982 Agriculture, Forestry, Fishing 0.3638654
14 1983 Agriculture, Forestry, Fishing 0.2901777
15 1984 Agriculture, Forestry, Fishing 0.3329089
16 1985 Agriculture, Forestry, Fishing 0.3384187
17 1986 Agriculture, Forestry, Fishing 0.3142270
18 1987 Agriculture, Forestry, Fishing 0.3610059
19 1988 Agriculture, Forestry, Fishing 0.2502937
20 1989 Agriculture, Forestry, Fishing 0.3156292

ggplot(df, aes(x=time, y=value))+
  geom_line(aes(group=Industry, color=Industry))+
  stat_summary(fun.y=mean, na.rm=T, group=11, alpha=1, color='red', size=1.5, geom='line')+
  theme_bw()+
  labs(x='year', y='gross profits on assets',
    color=NULL)+theme(legend.position = 'bottom')
</code>```

I tried the folowing with facet_grid:

```<code>ggplot(df, aes(x=time, y=value))+
  geom_line(aes(group=Industry, color=Industry))+
  stat_summary(fun.y=mean, na.rm=T, group=11, alpha=1, color='red', size=1.5, geom='line')+
  theme_bw()+
  labs(x='year', y='gross profits on assets',
    color=NULL)+theme(legend.position = 'bottom')+facet_grid(Industry~.)
</code>```

All I manage to get is the following, which obviously is useless:

I tried to split up the groups in order to have 3-4 industries per subplot, but I got this error:

```<code>Error in combine_vars(data, params$plot_env, vars, drop = params$drop) :
  At least one layer must contain all variables used for facetting
</code>```

In the end I would like to have a well-arranged plot of these 11 time series (10 industries and the mean). Since I already tried it with diffrent colors, linetypes and points, I think the best way are some subplots, but maybe someone has a better idea...?

答:
Consider that we have a data input as follow:

```<code>time <- 1970:2011
industry <- letters[1:10]

dat <- expand.grid(time=time, industry=industry)
dat$value <- rnorm(nrow(dat))
</code>```

The ggplot of this data would be similarly confusing as in the question:

```<code>ggplot(dat, aes(time, value, colour=industry)) +
    geom_line()
</code>```

One of the way to force a few plots into a single facet is by creating a new group. In this case, I'm grouping the first three listed industry as group_one, the next three as group_two and the remaining as group_three

```<code>library(tidyverse)
dat2 <- dat %>%
   mutate(group_one = ifelse(industry %in% letters[1:3], value, NA),
           group_two = ifelse(industry %in% letters[4:6], value, NA),
           group_three = ifelse(industry %in% letters[7:10], value, NA)) %>%
   gather(variable, new_val, group_one:group_three)
</code>```

The new plot with facet would now look slightly neater:

```<code>ggplot(dat2, aes(time, new_val, colour=industry)) + geom_line() +
    facet_wrap(~variable, ncol=1)
</code>```

Edit:

Overlaying additional line across all facet can be done with annotate function.

First, generate the summary table with mean value for each time point:

```<code>dat3 <- dat %>%
    group_by(time) %>%
    summarise(mean.value=mean(value))
</code>```

Adding the annotate to the ggplot above:

```<code>ggplot(dat2, aes(time, new_val, colour=industry)) +
  geom_line() +
  facet_wrap(~variable, ncol=1) +
  annotate(geom="line", x=dat3$time, y=dat3$mean.value,
           color='red', size=1.5)
</code>```

note that the additional table look at a little different due to the different seed used between the plots

Body:
I have a data frame with values for gross profits on assets, 10 Industry classes and e timespan from 1970 to 2015 in the long format. I want to plot each of these time series and the (overall) mean. But the problem is, that the plot gets pretty chaotic. Therefore I thought to split it up into two or three subplots. I am using ggplot and managed to plot the time series, but I cant figure out how to do subplots in the right fashion.

df <- melt(sic_j[1:11], id.vars='time', variable.name='Industry')
> head(df, 20)
   time                       Industry     value
1  1970 Agriculture, Forestry, Fishing 0.4450458
2  1971 Agriculture, Forestry, Fishing 0.3834808
3  1972 Agriculture, Forestry, Fishing 0.3970010
4  1973 Agriculture, Forestry, Fishing 0.3993006
5  1974 Agriculture, Forestry, Fishing 0.3960956
6  1975 Agriculture, Forestry, Fishing 0.4052760
7  1976 Agriculture, Forestry, Fishing 0.3856735
8  1977 Agriculture, Forestry, Fishing 0.4062286
9  1978 Agriculture, Forestry, Fishing 0.3631151
10 1979 Agriculture, Forestry, Fishing 0.3987136
11 1980 Agriculture, Forestry, Fishing 0.3926147
12 1981 Agriculture, Forestry, Fishing 0.3207508
13 1982 Agriculture, Forestry, Fishing 0.3638654
14 1983 Agriculture, Forestry, Fishing 0.2901777
15 1984 Agriculture, Forestry, Fishing 0.3329089
16 1985 Agriculture, Forestry, Fishing 0.3384187
17 1986 Agriculture, Forestry, Fishing 0.3142270
18 1987 Agriculture, Forestry, Fishing 0.3610059
19 1988 Agriculture, Forestry, Fishing 0.2502937
20 1989 Agriculture, Forestry, Fishing 0.3156292

ggplot(df, aes(x=time, y=value))+
  geom_line(aes(group=Industry, color=Industry))+
  stat_summary(fun.y=mean, na.rm=T, group=11, alpha=1, color='red', size=1.5, geom='line')+
  theme_bw()+
  labs(x='year', y='gross profits on assets',
    color=NULL)+theme(legend.position = 'bottom')

I tried the folowing with facet_grid:

ggplot(df, aes(x=time, y=value))+
  geom_line(aes(group=Industry, color=Industry))+
  stat_summary(fun.y=mean, na.rm=T, group=11, alpha=1, color='red', size=1.5, geom='line')+
  theme_bw()+
  labs(x='year', y='gross profits on assets',
    color=NULL)+theme(legend.position = 'bottom')+facet_grid(Industry~.)

All I manage to get is the following, which obviously is useless:

I tried to split up the groups in order to have 3-4 industries per subplot, but I got this error:

Error in combine_vars(data, params$plot_env, vars, drop = params$drop) :
  At least one layer must contain all variables used for facetting

In the end I would like to have a well-arranged plot of these 11 time series (10 industries and the mean). Since I already tried it with diffrent colors, linetypes and points, I think the best way are some subplots, but maybe someone has a better idea...?

Body:
Consider that we have a data input as follow:

time <- 1970:2011
industry <- letters[1:10]

dat <- expand.grid(time=time, industry=industry)
dat$value <- rnorm(nrow(dat))

The ggplot of this data would be similarly confusing as in the question:

ggplot(dat, aes(time, value, colour=industry)) +
    geom_line()

One of the way to force a few plots into a single facet is by creating a new group. In this case, I'm grouping the first three listed industry as group_one, the next three as group_two and the remaining as group_three

library(tidyverse)
dat2 <- dat %>%
   mutate(group_one = ifelse(industry %in% letters[1:3], value, NA),
           group_two = ifelse(industry %in% letters[4:6], value, NA),
           group_three = ifelse(industry %in% letters[7:10], value, NA)) %>%
   gather(variable, new_val, group_one:group_three)

The new plot with facet would now look slightly neater:

ggplot(dat2, aes(time, new_val, colour=industry)) + geom_line() +
    facet_wrap(~variable, ncol=1)

Edit:

Overlaying additional line across all facet can be done with annotate function.

First, generate the summary table with mean value for each time point:

dat3 <- dat %>%
    group_by(time) %>%
    summarise(mean.value=mean(value))

Adding the annotate to the ggplot above:

ggplot(dat2, aes(time, new_val, colour=industry)) +
  geom_line() +
  facet_wrap(~variable, ncol=1) +
  annotate(geom="line", x=dat3$time, y=dat3$mean.value,
           color='red', size=1.5)

note that the additional table look at a little different due to the different seed used between the plots


问:
Class based impersonation
Is it possible for a class to impersonate its identity? For example, Class A attempts to access Class B methods. Class B methods uses getClass().getName() to attempt to check Class A to ensure it is who it is. Can impersonation take place ? e.g. Class C impersonates Class A to get pass the getclass().getName() Class B uses for checks?

If Class B wants to implement getClass().getName() for checks effective on the sample method below, how do I implement it properly in the sample code below ?

```<code>public byte[] getStoragePrivateKey(String application) {
    if (application.getClass().getName().equals("correctClass") {
        // Allow access to Private Key.
    } else {
        // Access denied
    }
}
</code>```

The above example is a simulation of a plugin applet in the system trying to access an internal key server database in the system.

答:
You can do this with multiple classloaders. Each class laoder can have a class with the same name which is different.

However, I suggest you just use reflections if you can to by-pass this "security"

A simpler way to write the validation is

```<code>if (application.getClass() == CorrectClass.class) {
</code>```

An improved way to implement the validation is to use

```<code>StackTraceElement[] stes = Thread.currentThread().getStackTrace();
if (stes[0].getClassName().equals("correctClass") {
</code>```

This ensures the caller is from the correct class name.  It can still be spoofed with class loaders.

The sun.misc.Unsafe class uses something like the latter to protect the getUnsafe() method.  The standard work around is to do.

```<code>Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
theUnsafe.setAccessible(true);
Unsafe unafe = theUnsafe.get(null);
</code>```

If you are wondering why Unsafe is protected and why you might want to get access have a look at the method list. ;)

EDIT: Unsafe.getUnsafe() used to be protected but doesn't appear to be any more in the latest source. Possibly because the check could be easily bypassed. ??

Title: Class based impersonation

Body:
Is it possible for a class to impersonate its identity? For example, Class A attempts to access Class B methods. Class B methods uses getClass().getName() to attempt to check Class A to ensure it is who it is. Can impersonation take place ? e.g. Class C impersonates Class A to get pass the getclass().getName() Class B uses for checks?

If Class B wants to implement getClass().getName() for checks effective on the sample method below, how do I implement it properly in the sample code below ?

public byte[] getStoragePrivateKey(String application) {
    if (application.getClass().getName().equals("correctClass") {
        // Allow access to Private Key.
    } else {
        // Access denied
    }
}

The above example is a simulation of a plugin applet in the system trying to access an internal key server database in the system.

Body:
You can do this with multiple classloaders. Each class laoder can have a class with the same name which is different.

However, I suggest you just use reflections if you can to by-pass this "security"

A simpler way to write the validation is

if (application.getClass() == CorrectClass.class) {

An improved way to implement the validation is to use

StackTraceElement[] stes = Thread.currentThread().getStackTrace();
if (stes[0].getClassName().equals("correctClass") {

This ensures the caller is from the correct class name.  It can still be spoofed with class loaders.

The sun.misc.Unsafe class uses something like the latter to protect the getUnsafe() method.  The standard work around is to do.

Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
theUnsafe.setAccessible(true);
Unsafe unafe = theUnsafe.get(null);

If you are wondering why Unsafe is protected and why you might want to get access have a look at the method list. ;)

EDIT: Unsafe.getUnsafe() used to be protected but doesn't appear to be any more in the latest source. Possibly because the check could be easily bypassed. ??


问:
What is wrong with : Pattern pattern = Pattern.compile("\\");
I just want to use the regular expression to match the backslash (\) character, but it throws a PatternSyntaxException:

```<code>Exception in thread "main" java.util.regex.PatternSyntaxException: Unexpected internal error near index 1
\
 ^
    at java.util.regex.Pattern.error(Unknown Source)
    at java.util.regex.Pattern.compile(Unknown Source)
    at java.util.regex.Pattern.<init>(Unknown Source)
    at java.util.regex.Pattern.compile(Unknown Source)
    at helloworld.HelloWorld.main(HelloWorld.java:20)
</code>```

答:
You're just trying a regex using only the regex escape character \ (that's why is raised java.util.regex.PatternSyntaxException: Unexpected internal error near index 1 \)

Just to be clear, incidentally, the slash \ in Java is also the character used to identify the start of a escaped sequence (java escape characters) and has special meaning to the compiler. So if you want write a slash in a String you have to double it ("\\").

If you want write a regex that search a slash you must escape it, and translating the regex in a Java String you must double the slashes again.

So the regex for slash becomes "\\\\"

Body:
I just want to use the regular expression to match the backslash (\) character, but it throws a PatternSyntaxException:

Exception in thread "main" java.util.regex.PatternSyntaxException: Unexpected internal error near index 1
\
 ^
    at java.util.regex.Pattern.error(Unknown Source)
    at java.util.regex.Pattern.compile(Unknown Source)
    at java.util.regex.Pattern.<init>(Unknown Source)
    at java.util.regex.Pattern.compile(Unknown Source)
    at helloworld.HelloWorld.main(HelloWorld.java:20)


问:
how to remove content from images when using multipart
so I made an uploader in my web API by using multipart form data but the problem is when I save my pictures from the file stream it also gave me the content here

```<code> -----------------------------7e1e364095c
Content-Disposition: form-data; name="file"; filename="C:\Users\kewin\Downloads\windows 10 pro.jpg"
Content-Type: image/jpeg

 the binary starts from here
</code>```

and if i remove thoose 4 lines i can watch my picture so are there any way to remove that so I am only left with the picture

```<code>    public async Task<IHttpActionResult> UploadImage(string fileName = "")
    {
        if (fileName == "")
        {
            fileName = Guid.NewGuid().ToString();
        }
            if (!Request.Content.IsMimeMultipartContent("form-data"))
        {
            return BadRequest("Could not find file to upload");
        }
        var provider = await Request.Content.ReadAsMultipartAsync(new InMemoryMultipartFormDataStreamProvider());

        var files = provider.Files;
        var uploadedFile = files[0];
        var extension = ExtractExtension(uploadedFile);
        var contentType = uploadedFile.Headers.ContentType.ToString();
        var savePath = ConfigurationManager.AppSettings["savePath"];
        var file = string.Concat(savePath, fileName, extension);

        try
        {
            var request = HttpContext.Current.Request;
            var fileDir = file + request.Headers[""];
            using (var fs = new FileStream(fileDir, FileMode.Create))
            {
                request.InputStream.CopyTo(fs);
            }
            return Ok();
        }

        catch (StorageException e)
        {
            return BadRequest(e.Message);
        }

        try
        {
                var fileInfo = new UploadedFileInfo
            {
                FileName = fileName,
                FileExtension = extension,
                ContentType = contentType,
                FilePath = savePath + imageFile
            };
            return Ok(fileInfo);
        }
</code>```

答:
Currently you read picture data from request.InputStream, which contains whole unparsed multipart content, including headers you don't need. Instead, you should read picture data from InMemoryMultipartFormDataStreamProvider you created, which parses input stream and provides you simple access to headers and data stream of individual uploaded file(s).

```<code>....
var provider = await Request.Content.ReadAsMultipartAsync(new InMemoryMultipartFormDataStreamProvider());

var files = provider.Files;
var uploadedFile = files[0];
var extension = ExtractExtension(uploadedFile);
var contentType = uploadedFile.Headers.ContentType.ToString();
var savePath = ConfigurationManager.AppSettings["savePath"];
var file = string.Concat(savePath, fileName, extension);

try
{
    using (var fs = new FileStream(file, FileMode.Create))
    {
        await uploadedFile.CopyToAsync(fs);
    }
    return Ok();
}
....
</code>```

Body:
so I made an uploader in my web API by using multipart form data but the problem is when I save my pictures from the file stream it also gave me the content here

 -----------------------------7e1e364095c
Content-Disposition: form-data; name="file"; filename="C:\Users\kewin\Downloads\windows 10 pro.jpg"
Content-Type: image/jpeg

 the binary starts from here

and if i remove thoose 4 lines i can watch my picture so are there any way to remove that so I am only left with the picture

    public async Task<IHttpActionResult> UploadImage(string fileName = "")
    {
        if (fileName == "")
        {
            fileName = Guid.NewGuid().ToString();
        }
            if (!Request.Content.IsMimeMultipartContent("form-data"))
        {
            return BadRequest("Could not find file to upload");
        }
        var provider = await Request.Content.ReadAsMultipartAsync(new InMemoryMultipartFormDataStreamProvider());

        var files = provider.Files;
        var uploadedFile = files[0];
        var extension = ExtractExtension(uploadedFile);
        var contentType = uploadedFile.Headers.ContentType.ToString();
        var savePath = ConfigurationManager.AppSettings["savePath"];
        var file = string.Concat(savePath, fileName, extension);

        try
        {
            var request = HttpContext.Current.Request;
            var fileDir = file + request.Headers[""];
            using (var fs = new FileStream(fileDir, FileMode.Create))
            {
                request.InputStream.CopyTo(fs);
            }
            return Ok();
        }

        catch (StorageException e)
        {
            return BadRequest(e.Message);
        }

        try
        {
                var fileInfo = new UploadedFileInfo
            {
                FileName = fileName,
                FileExtension = extension,
                ContentType = contentType,
                FilePath = savePath + imageFile
            };
            return Ok(fileInfo);
        }

Body:
Currently you read picture data from request.InputStream, which contains whole unparsed multipart content, including headers you don't need. Instead, you should read picture data from InMemoryMultipartFormDataStreamProvider you created, which parses input stream and provides you simple access to headers and data stream of individual uploaded file(s).

....
var provider = await Request.Content.ReadAsMultipartAsync(new InMemoryMultipartFormDataStreamProvider());

var files = provider.Files;
var uploadedFile = files[0];
var extension = ExtractExtension(uploadedFile);
var contentType = uploadedFile.Headers.ContentType.ToString();
var savePath = ConfigurationManager.AppSettings["savePath"];
var file = string.Concat(savePath, fileName, extension);

try
{
    using (var fs = new FileStream(file, FileMode.Create))
    {
        await uploadedFile.CopyToAsync(fs);
    }
    return Ok();
}
....


问:
Why wont my email validation work? PHP
I have used

```<code>if (!preg_match('/[a-z||0-9]@[a-z||0-9].[a-z]/', $email)) {
    [PRINT ERROR]
}
</code>```

&

```<code>if (!eregi( "^[0-9]+$", $email)) {
    [PRINT ERROR]
}
</code>```

&

```<code>if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    [PRINT ERROR]
}
</code>```

I have also tried taking out the ! and make it work backwards but for some reason NONE of those work to find out if it is valid. Any ideas why?...
I have it in an else if statement, Im not sure if that could be the cause..

I am using PHP

答:
Try

```<code>'/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/'
</code>```

...

```<code>if (!preg_match('/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/', strtoupper($email))) {
    [PRINT ERROR]
}
</code>```

As far as I can see, none of your regex expressions would match an email.

Title: Why wont my email validation work? PHP

Body:
I have used

if (!preg_match('/[a-z||0-9]@[a-z||0-9].[a-z]/', $email)) {
    [PRINT ERROR]
}

&

if (!eregi( "^[0-9]+$", $email)) {
    [PRINT ERROR]
}

&

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    [PRINT ERROR]
}

I have also tried taking out the ! and make it work backwards but for some reason NONE of those work to find out if it is valid. Any ideas why?...
I have it in an else if statement, Im not sure if that could be the cause..

I am using PHP

Body:
Try

'/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/'

...

if (!preg_match('/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/', strtoupper($email))) {
    [PRINT ERROR]
}

As far as I can see, none of your regex expressions would match an email.