问:
Simplest way to fix variables spacing? [php]
I'm trying to create a very basic multiplication table without the actual table element, but not sure how to space the numbers correctly (without using css or an html table!). What's the simplest way to do this?

<?php

  for ($i=1; $i < 11 ; $i++) {

    for ($x=1; $x< 11 ; $x++) {
      echo  $i*$x . " ";
    }
    echo "
";
  }

 ?>```

答:
if the problem is, that the numbers do not fit in the "columns" than that could help. It prints spaces after the numbers so that you always have 3 digits/characters.

```<code><?php

  for ($i=1; $i < 11 ; $i++) {

    for ($x=1; $x< 11 ; $x++) {
      echo  $i*$x;
      for($y=0; $y < 3-strlen((string)$i*$y)) { echo " "; }
    }
    echo "<br>";
  }
?>
</code>```

But to use table Tags would be the best way.

Body:
if the problem is, that the numbers do not fit in the "columns" than that could help. It prints spaces after the numbers so that you always have 3 digits/characters.

<?php

  for ($i=1; $i < 11 ; $i++) {

    for ($x=1; $x< 11 ; $x++) {
      echo  $i*$x;
      for($y=0; $y < 3-strlen((string)$i*$y)) { echo " "; }
    }
    echo "<br>";
  }
?>

But to use table Tags would be the best way.


来源: stackexchange

问:
insert pdo query issue, multiple inserts in wrong table
Have this process to insert data into two tables and is working just fine, but the problem is if i select 3 images for uploading and query them into db and when i submit my form i see 3 queries insertions in db and has to be one in table tours and 3 insertions with same id from tours: in table poze_articol for images path with same id from tours at row (pid).. something is wrong here

Php code:

```<code>         <?php
        $servername = "";
        $username = "";
        $password = "";
        $dbname = "";
         // Create connection
        $conn = new mysqli($servername, $username, $password, $dbname);
        // Check connection

        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        }
        if(isset($_POST['addtour']))
        {

       #### START FROM HERE I THINK IS THE PROBLEM ###
        define ("MAX_SIZE","9000");
        function getExtension($str)
        {
                 $i = strrpos($str,".");
                 if (!$i) { return ""; }
                 $l = strlen($str) - $i;
                 $ext = substr($str,$i+1,$l);
                 return $ext;
        }
        $valid_formats = array("jpg", "png", "bmp","jpeg");

            $uploaddir = "../../../img/carousel/"; //image upload directory
            foreach ($_FILES['photos']['name'] as $name => $value)
            {

                $filename = stripslashes($_FILES['photos']['name'][$name]);
                $size=filesize($_FILES['photos']['tmp_name'][$name]);
                //get the extension of the file in a lower case format
                  $ext = getExtension($filename);
                  $ext = strtolower($ext);

                 if(in_array($ext,$valid_formats))
                 {
                   if ($size < (MAX_SIZE*1024))
                   {
                   $image_name=time().$filename;

                   $newname=$uploaddir.$image_name;

                   if (move_uploaded_file($_FILES['photos']['tmp_name'][$name], $newname))
                   {

         $sql2  = "INSERT INTO tours (titlu,durata,descriere,pret,ribbon,titlu_slider,desc_slider,descriere_box,titlu_box1,desc_box1,titlu_box2,desc_box2,titlu_box3,desc_box3,titlu_box4,desc_box4) VALUES (
         '".$_POST["oras_caseta"]."',
         '".$_POST["durata_caseta"]."',
         '".$_POST["descriere_caseta"]."',
         '".$_POST["pret_caseta"]."',
         '".$_POST["icon_caseta"]."',
         '".$_POST["titlu_slider"]."',
         '".$_POST["descriere_slider"]."',
         '".$_POST["descriere_overview"]."',
         '".$_POST["titlu_box1"]."',
         '".$_POST["desc_box1"]."',
         '".$_POST["titlu_box2"]."',
         '".$_POST["desc_box2"]."',
         '".$_POST["titlu_box3"]."',
         '".$_POST["desc_box3"]."',
         '".$_POST["titlu_box4"]."',
         '".$_POST["desc_box4"]."')";

        if ($conn->query($sql2) === TRUE) {
            $last_id = $conn->insert_id;

            echo '<div class="alert alert-success" role="alert">
          <strong>Bravo!</strong> Ai adaugat cu succes un traseu pe site.
        </div>';
        } else {
            echo "Error: " . $sql . "<br>" . $conn->error;
        }
        $sql = "INSERT INTO poze_articol (poza_articol,pid) VALUES ('img/carousel/$image_name','$last_id')";

        if ($conn->query($sql) === TRUE) {}
             }
          }
       }
    }
 }
  $conn->close();
        ?>
</code>```

答:
If I well understood you, You want create number of files field in poze_articol all of this poze_articol field has id of the tour field...

If it is,

So firstly, All of your database insertion are in foreach loop scope, in other words, the portion of code inside foreach loop will be executed x times that the loop iterate. ( n times he has item on $_FILES['photos']['name'] your case).

To resolve the problem,
I suggere you to firstly create tour field outside foreach !

```<code>        $sql2  = "INSERT INTO tours (titlu,durata,descriere,pret,ribbon,titlu_slider,desc_slider,descriere_box,titlu_box1,desc_box1,titlu_box2,desc_box2,titlu_box3,desc_box3,titlu_box4,desc_box4) VALUES (
     '".$_POST["oras_caseta"]."',
     '".$_POST["durata_caseta"]."',
     '".$_POST["descriere_caseta"]."',
     '".$_POST["pret_caseta"]."',
     '".$_POST["icon_caseta"]."',
     '".$_POST["titlu_slider"]."',
     '".$_POST["descriere_slider"]."',
     '".$_POST["descriere_overview"]."',
     '".$_POST["titlu_box1"]."',
     '".$_POST["desc_box1"]."',
     '".$_POST["titlu_box2"]."',
     '".$_POST["desc_box2"]."',
     '".$_POST["titlu_box3"]."',
     '".$_POST["desc_box3"]."',
     '".$_POST["titlu_box4"]."',
     '".$_POST["desc_box4"]."')";

    if ($conn->query($sql2) === TRUE) {
        $last_id = $conn->insert_id;

        echo '<div class="alert alert-success" role="alert">
      <strong>Bravo!</strong> Ai adaugat cu succes un traseu pe site.
    </div>';
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
</code>```

Because you want be sure that all file will be save both on local disk and database, You can use transaction to assure the integrity.

Juste after tour field is created, You can do your loop

```<code>foreach ($_FILES['photos']['name'] as $name => $value)
        {

            $filename = stripslashes($_FILES['photos']['name'][$name]);
            $size=filesize($_FILES['photos']['tmp_name'][$name]);
            //get the extension of the file in a lower case format
              $ext = getExtension($filename);
              $ext = strtolower($ext);

             if(in_array($ext,$valid_formats))
             {
               if ($size < (MAX_SIZE*1024))
               {
               $image_name=time().$filename;

               $newname=$uploaddir.$image_name;

               if (move_uploaded_file($_FILES['photos']['tmp_name'][$name], $newname)) {

    $sql = "INSERT INTO poze_articol (poza_articol,pid) VALUES ('img/carousel/$image_name','$last_id')";

    if ($conn->query($sql) === TRUE) {}
         }
      }
   }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Have this process to insert data into two tables and is working just fine, but the problem is if i select 3 images for uploading and query them into db and when i submit my form i see 3 queries insertions in db and has to be one in table tours and 3 insertions with same id from tours: in table poze_articol for images path with same id from tours at row (pid).. something is wrong here

Php code:

         <?php
        $servername = "";
        $username = "";
        $password = "";
        $dbname = "";
         // Create connection
        $conn = new mysqli($servername, $username, $password, $dbname);
        // Check connection

        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        }
        if(isset($_POST['addtour']))
        {

       #### START FROM HERE I THINK IS THE PROBLEM ###
        define ("MAX_SIZE","9000");
        function getExtension($str)
        {
                 $i = strrpos($str,".");
                 if (!$i) { return ""; }
                 $l = strlen($str) - $i;
                 $ext = substr($str,$i+1,$l);
                 return $ext;
        }
        $valid_formats = array("jpg", "png", "bmp","jpeg");

            $uploaddir = "../../../img/carousel/"; //image upload directory
            foreach ($_FILES['photos']['name'] as $name => $value)
            {

                $filename = stripslashes($_FILES['photos']['name'][$name]);
                $size=filesize($_FILES['photos']['tmp_name'][$name]);
                //get the extension of the file in a lower case format
                  $ext = getExtension($filename);
                  $ext = strtolower($ext);

                 if(in_array($ext,$valid_formats))
                 {
                   if ($size < (MAX_SIZE*1024))
                   {
                   $image_name=time().$filename;

                   $newname=$uploaddir.$image_name;

                   if (move_uploaded_file($_FILES['photos']['tmp_name'][$name], $newname))
                   {

         $sql2  = "INSERT INTO tours (titlu,durata,descriere,pret,ribbon,titlu_slider,desc_slider,descriere_box,titlu_box1,desc_box1,titlu_box2,desc_box2,titlu_box3,desc_box3,titlu_box4,desc_box4) VALUES (
         '".$_POST["oras_caseta"]."',
         '".$_POST["durata_caseta"]."',
         '".$_POST["descriere_caseta"]."',
         '".$_POST["pret_caseta"]."',
         '".$_POST["icon_caseta"]."',
         '".$_POST["titlu_slider"]."',
         '".$_POST["descriere_slider"]."',
         '".$_POST["descriere_overview"]."',
         '".$_POST["titlu_box1"]."',
         '".$_POST["desc_box1"]."',
         '".$_POST["titlu_box2"]."',
         '".$_POST["desc_box2"]."',
         '".$_POST["titlu_box3"]."',
         '".$_POST["desc_box3"]."',
         '".$_POST["titlu_box4"]."',
         '".$_POST["desc_box4"]."')";

        if ($conn->query($sql2) === TRUE) {
            $last_id = $conn->insert_id;

            echo '

          Bravo! Ai adaugat cu succes un traseu pe site.

';
        } else {
            echo "Error: " . $sql . "
" . $conn->error;
        }
        $sql = "INSERT INTO poze_articol (poza_articol,pid) VALUES ('img/carousel/$image_name','$last_id')";

        if ($conn->query($sql) === TRUE) {}
             }
          }
       }
    }
 }
  $conn->close();
        ?>

Body:
If I well understood you, You want create number of files field in poze_articol all of this poze_articol field has id of the tour field...

If it is,

So firstly, All of your database insertion are in foreach loop scope, in other words, the portion of code inside foreach loop will be executed x times that the loop iterate. ( n times he has item on $_FILES['photos']['name'] your case).

To resolve the problem,
I suggere you to firstly create tour field outside foreach !

        $sql2  = "INSERT INTO tours (titlu,durata,descriere,pret,ribbon,titlu_slider,desc_slider,descriere_box,titlu_box1,desc_box1,titlu_box2,desc_box2,titlu_box3,desc_box3,titlu_box4,desc_box4) VALUES (
     '".$_POST["oras_caseta"]."',
     '".$_POST["durata_caseta"]."',
     '".$_POST["descriere_caseta"]."',
     '".$_POST["pret_caseta"]."',
     '".$_POST["icon_caseta"]."',
     '".$_POST["titlu_slider"]."',
     '".$_POST["descriere_slider"]."',
     '".$_POST["descriere_overview"]."',
     '".$_POST["titlu_box1"]."',
     '".$_POST["desc_box1"]."',
     '".$_POST["titlu_box2"]."',
     '".$_POST["desc_box2"]."',
     '".$_POST["titlu_box3"]."',
     '".$_POST["desc_box3"]."',
     '".$_POST["titlu_box4"]."',
     '".$_POST["desc_box4"]."')";

    if ($conn->query($sql2) === TRUE) {
        $last_id = $conn->insert_id;

        echo '<div class="alert alert-success" role="alert">
      <strong>Bravo!</strong> Ai adaugat cu succes un traseu pe site.
    </div>';
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }

Because you want be sure that all file will be save both on local disk and database, You can use transaction to assure the integrity.

Juste after tour field is created, You can do your loop

foreach ($_FILES['photos']['name'] as $name => $value)
        {

            $filename = stripslashes($_FILES['photos']['name'][$name]);
            $size=filesize($_FILES['photos']['tmp_name'][$name]);
            //get the extension of the file in a lower case format
              $ext = getExtension($filename);
              $ext = strtolower($ext);

             if(in_array($ext,$valid_formats))
             {
               if ($size < (MAX_SIZE*1024))
               {
               $image_name=time().$filename;

               $newname=$uploaddir.$image_name;

               if (move_uploaded_file($_FILES['photos']['tmp_name'][$name], $newname)) {

    $sql = "INSERT INTO poze_articol (poza_articol,pid) VALUES ('img/carousel/$image_name','$last_id')";

    if ($conn->query($sql) === TRUE) {}
         }
      }
   }
}


问:
does inserting javascript code at the beginning of the body affect SEO?

is there any concern of adding javascript code at the very beginning of opening tag of body?

does it affect SEO??

Thanks for your help

答: It depends which script, it is recommended to put it at the end to increase load times, but if it is a "low weight" script and it is important to you you can put it on the top and check the load time , if you are still in the "green" area then it is OK. If your site will take 0.5 sec longer to load it will not crash all your SEO efforts.</p>

ContentLicense: CC BY-SA 2.5


问:
SignalR ERR_CONECTION_REFUSED on signalr/hubs
Have changed computer to run my project and website on, and now it doesn't work at all.

When I go to http://localhost:8080/signalr/hubs I get "ERR_CONNECTION_REFUSED"

In my Self-Hosted aplikation:

```<code>string url = "http://*:8080";
using (WebApp.Start(url))
 {
     writeStatus("Server running on " + url);
 }
</code>```

And on my website:

```<code><script src="http://localhost:8080/signalr/hubs"></script>
</code>```

What have i missed?

答:
Try this-->CorsOptions.AllowAll;            </p>

```<code>        app.UseCors(CorsOptions.AllowAll);
        var hubConfiguration = new HubConfiguration() ;
        hubConfiguration.EnableDetailedErrors = true;

        app.MapSignalR(hubConfiguration);
</code>```

Body:
Have changed computer to run my project and website on, and now it doesn't work at all.

When I go to http://localhost:8080/signalr/hubs I get "ERR_CONNECTION_REFUSED"

In my Self-Hosted aplikation:

string url = "http://*:8080";
using (WebApp.Start(url))
 {
     writeStatus("Server running on " + url);
 }

And on my website:

What have i missed?

Body:
Try this-->CorsOptions.AllowAll;

        app.UseCors(CorsOptions.AllowAll);
        var hubConfiguration = new HubConfiguration() ;
        hubConfiguration.EnableDetailedErrors = true;

        app.MapSignalR(hubConfiguration);


问:
Html dom add class to all elements
I'm trying to addclass to all elements at once using html dom. // No jquery

Here is what i tryed:

```<code>document.getElementsByTagName("*").classList.add('addedclassname');
</code>```

I guess i could not select(get) all elements. Because this,

```<code>document.getElementById("id").classList.add('addedclassname');
</code>```

was working.

答:
function addClass(){
document.getElementsByTagName("*")[0].setAttribute("class", "demo")
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.demo {
    color: red;
}</code>```

this is h1 element

hello this is p element

this is h2 element

<button onclick='addClass()'>add class</button>```

Title: Html dom add class to all elements

Body:
I'm trying to addclass to all elements at once using html dom. // No jquery

Here is what i tryed:

document.getElementsByTagName("*").classList.add('addedclassname');

I guess i could not select(get) all elements. Because this,

document.getElementById("id").classList.add('addedclassname');

was working.

Body:
function addClass(){
document.getElementsByTagName("*")[0].setAttribute("class", "demo")
}

.demo {
    color: red;
}

<h1>this is h1 element</h1>
<p>hello this is p element</p>
<h2>this is h2 element</h2>
<button onclick='addClass()'>add class</button>


问:
Get GIT HEAD remote
I'm kinda new to Git and I have to compare the HEAD from a lokal branch with a remote branch.

On the lokal branch I get the HEAD with the following command:

```<code>git rev-parse --short HEAD

root@debian:xxxx# git rev-parse --short HEAD
469xxx
</code>```

But how can I get the short HEAD of a remote branch?
For Example:

```<code>https://github.com/openssl/openssl
</code>```

The lastest short HEAD is there "cded951"

In my case, getting the HEAD and comparing it does it.

```<code>If local HEAD != remote HEAD do xyz
</code>```

For this check I need the remote HEAD of my github branch.

best regards :)

Solution:

```<code>git remote update
if ! git diff --quiet origin/master; then
    echo "the branch is different!"
else
    echo "the branch is equal!"
fi
</code>```

答:
To check if your local branch differs from the associated remote tracking branch (assuming you are on the master branch):

```<code>git remote update
if ! git diff --quiet origin/master; then
    echo "the branch is different!"
fi
</code>```

You could also write instead:

```<code>git diff --quiet @{u}
</code>```

Where @{u} refers to the remote tracking branch, so this would work for any local branch that is tracking a remote branch.

Title: Get GIT HEAD remote

Body:
I'm kinda new to Git and I have to compare the HEAD from a lokal branch with a remote branch.

On the lokal branch I get the HEAD with the following command:

git rev-parse --short HEAD

root@debian:xxxx# git rev-parse --short HEAD
469xxx

But how can I get the short HEAD of a remote branch?
For Example:

https://github.com/openssl/openssl

The lastest short HEAD is there "cded951"

In my case, getting the HEAD and comparing it does it.

If local HEAD != remote HEAD do xyz

For this check I need the remote HEAD of my github branch.

best regards :)

Solution:

git remote update
if ! git diff --quiet origin/master; then
    echo "the branch is different!"
else
    echo "the branch is equal!"
fi

Body:
To check if your local branch differs from the associated remote tracking branch (assuming you are on the master branch):

git remote update
if ! git diff --quiet origin/master; then
    echo "the branch is different!"
fi

You could also write instead:

git diff --quiet @{u}

Where @{u} refers to the remote tracking branch, so this would work for any local branch that is tracking a remote branch.


问:
Communication with GPRS module using C#, with TCP
I have searched a lot for this but could not find any specific answer that applies to my case. I have made device using GPS module and GSM/GPRS module with Arduino Mega 2560, and it sends me the location through SMS. Now I want to get the location parameters using GPRS. I have in mind to use TCP. I will send data through AT Commands from GPRS module, but I am confused on how to make a server on C#. I know that I would be needing a static/public IP for this. But I don't know how to get the public IP, and start receiving data which I send from GPRS module. Please please I need help because I am a beginner in Client/Server programming, and I am working on my final year project. Many thanks in advance!</p>

答:
Here is the Server Code:</p>

```<code>class Server
{
    TcpListener server = null;
    public Server(string ip, int port)
    {
        IPAddress localAddr = IPAddress.Parse(ip);
        server = new TcpListener(localAddr, port);
        server.Start();
        StartListener();
    }

    public void StartListener()
    {
        try
        {
            while (true)
            {
                Console.WriteLine("Waiting for a connection... ");
                TcpClient client = server.AcceptTcpClient();
                Console.WriteLine("Connected!");

                Thread t = new Thread(new ParameterizedThreadStart(HandleDeivce));
                t.Start(client);
            }
        }
        catch (SocketException e)
        {
            Console.WriteLine("SocketException: {0}", e);
        }
    }

    public void HandleDeivce(Object obj)
    {
        TcpClient client = (TcpClient)obj;
        NetworkStream stream = client.GetStream();

        string data = null;
        Byte[] bytes = new Byte[256];
        int i;

        while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
        {
            data = Encoding.ASCII.GetString(bytes, 0, i);
            Console.WriteLine("{1}: Received: {0}", data, Thread.CurrentThread.ManagedThreadId);

            if (data.StartsWith("##"))
            {
                data = "LOAD";
            }
            else
            {
                data = "ON";
            }

            byte[] msg = Encoding.ASCII.GetBytes(data);
            stream.Write(msg, 0, msg.Length);

            Console.WriteLine("{1}: Sent: {0}", data, Thread.CurrentThread.ManagedThreadId);
        }
        client.Close();
    }
}
</code>```

Body:
Here is the Server Code:

class Server
{
    TcpListener server = null;
    public Server(string ip, int port)
    {
        IPAddress localAddr = IPAddress.Parse(ip);
        server = new TcpListener(localAddr, port);
        server.Start();
        StartListener();
    }

    public void StartListener()
    {
        try
        {
            while (true)
            {
                Console.WriteLine("Waiting for a connection... ");
                TcpClient client = server.AcceptTcpClient();
                Console.WriteLine("Connected!");

                Thread t = new Thread(new ParameterizedThreadStart(HandleDeivce));
                t.Start(client);
            }
        }
        catch (SocketException e)
        {
            Console.WriteLine("SocketException: {0}", e);
        }
    }

    public void HandleDeivce(Object obj)
    {
        TcpClient client = (TcpClient)obj;
        NetworkStream stream = client.GetStream();

        string data = null;
        Byte[] bytes = new Byte[256];
        int i;

        while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
        {
            data = Encoding.ASCII.GetString(bytes, 0, i);
            Console.WriteLine("{1}: Received: {0}", data, Thread.CurrentThread.ManagedThreadId);

            if (data.StartsWith("##"))
            {
                data = "LOAD";
            }
            else
            {
                data = "ON";
            }

            byte[] msg = Encoding.ASCII.GetBytes(data);
            stream.Write(msg, 0, msg.Length);

            Console.WriteLine("{1}: Sent: {0}", data, Thread.CurrentThread.ManagedThreadId);
        }
        client.Close();
    }
}


问:
Read excel (xlsx) file in java using Apoche POI (getting weird numbers)
I have to open a testdate for a schoolproject. This testdate is a excel(xlsx) file that includes number, letter, date and time. But with the code below it reads the excel file, but i get weird numbers like 42538.0 and 1.153481443E9. after date.

```<code>public class Page4_Controller implements Initializable {

    @FXML
    private Button button1;

    public void Button1Action(ActionEvent event) throws IOException {
        //Initialize excel file
        FileChooser fc = new FileChooser();
        fc.getExtensionFilters().addAll(
                new ExtensionFilter("Excel Files", "*.xlsx"));
        File selectedFile = fc.showOpenDialog(null);

        // Read file
        readXLSXFile(selectedFile.getAbsolutePath());
    }

    public static void readXLSXFile(String excelFilePath) throws IOException {
        FileInputStream fys = new FileInputStream(new File(excelFilePath));

        //Create workbook instance that refers to .xlsx file
        XSSFWorkbook wb = new XSSFWorkbook(fys);

        //Create a sheet object to retrive the sheet
        XSSFSheet sheet = wb.getSheetAt(0);

        //That is for evalueate the cell type
        FormulaEvaluator forlulaEvaluator = wb.getCreationHelper().createFormulaEvaluator();
        DataFormatter df = new DataFormatter();

        //Default data for database (comes later)
        //String airport = sheet.getRow(1).getCell(1).getStringCellValue();
        //Date date = sheet.getRow(2).getCell(1).getDateCellValue();

        for (Row row : sheet) {
            for (Cell cell : row) {
                switch (forlulaEvaluator.evaluateInCell(cell).getCellType()) {
                    //If cell is a numeric format
                    case Cell.CELL_TYPE_NUMERIC:
                        System.out.print(cell.getNumericCellValue() + "\t");
                        System.out.print(df.formatCellValue(cell) + "\t");
                        break;
                    //If cell is a string format
                    case Cell.CELL_TYPE_STRING:
                        System.out.print(cell.getRichStringCellValue() + "\t");
                        break;
                }

            }
            System.out.println();
        }
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
    }

}
</code>```

答:
Dates are stored internally in Excel as double values and DataFormatter.formatCellValue(Cell cell) returns the formatted value of a cell as a String regardless of the cell type. So when you call df.formatCellValue(cell) you are returning as a string the double value of the cell.

To print the cell value as a date the code is this:

```<code>switch (cell.getCellType()) {
    // ...
    case CellType.NUMERIC:
        // Check if a cell contains a date. Since dates are stored internally in Excel as double values we infer it is a date if it is formatted as such.
        if (DateUtil.isCellDateFormatted(cell)) {
            // Get the value of the cell as a date. Returns a java.util.Date.
            System.out.println(cell.getDateCellValue());
        } else {
            System.out.println(cell.getNumericCellValue());
        }
    // ...
}
</code>```

Source:

https://poi.apache.org/spreadsheet/quick-guide.html#CellContents

https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/DataFormatter.html

https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Cell.html

https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/DateUtil.html

EDIT

Excel cells containing only time have their date part fixed to 31 december 1899. You can use this information to check if a cell is time or date: extract the year, if it is 1899 it is a time cell.

```<code>SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy");
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");

switch (cell.getCellType()) {

  case CellType.NUMERIC:
    if (DateUtil.isCellDateFormatted(cell)) {
        Date dateCellValue = cell.getDateCellValue();
        String year = yearFormat.format(dateCellValue);
        if (year.equals("1899"))
          System.out.println(timeFormat.format(dateCellValue));
        else
          System.out.println(dateFormat.format(dateCellValue));
    } else {
        System.out.println(cell.getNumericCellValue());
    }

}
</code>```

Body:
I have to open a testdate for a schoolproject. This testdate is a excel(xlsx) file that includes number, letter, date and time. But with the code below it reads the excel file, but i get weird numbers like 42538.0 and 1.153481443E9. after date.

public class Page4_Controller implements Initializable {

    @FXML
    private Button button1;

    public void Button1Action(ActionEvent event) throws IOException {
        //Initialize excel file
        FileChooser fc = new FileChooser();
        fc.getExtensionFilters().addAll(
                new ExtensionFilter("Excel Files", "*.xlsx"));
        File selectedFile = fc.showOpenDialog(null);

        // Read file
        readXLSXFile(selectedFile.getAbsolutePath());
    }

    public static void readXLSXFile(String excelFilePath) throws IOException {
        FileInputStream fys = new FileInputStream(new File(excelFilePath));

        //Create workbook instance that refers to .xlsx file
        XSSFWorkbook wb = new XSSFWorkbook(fys);

        //Create a sheet object to retrive the sheet
        XSSFSheet sheet = wb.getSheetAt(0);

        //That is for evalueate the cell type
        FormulaEvaluator forlulaEvaluator = wb.getCreationHelper().createFormulaEvaluator();
        DataFormatter df = new DataFormatter();

        //Default data for database (comes later)
        //String airport = sheet.getRow(1).getCell(1).getStringCellValue();
        //Date date = sheet.getRow(2).getCell(1).getDateCellValue();

        for (Row row : sheet) {
            for (Cell cell : row) {
                switch (forlulaEvaluator.evaluateInCell(cell).getCellType()) {
                    //If cell is a numeric format
                    case Cell.CELL_TYPE_NUMERIC:
                        System.out.print(cell.getNumericCellValue() + "\t");
                        System.out.print(df.formatCellValue(cell) + "\t");
                        break;
                    //If cell is a string format
                    case Cell.CELL_TYPE_STRING:
                        System.out.print(cell.getRichStringCellValue() + "\t");
                        break;
                }

            }
            System.out.println();
        }
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
    }

}

Body:
Dates are stored internally in Excel as double values and DataFormatter.formatCellValue(Cell cell) returns the formatted value of a cell as a String regardless of the cell type. So when you call df.formatCellValue(cell) you are returning as a string the double value of the cell.

To print the cell value as a date the code is this:

switch (cell.getCellType()) {
    // ...
    case CellType.NUMERIC:
        // Check if a cell contains a date. Since dates are stored internally in Excel as double values we infer it is a date if it is formatted as such.
        if (DateUtil.isCellDateFormatted(cell)) {
            // Get the value of the cell as a date. Returns a java.util.Date.
            System.out.println(cell.getDateCellValue());
        } else {
            System.out.println(cell.getNumericCellValue());
        }
    // ...
}

Source:

https://poi.apache.org/spreadsheet/quick-guide.html#CellContents

https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/DataFormatter.html

https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Cell.html

https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/DateUtil.html

EDIT

Excel cells containing only time have their date part fixed to 31 december 1899. You can use this information to check if a cell is time or date: extract the year, if it is 1899 it is a time cell.

SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy");
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");

switch (cell.getCellType()) {

  case CellType.NUMERIC:
    if (DateUtil.isCellDateFormatted(cell)) {
        Date dateCellValue = cell.getDateCellValue();
        String year = yearFormat.format(dateCellValue);
        if (year.equals("1899"))
          System.out.println(timeFormat.format(dateCellValue));
        else
          System.out.println(dateFormat.format(dateCellValue));
    } else {
        System.out.println(cell.getNumericCellValue());
    }

}


问:
fermi cuda double precision against C
there is a small error between CPU and GPU double precision results, using a fermi GPU.

e.g. for a small test set, I get the following absolute error for: (Number 1(CPU)  - Number 2(GPU))  =    3E-018.

in binary form it is as expected very small…

NUMBER 1 in binary:

xxxxxxxxxxxxx11100000001001

vs

NUMBER 2 in binary:

xxxxxxxxxxxx111100000001010

Although this is a difference of one binary digit, I am keen to eliminate any differences, as the errors addup during my code.

any tips from those familiar with fermi? if this is unavoidable can I get C/C++ to mimic the fermi rounding off behaviour?

答:
You should take a look at this post.

Floating point is not associative, so if a compiler chooses to do operations in a different order then you'll get a different result. Two versions of the same compiler can produce differences! Different compilers are even more likely to produce differences, and if you're doing work in parallel on the GPU (you are, right?) then you're inherently doing operations in a different order...

Fermi hardware is IEEE754-2008 compliant, which means that in addition to IEEE754 standard rounding it also has the fused multiply-add (FMA) instruction which avoids losing precision between multiplication and addition.

Title: fermi cuda double precision against C


问:
sqlite update works only once at first then fails
I've got a method that is supposed to update a row in a table
but it only works once and then when I want to update the second row or other rows it doesn't work...

here's the update method:

```<code>@Override
public boolean updateRelayItemStatus(int deviceId, String itemDefaultName, int status) {
    LogClass.logD("start updating '"+itemDefaultName+"'");

    SQLiteDatabase sql = db.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(Database.R_STATUS, status);

    long responseId = sql.update(Database.TABLE_RELAYS, contentValues, Database.R_ID + " =? AND " + Database.R_DEFAULT_NAME + " =?", new String[]{String.valueOf(deviceId), itemDefaultName});

    sql.close();
    LogClass.logD("update relay row for '" + itemDefaultName + "' " +
            " -  '"+deviceId+"' " +
            " -  '"+status+"'  =======   " + (responseId > 0 ? "succeed" : "failed"));
    return responseId > 0;
}
</code>```

and this is the table:

```<code>private final String CREATE_RELAYS = "CREATE TABLE " + TABLE_RELAYS + "("
            + R_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
            + R_DEVICE_ID + " TEXT, "
            + R_DEFAULT_NAME + " TEXT,"
            + R_CUSTOM_NAME + " TEXT,"
            + R_ICON + " INTEGER,"
            + R_TIME + " INTEGER,"
            + R_STATUS + " INTEGER);";
</code>```

答:
I found the problem... i have two Id in my table
one of them is simply the unique Id and the other is id of device from another table and for updating i need device id but I had used the other id that's what was causing the problem</p>

Body:
I've got a method that is supposed to update a row in a table
but it only works once and then when I want to update the second row or other rows it doesn't work...

here's the update method:

@Override
public boolean updateRelayItemStatus(int deviceId, String itemDefaultName, int status) {
    LogClass.logD("start updating '"+itemDefaultName+"'");

    SQLiteDatabase sql = db.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(Database.R_STATUS, status);

    long responseId = sql.update(Database.TABLE_RELAYS, contentValues, Database.R_ID + " =? AND " + Database.R_DEFAULT_NAME + " =?", new String[]{String.valueOf(deviceId), itemDefaultName});

    sql.close();
    LogClass.logD("update relay row for '" + itemDefaultName + "' " +
            " -  '"+deviceId+"' " +
            " -  '"+status+"'  =======   " + (responseId > 0 ? "succeed" : "failed"));
    return responseId > 0;
}

and this is the table:

private final String CREATE_RELAYS = "CREATE TABLE " + TABLE_RELAYS + "("
            + R_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
            + R_DEVICE_ID + " TEXT, "
            + R_DEFAULT_NAME + " TEXT,"
            + R_CUSTOM_NAME + " TEXT,"
            + R_ICON + " INTEGER,"
            + R_TIME + " INTEGER,"
            + R_STATUS + " INTEGER);";


问:
Mockito with functions in Dart
I have a method that I would like to mock, however when I am trying to verify calls of this method. I get an error that says:

```<code>Used on a non-mockito object
</code>```

Here is the simplified code:

```<code>test('test',() {
  MockReducer reducer = new MockReducer();
  verify(reducer).called(0);
});

class MockReducer extends Mock {
  call(state, action) => state;
}
</code>```

Why can't I do something like this?

答:
I think you have three problems here:

Mockito only works with Classes, not functions (see https://github.com/dart-lang/mockito/issues/62). You have some options: create a test implementation of the function, or for redux.dart, you can implement the ReducerClass (which acts as a Reducer function by implementing call).

You need to verify methods being called, not the whole Mock class.

You must use verifyNever instead of verify(X).called(0).

Working example:

```<code>class MockReducer extends Mock implements ReducerClass {}

main() {
  test('should be able to mock a reducer', () {
    final reducer = new MockReducer();

    verifyNever(reducer.call(any, any));
  });
}
</code>```

Title: Mockito with functions in Dart

Body:
I have a method that I would like to mock, however when I am trying to verify calls of this method. I get an error that says:

Used on a non-mockito object

Here is the simplified code:

test('test',() {
  MockReducer reducer = new MockReducer();
  verify(reducer).called(0);
});

class MockReducer extends Mock {
  call(state, action) => state;
}

Why can't I do something like this?

Body:
I think you have three problems here:

Mockito only works with Classes, not functions (see https://github.com/dart-lang/mockito/issues/62). You have some options: create a test implementation of the function, or for redux.dart, you can implement the ReducerClass (which acts as a Reducer function by implementing call).

You need to verify methods being called, not the whole Mock class.

You must use verifyNever instead of verify(X).called(0).

Working example:

class MockReducer extends Mock implements ReducerClass {}

main() {
  test('should be able to mock a reducer', () {
    final reducer = new MockReducer();

    verifyNever(reducer.call(any, any));
  });
}


问:
net core app fails to access azure key vault
I am trying to use Azure key vault to store some secrets.  Following this tutorial:
https://learn.microsoft.com/en-us/azure/key-vault/vs-secure-secret-appsettings

works while debugging, but when I publish the app to Azure, it fails by returning null for my key.

I then tried this tutorial: https://medium.com/@patoncrispy/securing-settings-in-dot-net-core-apps-using-azure-key-vault-d4ec82de00b8

this also works during debugging, but when I publish to Azure, it also fails by returning null for my key.

any help in where I should look on how to resolve this would be great.  Why would I get null in production, but not debugging when the same credentials are supplied?

答:
In order for the app to be able to access the Key Vault in Azure using the AppAuthentication library, it should have Managed Service Identity enabled.

In addition the automatically created service principal needs to be given access to the secrets in Key Vault.

Specifying the KeyVault endpoint URL in Azure can be done using an app setting with the key KEYVAULT_ENDPOINT in the first example.


问:
Select values that exists in array, but do not exits in database?
I have got DB with IDs: 1 2 3 4 5. I need to return elements that exists in my array (simple list of data that usually specifying in IN ( ... ) ), but DO NOT exits in DB.
For example checking values: 1, 2, 3, 4, 5, 6, 7.

So query should return 6, 7. How can I do it's with PostgreSQL?

答:
This can be solved using except

```<code>select *
from unnest(array[1,2,3,4,5,6]) as t(id)
except
select id
from the_table
</code>```

With some test data:

```<code>select *
from unnest(array[1,2,3,4,5,6]) as t(id)
except
select id
from (values (1), (2), (3), (4) ) as the_table(id)
</code>```

returns

```<code>id
--
 5
 6
</code>```

Body:
This can be solved using except

select *
from unnest(array[1,2,3,4,5,6]) as t(id)
except
select id
from the_table

With some test data:

select *
from unnest(array[1,2,3,4,5,6]) as t(id)
except
select id
from (values (1), (2), (3), (4) ) as the_table(id)

returns

id
--
 5
 6


问:
If a function creates and returns an object, should it be in the autorelease pool
I'm still pretty new to objective-c.

As far as I can understand, any object I do not get from alloc, new, copy, or mutableCopy should be assumed to be in the autorelease pool.

I assume that also means that if I create a function that creates and returns a new instance of an object, I should place that in the autorelease pool before returning.

For example, I have a function that parses xml, and returns an object representing the data in the xml, that object should be in the autorelease pool before returning.

My primary concern is iPhone development, but a general answer would be appreciated.

答:
You can do it both ways: either return an object that is owned by the caller, or return an object that is not owned by the caller (e.g., an autoreleased object). Regardless of which strategy you choose, follow the naming conventions. For instance,

```<code>- (NSString *)fullNameCopy {
    return [[NSString alloc] initWithFormat:@"%@ %@", self.firstName, self.LastName];
}
</code>```

returns an NSString object that is owned by the caller. The method name is fullNameCopy, which follows the naming rules: a method that contains ‘copy’ in its name returns an object that’s owned by the caller. The return value is not placed in the autorelease pool.

Alternatively,

```<code>- (NSString *)fullName {
    return [NSString stringWithFormat:@"%@ %@", self.firstName, self.LastName];
}
</code>```

or

```<code>- (NSString *)fullName {
    NSString *s = [[NSString alloc] initWithFormat:@"%@ %@", self.firstName, self.LastName];
    return [s autorelease];
}
</code>```

return a string that is not owned by the caller, and the method name doesn’t contain alloc, new, or copy. The return value is autoreleased, hence it will be deallocated when the corresponding autorelease pool is drained unless the caller explicitly chooses to retain it.

That said, in your particular scenario, the second strategy — returning an object that is not owned by the caller — looks like a better solution. The caller will most likely either process the object immediately (so he won’t be interested in owning the object) or keep it in a property (which will most likely be either a copy or a retain property).

Body:
You can do it both ways: either return an object that is owned by the caller, or return an object that is not owned by the caller (e.g., an autoreleased object). Regardless of which strategy you choose, follow the naming conventions. For instance,

- (NSString *)fullNameCopy {
    return [[NSString alloc] initWithFormat:@"%@ %@", self.firstName, self.LastName];
}

returns an NSString object that is owned by the caller. The method name is fullNameCopy, which follows the naming rules: a method that contains ‘copy’ in its name returns an object that’s owned by the caller. The return value is not placed in the autorelease pool.

Alternatively,

- (NSString *)fullName {
    return [NSString stringWithFormat:@"%@ %@", self.firstName, self.LastName];
}

or

- (NSString *)fullName {
    NSString *s = [[NSString alloc] initWithFormat:@"%@ %@", self.firstName, self.LastName];
    return [s autorelease];
}

return a string that is not owned by the caller, and the method name doesn’t contain alloc, new, or copy. The return value is autoreleased, hence it will be deallocated when the corresponding autorelease pool is drained unless the caller explicitly chooses to retain it.

That said, in your particular scenario, the second strategy — returning an object that is not owned by the caller — looks like a better solution. The caller will most likely either process the object immediately (so he won’t be interested in owning the object) or keep it in a property (which will most likely be either a copy or a retain property).


问:
Invalid SSL certificate when building a crate with cargo
While trying an example from the tutorial (guessing game) after defining a dependency (rand="0.3.0") I got this:

```<code>$ cargo build --verbose
    Updating registry `https://github.com/rust-lang/crates.io-index`
Unable to update registry https://github.com/rust-lang/crates.io-index

Caused by:
  failed to fetch `https://github.com/rust-lang/crates.io-index`

Caused by:
  [16] The SSL certificate is invalid
</code>```

Added this to cargo registry git repo, but without success:

```<code>[http]
    sslVerify = false
</code>```

Where to dig?

答:
I ran into the same problem today and found that my $HOME/.gitconfig had this:

```<code>[url "git@github.com:"]
    insteadOf = https://github.com/
</code>```

I had added this to make go get to work over SSH for private repos. Commenting this out fixed the error.

Body:
While trying an example from the tutorial (guessing game) after defining a dependency (rand="0.3.0") I got this:

$ cargo build --verbose
    Updating registry `https://github.com/rust-lang/crates.io-index`
Unable to update registry https://github.com/rust-lang/crates.io-index

Caused by:
  failed to fetch `https://github.com/rust-lang/crates.io-index`

Caused by:
  [16] The SSL certificate is invalid

Added this to cargo registry git repo, but without success:

[http]
    sslVerify = false

Where to dig?

Body:
I ran into the same problem today and found that my $HOME/.gitconfig had this:

[url "git@github.com:"]
    insteadOf = https://github.com/

I had added this to make go get to work over SSH for private repos. Commenting this out fixed the error.


答:
```<code>with t (id) as (values (1),(2),(3),(4),(5))
select u.id
from
    t
    right join
    unnest(array[1,2,3,4,5,6,7]) u (id) on t.id = u.id
where t.id is null
;
 id
----
  6
  7
</code>```

Title: Select values that exists in array, but do not exits in database?

Body:
I have got DB with IDs: 1 2 3 4 5. I need to return elements that exists in my array (simple list of data that usually specifying in IN ( ... ) ), but DO NOT exits in DB.
For example checking values: 1, 2, 3, 4, 5, 6, 7.

So query should return 6, 7. How can I do it's with PostgreSQL?


问:
Laravel CSRF Field in Vue Component
I would like to ask how can I add the csrf_field() in my vue component. The error is

Property or method "csrfToken" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option.

Here's the code:

```
<pre class="snippet-code-html lang-html prettyprint-override"><code><template>
  <div id="app">
    <form action="#" method="POST">
      {{csrfToken()}}
      <div class="form-group">
        <label for="name">Name</label>
        <input type="text" id="name" class="form-control">
      </div>
      <div class="form-group">
        <label for="location">Location</label>
        <input type="text" id="location" class="form-control">
      </div>
      <div class="form-group">
        <label for="age">Age</label>
        <input type="number" id="age" class="form-control">
      </div>
      <div class="form-group">
        <input type="submit" class="btn btn-default">
      </div>
    </form>
  </div>
</template></code>```

答:
As I already wrote here, I would simply suggest to put this in your PHP file:

```<code><script>
    window.Laravel = <?php echo json_encode(['csrfToken' => csrf_token()]); ?>
</script>
</code>```

This way you're able to easily import your csrfToken from the JS part (Vue in this case).

Moreover, if you insert this code in your PHP layout file, you can use the token by any component of your app, since window is a JS global variable.

Source: I got the trick from this post.

Title: Laravel CSRF Field in Vue Component

Body:
I would like to ask how can I add the csrf_field() in my vue component. The error is

Property or method "csrfToken" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option.

Here's the code:

<template>

    <form action="#" method="POST">
      {{csrfToken()}}

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

        Location
        <input type="text" id="location" class="form-control">

        Age
        <input type="number" id="age" class="form-control">

        <input type="submit" class="btn btn-default">

    </form>

</template>

Body:
As I already wrote here, I would simply suggest to put this in your PHP file:

<script>
    window.Laravel = <?php echo json_encode(['csrfToken' => csrf_token()]); ?>
</script>

This way you're able to easily import your csrfToken from the JS part (Vue in this case).

Moreover, if you insert this code in your PHP layout file, you can use the token by any component of your app, since window is a JS global variable.

Source: I got the trick from this post.


问:
Convert a Pandas DataFrame to a multidimensional ndarray
I have a DataFrame with columns for the x, y, z coordinates and the value at this position and I want to convert this to a 3-dimensional ndarray.

To make things more complicated, not all values exist in the DataFrame (these can just be replaced by NaN in the ndarray).

Just a simple example:

```<code>df = pd.DataFrame({'x': [1, 2, 1, 3, 1, 2, 3, 1, 2],
                   'y': [1, 1, 2, 2, 1, 1, 1, 2, 2],
                   'z': [1, 1, 1, 1, 2, 2, 2, 2, 2],
                   'value': [1, 2, 3, 4, 5, 6, 7, 8, 9]})
</code>```

Should result in the ndarray:

```<code>array([[[  1.,   2.,  nan],
        [  3.,  nan,   4.]],

       [[  5.,   6.,   7.],
        [  8.,   9.,  nan]]])
</code>```

For two dimensions, this is easy:

```<code>array = df.pivot_table(index="y", columns="x", values="value").as_matrix()
</code>```

However, this method can not be applied to three or more dimensions.

Could you give me some suggestions?

Bonus points if this also works for more than three dimensions, handles multiple defined values (by taking the average) and ensures that all x, y, z coordinates are consecutive (by inserting row/columns of NaN when a coordinate is missing).

EDIT: Some more explanations:

I read data from a CSV file which has the columns for x, y, z coordinates, optionally the frequency and the measurement value at this point and frequency. Then I round the coordinates to a specified precision (e.g. 0.1m) and want to get an ndarray which contains the averaged measurement values at each (rounded) coordinates. The indizes of the values do not need to coincide with the location. However they need to be in the correct order.

EDIT: I just ran a quick performance test:

The solution of jakevdp takes 1.598s, Divikars solution takes 7.405s, JohnE's solution takes 7.867s and Wens solution takes 6.286s to complete.

答:
Here's one NumPy approach -

```<code>def dataframe_to_array_averaged(df):
    arr = df[['z','y','x']].values
    arr -= arr.min(0)
    out_shp = arr.max(0)+1

    L = np.prod(out_shp)

    val = df['value'].values
    ids = np.ravel_multi_index(arr.T, out_shp)

    avgs = np.bincount(ids, val, minlength=L)/np.bincount(ids, minlength=L)
    return avgs.reshape(out_shp)
</code>```

Note that that this shows a warning because for places with no x,y,z triplets would have zero counts and hence the average values would be 0/0 = NaN, but since that's the expected output for those places, you can ignore the warning there. To avoid this warning, we can employ indexing, as discussed in the second method (Alternative method).

Sample run -

```<code>In [106]: df
Out[106]:
   value  x  y  z
0      1  1  1  1  # <=== this is repeated
1      2  2  1  1
2      3  1  2  1
3      4  3  2  1
4      5  1  1  2
5      6  2  1  2
6      7  3  1  2
7      8  1  2  2
8      9  2  2  2
9      4  1  1  1  # <=== this is repeated

In [107]: dataframe_to_array_averaged(df)
__main__:42: RuntimeWarning: invalid value encountered in divide
Out[107]:
array([[[ 2.5,  2. ,  nan],
        [ 3. ,  nan,  4. ]],

       [[ 5. ,  6. ,  7. ],
        [ 8. ,  9. ,  nan]]])
</code>```

Alternative method

To avoid warning, an alternative way would be like so -

```<code>out = np.full(out_shp,  np.nan)
sums = np.bincount(ids, val)
unq_ids, count = np.unique(ids, return_counts=1)
out.flat[:unq_ids[-1]] = sums
out.flat[unq_ids] /= count
</code>```

Body:
I have a DataFrame with columns for the x, y, z coordinates and the value at this position and I want to convert this to a 3-dimensional ndarray.

To make things more complicated, not all values exist in the DataFrame (these can just be replaced by NaN in the ndarray).

Just a simple example:

df = pd.DataFrame({'x': [1, 2, 1, 3, 1, 2, 3, 1, 2],
                   'y': [1, 1, 2, 2, 1, 1, 1, 2, 2],
                   'z': [1, 1, 1, 1, 2, 2, 2, 2, 2],
                   'value': [1, 2, 3, 4, 5, 6, 7, 8, 9]})

Should result in the ndarray:

array([[[  1.,   2.,  nan],
        [  3.,  nan,   4.]],

       [[  5.,   6.,   7.],
        [  8.,   9.,  nan]]])

For two dimensions, this is easy:

array = df.pivot_table(index="y", columns="x", values="value").as_matrix()

However, this method can not be applied to three or more dimensions.

Could you give me some suggestions?

Bonus points if this also works for more than three dimensions, handles multiple defined values (by taking the average) and ensures that all x, y, z coordinates are consecutive (by inserting row/columns of NaN when a coordinate is missing).

EDIT: Some more explanations:

I read data from a CSV file which has the columns for x, y, z coordinates, optionally the frequency and the measurement value at this point and frequency. Then I round the coordinates to a specified precision (e.g. 0.1m) and want to get an ndarray which contains the averaged measurement values at each (rounded) coordinates. The indizes of the values do not need to coincide with the location. However they need to be in the correct order.

EDIT: I just ran a quick performance test:

The solution of jakevdp takes 1.598s, Divikars solution takes 7.405s, JohnE's solution takes 7.867s and Wens solution takes 6.286s to complete.

Body:
Here's one NumPy approach -

def dataframe_to_array_averaged(df):
    arr = df[['z','y','x']].values
    arr -= arr.min(0)
    out_shp = arr.max(0)+1

    L = np.prod(out_shp)

    val = df['value'].values
    ids = np.ravel_multi_index(arr.T, out_shp)

    avgs = np.bincount(ids, val, minlength=L)/np.bincount(ids, minlength=L)
    return avgs.reshape(out_shp)

Note that that this shows a warning because for places with no x,y,z triplets would have zero counts and hence the average values would be 0/0 = NaN, but since that's the expected output for those places, you can ignore the warning there. To avoid this warning, we can employ indexing, as discussed in the second method (Alternative method).

Sample run -

In [106]: df
Out[106]:
   value  x  y  z
0      1  1  1  1  # <=== this is repeated
1      2  2  1  1
2      3  1  2  1
3      4  3  2  1
4      5  1  1  2
5      6  2  1  2
6      7  3  1  2
7      8  1  2  2
8      9  2  2  2
9      4  1  1  1  # <=== this is repeated

In [107]: dataframe_to_array_averaged(df)
__main__:42: RuntimeWarning: invalid value encountered in divide
Out[107]:
array([[[ 2.5,  2. ,  nan],
        [ 3. ,  nan,  4. ]],

       [[ 5. ,  6. ,  7. ],
        [ 8. ,  9. ,  nan]]])

Alternative method

To avoid warning, an alternative way would be like so -

out = np.full(out_shp,  np.nan)
sums = np.bincount(ids, val)
unq_ids, count = np.unique(ids, return_counts=1)
out.flat[:unq_ids[-1]] = sums
out.flat[unq_ids] /= count


问:
Android Studio writing BOM's to UTF-8 file
I am working on a project where all the source files are encoded as UTF-8, to please the java compiler (otherwis, it will spit out errors on other encodings). Everytime I save a source file with Android Studio, it will write a Byte Order Mark on the file, preventing the compilation from succeeding. How can I fix this?

As a workaround, I am manually deleting the BOM with a Hex Editor but it gets really annoying.

答:
You can use some tool to convert your file to UTF-8 with BOM.

I used Notepad++:

remove "<?xml version="1.0" encoding="utf-8"?>" from file if it is. (I used Notepad for that)

open file with Notepad++.

ensure you see characters as they should be

select Menu -> Encoding -> Convert to UTF-8

add "<?xml version="1.0" encoding="utf-8"?>" at file start

ContentLicense: CC BY-SA 4.0


问:
Include node_module into Ember component
I am trying to add wavesurfer to my application. I did exactly according to the instructions. at: https://www.npmjs.com/package/wavesurfer.js

After I did bower install I had wavesurfer.js folder inside my node_modules

import WaveSurfer from 'wavesurfer.js';

Theoretically WaveSurfer class should be available on my component. But after I include above code I have this error

```<code>Uncaught Error: Could not find module wavesurfer.js
at requireModule (loader.js:58)
at reify (loader.js:41)
at requireModule (loader.js:69)
at Class._extractDefaultExport (ember-resolver.js:390)
at Class.resolveOther (ember-resolver.js:122)
at Class.superWrapper [as resolveOther] (ember.debug.js:17407)
at Class.resolve (ember.debug.js:4597)
at Registry.resolve [as resolver] (ember.debug.js:4437)
at resolve (ember.debug.js:2109)
at Registry.resolve (ember.debug.js:1715)
</code>```

I killed almost a week on this.

How can I make that class available for my component

Thanks

答:
Well, open your ember-cli-build.js and import the library as follows:

```<code>  // if you used npm then:
  app.import('node_modules/<path-to-wavesurfer.js>');

  // if you used bower then:
  app.import('bower_components/<path-to-wavesurfer.js>');
</code>```

depending on which package manager you used to install the dependency.
I did a quick search and found this shim: https://github.com/chrism/ember-cli-wavesurfer-js-shim, which probably includes the lib into the build. However, doesn't seem to be working with up-to-date Ember.

Body:
I am trying to add wavesurfer to my application. I did exactly according to the instructions. at: https://www.npmjs.com/package/wavesurfer.js

After I did bower install I had wavesurfer.js folder inside my node_modules

import WaveSurfer from 'wavesurfer.js';

Theoretically WaveSurfer class should be available on my component. But after I include above code I have this error

Uncaught Error: Could not find module wavesurfer.js
at requireModule (loader.js:58)
at reify (loader.js:41)
at requireModule (loader.js:69)
at Class._extractDefaultExport (ember-resolver.js:390)
at Class.resolveOther (ember-resolver.js:122)
at Class.superWrapper [as resolveOther] (ember.debug.js:17407)
at Class.resolve (ember.debug.js:4597)
at Registry.resolve [as resolver] (ember.debug.js:4437)
at resolve (ember.debug.js:2109)
at Registry.resolve (ember.debug.js:1715)

I killed almost a week on this.

How can I make that class available for my component

Thanks

Body:
Well, open your ember-cli-build.js and import the library as follows:

  // if you used npm then:
  app.import('node_modules/<path-to-wavesurfer.js>');

  // if you used bower then:
  app.import('bower_components/<path-to-wavesurfer.js>');

depending on which package manager you used to install the dependency.
I did a quick search and found this shim: https://github.com/chrism/ember-cli-wavesurfer-js-shim, which probably includes the lib into the build. However, doesn't seem to be working with up-to-date Ember.


问:
Convert Angular Web Application to android application through cordova. If not cordova any other framework suggestions
I have created a web application in Angular. Now I want to make that application into an android application. How can I achieve it through cordova? If not cordova then any other suggestions to converted angular web app to android app.</p>

答: I prefer Ionic Framework its built with angular 4,5 you can reuse the same code and there are some changes .. first you have to create new ionic app and reuse the components and services in IONIC for more documentation you can refer this link   here</p>


问:
Modify all text output by TYPO3
I would like to create a "cleanup" extension that replaces various characters (quotes by guillemets) in all kinds of textfields in TYPO3.

I thought about extending <f:format.html> or parseFunc, but I don't know where to "plug in" so I get to replace output content easily before it's cached.

Any ideas, can you give me an example?

答:
If you don't mind regexing, try this:

```<code>$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['cleanUpQuotes'][] = \NAMESPACE\Your\Extension::class;
</code>```

Insert it into ext_localconf.php and this part is done.
The next step is the class itself:

```<code>public function cleanUpQuotes(TypoScriptFrontendController $parentObject)
{
   $parentObject->content = DO_YOUR_THING_HERE
}
</code>```

Title: Modify all text output by TYPO3

Body:
If you don't mind regexing, try this:

$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['cleanUpQuotes'][] = \NAMESPACE\Your\Extension::class;

Insert it into ext_localconf.php and this part is done.
The next step is the class itself:

public function cleanUpQuotes(TypoScriptFrontendController $parentObject)
{
   $parentObject->content = DO_YOUR_THING_HERE
}


问:
Best practices: C# Extension methods namespace and promoting extension methods
I know there exists already a post, describing nearly the same, but I think mine is a bit different.

What I would like to know is how you organize your extension methods in terms of assigning the namespace. Currently - for the extension methods in our framework - I use the following namespace pattern

MyCompany.Web.Utils

and inside I have the extension method classes. This is fine for me with the disadvantage that the extenders are not immediately visible to our software developers. Consider the case where I have a StringExtender class which provides a quite handy extension method "In" that extends the String object. Having the extension method withing the above mentioned namespace, our programmers won't see the extension method unless they explicitly include its namespace. Instead, if I would put the extension method in the System namespace, everyone would immediately see it, but I've read that this is bad practice.

So my question is how you do promote your extension methods s.t. they are used by your developers.

答:
We put everything into the same Namespace and Class, however we use partial classes to keep them organized.

For example:

ExtensionMethods-String.cs

ExtensionMethods-DataObject.cs

ExtensionMethods-Debug.cs

...etc all have partial classes...


问:
Cannot convert from java Double to java Date
I am having an issue with converting a double to a Java date object in the format: yyyy-MM-dd HH:mm:ss

I have tried to convert this double value to a long value then instanciate a Date object with the result, but I got errors saying that I cannot convert from double to long.

my timestamp double values are in this format:

1.511554592277516E9

Can anybody help me with this issue please, thanks in advance.

答:
Your floating-point value, 1.511554592277516E9, no doubt denotes seconds since the epoch of January 1, 1970 at midnight UTC, with microsecond precision: 1 511 554 592 seconds and 277 516 microseconds (millionths of a second).

I suggest using java.time, the modern Java date and time API also known as JSR-310, for this. It is much nicer to work with than the outdated Date class and friends, and also offers nanosecond precision (Date only has millisecond precision, so you would lose precision if converting into one). More specifically I will first create a java.time.Instant object (conversion to other date-time types will be easy, I’ll touch on one example at the end).

Getting the full precision through into an Instant requires a little thought. I played a little with double and long, but realized (1) double doesn’t have the full precision required, the nanoseconds will not be right (2) converting to a long holding the nanoseconds (not the only way, but certainly the easiest) will create a “year 2262 problem”, so if you are handling dates in a far future, it will not work. In any case, I think that the easy and safe solution is to use BigDecimal for the math required before feeding the numbers into an Instant.

```<code>    String secondsSinceEpoch = "1.511554592277516E9";
    BigDecimal decimalSeconds = new BigDecimal(secondsSinceEpoch);
    long seconds = decimalSeconds.longValue();
    long nanos = decimalSeconds.subtract(BigDecimal.valueOf(seconds))
            .movePointRight(9)
            .longValueExact();
    Instant inst = Instant.ofEpochSecond(seconds, nanos);
    System.out.println(inst);
</code>```

This prints:

```<code>2017-11-24T20:16:32.277516Z
</code>```

The printed date-time is in UTC. If the value is as expected, I should say it confirms that your floating-point value was indeed seconds since the epoch.

You requested a date-time in the format yyyy-MM-dd HH:mm:ss. You will need to decide in which time zone you want the date-time. Date objects don’t have a format, so you will also need to get the format in a string. For example:

```<code>    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    System.out.println(inst.atZone(ZoneId.of("America/Vancouver")).format(formatter));
</code>```

This prints

```<code>2017-11-24 12:16:32
</code>```

You substitute your desired time zone, of course. atZone() converts the Instant into a ZonedDateTime, another often used class of java.time.

EDIT: In case you don’t want to bother with BigDecimal, you accept a slight inaccuracy and/or your receive your value as a double rather than a string, here’s an alternative in fewer lines of code:

```<code>    double secondsSinceEpoch = 1.511554592277516E9;
    long longSeconds = (long) secondsSinceEpoch;
    long micros = Math.round((secondsSinceEpoch - longSeconds) * 1_000_000);
    Instant inst = Instant.ofEpochSecond(longSeconds).plus(micros , ChronoUnit.MICROS);
</code>```

In this particular case it gives exactly the same result, down to the nanosecond. I’m not sure whether with other inputs, the microseconds may end up inaccurate, but on the other hand, if you receive a double (not a string), there’s nothing you could do about that anyway.

Body:
Your floating-point value, 1.511554592277516E9, no doubt denotes seconds since the epoch of January 1, 1970 at midnight UTC, with microsecond precision: 1 511 554 592 seconds and 277 516 microseconds (millionths of a second).

I suggest using java.time, the modern Java date and time API also known as JSR-310, for this. It is much nicer to work with than the outdated Date class and friends, and also offers nanosecond precision (Date only has millisecond precision, so you would lose precision if converting into one). More specifically I will first create a java.time.Instant object (conversion to other date-time types will be easy, I’ll touch on one example at the end).

Getting the full precision through into an Instant requires a little thought. I played a little with double and long, but realized (1) double doesn’t have the full precision required, the nanoseconds will not be right (2) converting to a long holding the nanoseconds (not the only way, but certainly the easiest) will create a “year 2262 problem”, so if you are handling dates in a far future, it will not work. In any case, I think that the easy and safe solution is to use BigDecimal for the math required before feeding the numbers into an Instant.

    String secondsSinceEpoch = "1.511554592277516E9";
    BigDecimal decimalSeconds = new BigDecimal(secondsSinceEpoch);
    long seconds = decimalSeconds.longValue();
    long nanos = decimalSeconds.subtract(BigDecimal.valueOf(seconds))
            .movePointRight(9)
            .longValueExact();
    Instant inst = Instant.ofEpochSecond(seconds, nanos);
    System.out.println(inst);

This prints:

2017-11-24T20:16:32.277516Z

The printed date-time is in UTC. If the value is as expected, I should say it confirms that your floating-point value was indeed seconds since the epoch.

You requested a date-time in the format yyyy-MM-dd HH:mm:ss. You will need to decide in which time zone you want the date-time. Date objects don’t have a format, so you will also need to get the format in a string. For example:

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    System.out.println(inst.atZone(ZoneId.of("America/Vancouver")).format(formatter));

This prints

2017-11-24 12:16:32

You substitute your desired time zone, of course. atZone() converts the Instant into a ZonedDateTime, another often used class of java.time.

EDIT: In case you don’t want to bother with BigDecimal, you accept a slight inaccuracy and/or your receive your value as a double rather than a string, here’s an alternative in fewer lines of code:

    double secondsSinceEpoch = 1.511554592277516E9;
    long longSeconds = (long) secondsSinceEpoch;
    long micros = Math.round((secondsSinceEpoch - longSeconds) * 1_000_000);
    Instant inst = Instant.ofEpochSecond(longSeconds).plus(micros , ChronoUnit.MICROS);

In this particular case it gives exactly the same result, down to the nanosecond. I’m not sure whether with other inputs, the microseconds may end up inaccurate, but on the other hand, if you receive a double (not a string), there’s nothing you could do about that anyway.


答:
You can use a groupby followed by the approach from Transform Pandas DataFrame with n-level hierarchical index into n-D Numpy array:

```<code>grouped = df.groupby(['z', 'y', 'x'])['value'].mean()

# create an empty array of NaN of the right dimensions
shape = tuple(map(len, grouped.index.levels))
arr = np.full(shape, np.nan)

# fill it using Numpy's advanced indexing
arr[grouped.index.labels] = grouped.values.flat

print(arr)
# [[[  1.   2.  nan]
#   [  3.  nan   4.]]
#
#  [[  5.   6.   7.]
#   [  8.   9.  nan]]]
</code>```

Title: Convert a Pandas DataFrame to a multidimensional ndarray

Body:
You can use a groupby followed by the approach from Transform Pandas DataFrame with n-level hierarchical index into n-D Numpy array:

grouped = df.groupby(['z', 'y', 'x'])['value'].mean()

# create an empty array of NaN of the right dimensions
shape = tuple(map(len, grouped.index.levels))
arr = np.full(shape, np.nan)

# fill it using Numpy's advanced indexing
arr[grouped.index.labels] = grouped.values.flat

print(arr)
# [[[  1.   2.  nan]
#   [  3.  nan   4.]]
#
#  [[  5.   6.   7.]
#   [  8.   9.  nan]]]


问:
getting values from strings taken by querySelectorAll
I'm trying to get values from strings.

```<code><div class="example">sth 44.05 $</div>

<div class="example">sth another 140.00 $</div>

<div class="example">sth sth 100.05 $</div>
<button onclick="myFunction()">test</button>
<p id="values">demo</p>
</code>```

If it's one, it's simple:

```<code><script>
function myFunction() {
var x = document.querySelector('.example').innerText;

let number=x.match(/\d+(\.\d+)?/)[0];

document.getElementById('values').innerHTML = +number;

}</script>
</code>```

But I'm not sure how to get all those values (and then count them). Trying to do to sth similar, but it doesn't work:

```<code><script>
function myFunction() {
var x = document.querySelectorAll('.example');
var i;
for (i = 0; i < x.length; i++) {
    x[i].innerText;
}

var value = [];
for (i = 0; i < x.length; i++) {
    value.push( x[i].innerText);
}

let number=value.match(/\d+(\.\d+)?/)[0];

document.getElementById('values').innerHTML = +number;

}
</script>
</code>```

答:
```<code>let number=value.match(/\d+(\.\d+)?/)[0];
</code>```

match is a method you find on strings.

value is an array, not a string.

You'll need to convert value to a string (e.g. with join) if you want to run a regex across all of it.

Body:
I'm trying to get values from strings.

sth 44.05 $

sth another 140.00 $

sth sth 100.05 $

<button onclick="myFunction()">test</button>

demo

If it's one, it's simple:

But I'm not sure how to get all those values (and then count them). Trying to do to sth similar, but it doesn't work:

Body:
let number=value.match(/\d+(\.\d+)?/)[0];

match is a method you find on strings.

value is an array, not a string.

You'll need to convert value to a string (e.g. with join) if you want to run a regex across all of it.


问:
Could not resolve all dependencies for configuration ':_debugApkCopy' when using cordova-plugin-facebook4
I installed cordova facebook4 plugin

```<code>cordova plugin add cordova-plugin-facebook4 --save --variable APP_ID="12345678910" --variable APP_NAME="My Application Name"
</code>```

and when I try to build, it shows
this error.

I never got this error till last week, but today when I want to update my app it shows that error. Any suggestion?

答:
This seems to be a new issue with the facebook plugin.

Try changing

```<code><framework src="com.facebook.android:facebook-android-sdk:4+"/>
</code>```

to

```<code><framework src="com.facebook.android:facebook-android-sdk:4.26.0"/>
</code>```

in plugin.xml of plugin located in /plugins/cordova-plugin-facebook4

and replace com.facebook.android:facebook-android-sdk:4.+
with
com.facebook.android:facebook-android-sdk:4.26.0
both in /platforms/android/build.gradle and /platforms/android/project.properties in your cordova project.

This should be a temporary measure.

Body:
I installed cordova facebook4 plugin

cordova plugin add cordova-plugin-facebook4 --save --variable APP_ID="12345678910" --variable APP_NAME="My Application Name"

and when I try to build, it shows
this error.

I never got this error till last week, but today when I want to update my app it shows that error. Any suggestion?

Body:
This seems to be a new issue with the facebook plugin.

Try changing

<framework src="com.facebook.android:facebook-android-sdk:4+"/>

to

<framework src="com.facebook.android:facebook-android-sdk:4.26.0"/>

in plugin.xml of plugin located in /plugins/cordova-plugin-facebook4

and replace com.facebook.android:facebook-android-sdk:4.+
with
com.facebook.android:facebook-android-sdk:4.26.0
both in /platforms/android/build.gradle and /platforms/android/project.properties in your cordova project.

This should be a temporary measure.


问:
Attribution muddled by Financing Partner
In Google Analytics, under Conversion > Attribution > Attribution Model Comparison Tool, I am running into an attribution problem. Our e-commerce company has partnered with a financing company that allows visitors to purchase our product by financing with our partner. This requires our user to click a link that takes them from our purchase page, to our partner's page. After getting approved for financing, they are redirected to our page, and the purchase is completed.
This causes a problem in Google Analytics. To Google Analytics, it looks like our partner page is the referring media source, so many of our purchases show up under the source/medium of our financing partner. In reality, these people originally came from some other media source like Facebook, instagram or google.

Is there a way to bypass the traffic from this specific source/medium (our financing partner) so that I can see where these purchases originated from?

答:
In this scenario, you'd probably want to add the partner domain to the Referral Exclusion List. https://support.google.com/analytics/answer/2795830 </p>

<p>Note, there is something more sinister happening as well to your session counts. As the user returns with a new referrer,  meaning the source/medium/campaign changed during a session,  the previous sessions closes out and a new session is created. So this is ruining your session based metrics like pages/visit, time on site, etc... https://support.google.com/analytics/answer/2731565 </p>

Body:
In this scenario, you'd probably want to add the partner domain to the Referral Exclusion List. https://support.google.com/analytics/answer/2795830

Note, there is something more sinister happening as well to your session counts. As the user returns with a new referrer,  meaning the source/medium/campaign changed during a session,  the previous sessions closes out and a new session is created. So this is ruining your session based metrics like pages/visit, time on site, etc... https://support.google.com/analytics/answer/2731565


问:
In .net MVC Is there a better way to hide dt elements than adding display: none to each?
One of my views contains a dl element with a lot of the following structures repeated inside:

```<code><dt>
    <label>Accept this thing?</label>
</dt>
<dd>
    @Html.CheckBoxFor(model => model.ThisThingAccepted)
</dd>
</code>```

There are many such "things". I want the checkbox and label to disappear once the user has accepted the thing and posted the data back so it can be saved.

However, use of div and span elements inside a dl are disallowed, so the only HTML-legal way of doing this appears to be:

```<code><dt  @if (Model.ThisThingAccepted) { <text> style="display: none;" </text> }>
    <label>Accept this thing?</label>
</dt>
<dd @if (Model.ThisThingAccepted) { <text> style="display: none;" </text> }>
    @Html.CheckBoxFor(model => model.ThisThingAccepted)
</dd>
</code>```

Which is messy as all hell.

I know I could tidy it up a bit by using a custom display template, but is there a neater way to hide these elements?

答:
I presume they need to be present in the UI on render?  If not, wrap them in an if statement and don't render them at all.

I sometimes do:

```<code>style='@(Model.ThisThingAccepted ? "display: none;" : "" }'
</code>```

Or use a method in a function block of the view:

```<code>@functions {
   public string GetInitialState(ModelType model)
   {
       return model.ThisThingAccepted ? "style=display:none;" : "";
   }
}

<dt @GetInitialState(Model)>
</code>```

Body:
One of my views contains a dl element with a lot of the following structures repeated inside:

    Accept this thing?

    @Html.CheckBoxFor(model => model.ThisThingAccepted)

There are many such "things". I want the checkbox and label to disappear once the user has accepted the thing and posted the data back so it can be saved.

However, use of div and span elements inside a dl are disallowed, so the only HTML-legal way of doing this appears to be:

<dt  @if (Model.ThisThingAccepted) { <text> style="display: none;" </text> }>
    Accept this thing?

<dd @if (Model.ThisThingAccepted) { <text> style="display: none;" </text> }>
    @Html.CheckBoxFor(model => model.ThisThingAccepted)

Which is messy as all hell.

I know I could tidy it up a bit by using a custom display template, but is there a neater way to hide these elements?

Body:
I presume they need to be present in the UI on render?  If not, wrap them in an if statement and don't render them at all.

I sometimes do:

style='@(Model.ThisThingAccepted ? "display: none;" : "" }'

Or use a method in a function block of the view:

@functions {
   public string GetInitialState(ModelType model)
   {
       return model.ThisThingAccepted ? "style=display:none;" : "";
   }
}

<dt @GetInitialState(Model)>


问:
How jsAjaxForm from jQuery v2.1.3 changed in jQuery v3.2.1

I am switching to higher version of jquery(3.2.1)
and facing difficulties with up-grade ajax file upload by jsAjaxForm in jQuery v2.1.3 functions.
Is there any function that does same role as jaAjaxForm in jQuery v3.2.1? or any suggestions?

I used to submit the form and jsAjaxForm will handle the rest of issue with uploading the file... and after applying jQuery v3.1.2 this function doesn't work anymore...

```<code>$("#frm").submit();

jsAjaxForm("POST", "/fcltsMange/fcltsInfoInsert", "frm", function(response, status){
        alert("!");
    if (response.result != null) {
        if (response.result == "success") {
            alert("success");
        }else{
            alert("fail");
        }
    }
});
</code>```

and this r.fn.load=function from jquery.min.js is where root-error happens...

```<code>r.fn.load=function(a,b,c){var d,e,f,g=this,.....
</code>```

答:
Try including the migrate plugin given below.

```<code><script src="https://code.jquery.com/jquery-migrate-3.0.1.js"></script>
</code>```

Source

Body:
I am switching to higher version of jquery(3.2.1)
and facing difficulties with up-grade ajax file upload by jsAjaxForm in jQuery v2.1.3 functions.
Is there any function that does same role as jaAjaxForm in jQuery v3.2.1? or any suggestions?

I used to submit the form and jsAjaxForm will handle the rest of issue with uploading the file... and after applying jQuery v3.1.2 this function doesn't work anymore...

$("#frm").submit();

jsAjaxForm("POST", "/fcltsMange/fcltsInfoInsert", "frm", function(response, status){
        alert("!");
    if (response.result != null) {
        if (response.result == "success") {
            alert("success");
        }else{
            alert("fail");
        }
    }
});

and this r.fn.load=function from jquery.min.js is where root-error happens...

r.fn.load=function(a,b,c){var d,e,f,g=this,.....

Body:
Try including the migrate plugin given below.

<script src="https://code.jquery.com/jquery-migrate-3.0.1.js"></script>

Source


问:
Regex using the AND NOT operator
I'm looking for a regular expression that I find in the text, the words "ata de audiência" OR "termo de audiência", and find "inconcilia" AND "reclamante" AND "reclamada", and do NOT find the word "sentença"

```<code>if(re.search(r'ata de audiência' or r'termo de audiência') and r'inconcilia' and r'reclamada' and r'reclamante' and not r'sentença', content.read())):
            key_content = True
</code>```

I tried to do it this way.. i can find the words, but when I use the  "AND NOT" operator, the regular expression does not work

ps: there are words in portuguese

答:
You don't need a regular expression for that.</p>

```<code>text = content.read()

if ('ata de audiência' in text or 'termo de audiência' in text) \
    and 'inconcilia' in text and 'reclamada' in text \
    and 'reclamante' in text and not 'sentença' in text:
        key_content = True
</code>```

Title: Regex using the AND NOT operator

Body:
I'm looking for a regular expression that I find in the text, the words "ata de audiência" OR "termo de audiência", and find "inconcilia" AND "reclamante" AND "reclamada", and do NOT find the word "sentença"

if(re.search(r'ata de audiência' or r'termo de audiência') and r'inconcilia' and r'reclamada' and r'reclamante' and not r'sentença', content.read())):
            key_content = True

I tried to do it this way.. i can find the words, but when I use the  "AND NOT" operator, the regular expression does not work

ps: there are words in portuguese

Body:
You don't need a regular expression for that.

text = content.read()

if ('ata de audiência' in text or 'termo de audiência' in text) \
    and 'inconcilia' in text and 'reclamada' in text \
    and 'reclamante' in text and not 'sentença' in text:
        key_content = True


问:
Can't create table with jpa+spring boot
I'm trying to generate table using JPA. but i can't create it. There is no error in the code, but it seems that there is configuration error. but i can't find it, i tried many configurations but nothing happen.
Thanks a lot.

This is application.property:

```<code>spring.datasource.url=jdbc:mysql://localhost:3306/springapp
spring.datasource.username= root
spring.datasource.password= me
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.hibernate.ddl-auto=create
</code>```

this is my class:

```<code>@Entity
public class Customer {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;
    private String name;
    private String phone;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
    public Customer(String name, String phone) {
        super();
        this.name = name;
        this.phone = phone;
    }
    public Customer() {
        super();
    }
}
</code>```

This is the application:

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

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
</code>```

And this is the controller:

@RestController
@RequestMapping("/customer")
public class CustomerController {
    @Autowired
    CustomerRepository customerRepository;

```<code>@RequestMapping("/findall")
@ResponseBody
public List<Customer> findAll() {
    return customerRepository.findAll();
}
</code>```

}

Pom.xml

```<code>    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>GStock-3</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>GStock-3</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

答:
With the current information I have a couple of suggestions / Questions that might help you allong:

Does the "springapp" database exist with the correct user (root) and password (me) assigned to it in MySQL

Has MySQL been started?

I see no @Repository definition in your code e.g.

@Repository
public interface CustomerRepository extends JpaRepository{}

Title: Can't create table with jpa+spring boot

Body:
I'm trying to generate table using JPA. but i can't create it. There is no error in the code, but it seems that there is configuration error. but i can't find it, i tried many configurations but nothing happen.
Thanks a lot.

This is application.property:

spring.datasource.url=jdbc:mysql://localhost:3306/springapp
spring.datasource.username= root
spring.datasource.password= me
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.hibernate.ddl-auto=create

this is my class:

@Entity
public class Customer {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;
    private String name;
    private String phone;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
    public Customer(String name, String phone) {
        super();
        this.name = name;
        this.phone = phone;
    }
    public Customer() {
        super();
    }
}

This is the application:

@SpringBootApplication
public class Application {

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

And this is the controller:

@RestController
@RequestMapping("/customer")
public class CustomerController {
    @Autowired
    CustomerRepository customerRepository;

@RequestMapping("/findall")
@ResponseBody
public List<Customer> findAll() {
    return customerRepository.findAll();
}

}

Pom.xml

    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>GStock-3</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>GStock-3</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
        <relativePath/>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>


问:
Rails getting routes name in Route.rb with controller actions
I'm a real beginner of rails.

Can I get multiple routes from one controller + many actions?

For example,

```<code>resources :something
</code>```

get "something#index", "something#show", "something#update"...etc.

I'm just curious if there is a command to get route name from the actions.

For example, in a controller named "pledges",

```<code>class PledgesController < ApplicationController
    def home
    end

    def abc
    end

    def defg
    end

    def hijk
    end
end
</code>```

Can any commands get "pledges#home", "pledges#abc", "pledges#defg","pledges#hijk" ?

答:
You will have to define all of the custom actions, if there are not restful (but I would highly recommend that you follow the rest conventions). For example:

```<code>get  'pledges' => 'abc'
post 'pledges' => 'defg'
put  'pledges' => 'hijk
</code>```

Body:
I'm a real beginner of rails.

Can I get multiple routes from one controller + many actions?

For example,

resources :something

get "something#index", "something#show", "something#update"...etc.

I'm just curious if there is a command to get route name from the actions.

For example, in a controller named "pledges",

class PledgesController < ApplicationController
    def home
    end

    def abc
    end

    def defg
    end

    def hijk
    end
end

Can any commands get "pledges#home", "pledges#abc", "pledges#defg","pledges#hijk" ?

Body:
You will have to define all of the custom actions, if there are not restful (but I would highly recommend that you follow the rest conventions). For example:

get  'pledges' => 'abc'
post 'pledges' => 'defg'
put  'pledges' => 'hijk


问:
Combine multiple OR and LIKE mySql
I understand that LIKE can not be used in inside IN clause from here.

My table has col1, col2, col3 columns.

How can I find multiple values in multiple columns using LIKE operator.
Currently my query is:

```<code>SELECT col1, col2, col3
FROM table_name
WHERE
(
    Col1 = '38'
    OR Col1 LIKE '%,38'
    OR Col1 LIKE '%,38,%'
    OR Col1 LIKE '38,%'
)
OR
(
    col2 = '38'
    OR col2 LIKE '%,38'
    OR col2 LIKE '%,38,%'
    OR col2 LIKE '38,%'
)
OR
(
    col3 = '38'
    OR col3 LIKE '%,38'
    OR col3 LIKE '%,38,%'
    OR col3 LIKE '38,%'
)
</code>```

Is there a way make it smarter/shorter/faster?
Thanks.!

答:
You can use the function FIND_IN_SET(). MySQL has a dedicated function FIND_IN_SET() that returns field index if the value is found in a string containing comma-separated values.

Example

```<code>DROP TABLE table_name;

CREATE TABLE table_name
(col1 VARCHAR(100));

INSERT INTO table_name VALUES ('38');
INSERT INTO table_name VALUES ('37,38,39');
INSERT INTO table_name VALUES ('37,38');
INSERT INTO table_name VALUES ('38,39');
INSERT INTO table_name VALUES ('48');

SELECT col1
FROM table_name
WHERE FIND_IN_SET(38, col1) > 0;
</code>```

Your solution would be

```<code>SELECT col1, col2, col3
FROM table_name
WHERE FIND_IN_SET(38, col1) > 0
  OR FIND_IN_SET(38, col2) > 0
  OR FIND_IN_SET(38, col3) > 0 ;
</code>```

Title: Combine multiple OR and LIKE mySql

Body:
I understand that LIKE can not be used in inside IN clause from here.

My table has col1, col2, col3 columns.

How can I find multiple values in multiple columns using LIKE operator.
Currently my query is:

SELECT col1, col2, col3
FROM table_name
WHERE
(
    Col1 = '38'
    OR Col1 LIKE '%,38'
    OR Col1 LIKE '%,38,%'
    OR Col1 LIKE '38,%'
)
OR
(
    col2 = '38'
    OR col2 LIKE '%,38'
    OR col2 LIKE '%,38,%'
    OR col2 LIKE '38,%'
)
OR
(
    col3 = '38'
    OR col3 LIKE '%,38'
    OR col3 LIKE '%,38,%'
    OR col3 LIKE '38,%'
)

Is there a way make it smarter/shorter/faster?
Thanks.!

Body:
You can use the function FIND_IN_SET(). MySQL has a dedicated function FIND_IN_SET() that returns field index if the value is found in a string containing comma-separated values.

Example

DROP TABLE table_name;

CREATE TABLE table_name
(col1 VARCHAR(100));

INSERT INTO table_name VALUES ('38');
INSERT INTO table_name VALUES ('37,38,39');
INSERT INTO table_name VALUES ('37,38');
INSERT INTO table_name VALUES ('38,39');
INSERT INTO table_name VALUES ('48');

SELECT col1
FROM table_name
WHERE FIND_IN_SET(38, col1) > 0;

Your solution would be

SELECT col1, col2, col3
FROM table_name
WHERE FIND_IN_SET(38, col1) > 0
  OR FIND_IN_SET(38, col2) > 0
  OR FIND_IN_SET(38, col3) > 0 ;


答:
That's not how regex works. I'd suggest you read more about it if you really want to use it.

For your needs, the in keyword would be more appropriate. It returns True if the substring is in the string, or False if it isn't. You could chain those with and and or commands, or you could do something like this:

```<code>contents_text = content.read()
if any(word in contents_text for word in ['ata de audiência', 'termo de audiência'])
    and all(word in context_text for word in ['inconcilia', 'reclamada', 'reclamante'])
    and 'sentença' not in context_text:
        key_content = True
</code>```

Title: Regex using the AND NOT operator

Body:
That's not how regex works. I'd suggest you read more about it if you really want to use it.

For your needs, the in keyword would be more appropriate. It returns True if the substring is in the string, or False if it isn't. You could chain those with and and or commands, or you could do something like this:

contents_text = content.read()
if any(word in contents_text for word in ['ata de audiência', 'termo de audiência'])
    and all(word in context_text for word in ['inconcilia', 'reclamada', 'reclamante'])
    and 'sentença' not in context_text:
        key_content = True


问:
Use multiline regex on cat output
I've the following file queries.sql that contains a number of queries, structured like this:

```<code>/* Query 1 */
SELECT cab_type_id,
       Count(*)
FROM   trips
GROUP  BY 1;

/* Query 2 */
SELECT passenger_count,
       Avg(total_amount)
FROM   trips
GROUP  BY 1;

/* Query 3 */
SELECT passenger_count,
       Extract(year FROM pickup_datetime),
       Count(*)
FROM   trips
GROUP  BY 1,
          2;
</code>```

Then I've written a regex, that finds all those queries in the file:

```<code>/\*[^\*]*\*/[^;]*;
</code>```

What I'd like to achieve is the following:

Select all the queries with the regex.

Prefix each query with EXPLAIN ANALYZE

Execute each query and output the results to a new file. That means, query 1 will create a file q1.txt with the corresponding output, query 2 create q2.txt etc.

One of my main challenges (there are no problems, right? ;-)) is, that I'm rather unfamiliar with the linux bash I've to use.

I tried cat queries.sql | grep '/\*[^\*]*\*/[^;]*;' but that doesn't return anything.

So a solution could look like:

```<code>count = 0
for query in (cat queries.sql | grep 'somehow-here-comes-my-regex') do
    count = $count+1
    query = 'EXPLAIN ANALYZE '+query
    psql -U postgres -h localhost -d nyc-taxi-data -c query > 'q'$count'.txt'
</code>```

Except from: that doesn't work and I don't know how to make it work.

答:
It sounds like this is what you're looking for:

```<code>awk -v RS= -v ORS='\0' '{print "EXPLAIN ANALYZE", $0}' queries.sql |
while IFS= read -r -d '' query; do
    psql -U postgres -h localhost -d nyc-taxi-data -c "$query" > "q$((++count)).txt"
do
</code>```

The awk statement outputs each query as a NUL-terminated string, the shell loop reads it as such one at a time and calls psql on it. Simple, robust, efficient, etc...

Title: Use multiline regex on cat output

Body:
I've the following file queries.sql that contains a number of queries, structured like this:

/* Query 1 */
SELECT cab_type_id,
       Count(*)
FROM   trips
GROUP  BY 1;

/* Query 2 */
SELECT passenger_count,
       Avg(total_amount)
FROM   trips
GROUP  BY 1;

/* Query 3 */
SELECT passenger_count,
       Extract(year FROM pickup_datetime),
       Count(*)
FROM   trips
GROUP  BY 1,
          2;

Then I've written a regex, that finds all those queries in the file:

/\*[^\*]*\*/[^;]*;

What I'd like to achieve is the following:

Select all the queries with the regex.

Prefix each query with EXPLAIN ANALYZE

Execute each query and output the results to a new file. That means, query 1 will create a file q1.txt with the corresponding output, query 2 create q2.txt etc.

One of my main challenges (there are no problems, right? ;-)) is, that I'm rather unfamiliar with the linux bash I've to use.

I tried cat queries.sql | grep '/\*[^\*]*\*/[^;]*;' but that doesn't return anything.

So a solution could look like:

count = 0
for query in (cat queries.sql | grep 'somehow-here-comes-my-regex') do
    count = $count+1
    query = 'EXPLAIN ANALYZE '+query
    psql -U postgres -h localhost -d nyc-taxi-data -c query > 'q'$count'.txt'

Except from: that doesn't work and I don't know how to make it work.

Body:
It sounds like this is what you're looking for:

awk -v RS= -v ORS='\0' '{print "EXPLAIN ANALYZE", $0}' queries.sql |
while IFS= read -r -d '' query; do
    psql -U postgres -h localhost -d nyc-taxi-data -c "$query" > "q$((++count)).txt"
do

The awk statement outputs each query as a NUL-terminated string, the shell loop reads it as such one at a time and calls psql on it. Simple, robust, efficient, etc...