问:
C# DO While loop - Hangman
I'm in the process of learning to code using C#. I have not been able to figure out why my loop won't end after 10 entries into my Hangman program, although the program works if set at a lesser number such as 6. I'm using a do while loop, and, when set to 10, I keep getting what seems to be an infinite loop, as it just keeps repeating and not ending as expected. I have no compiler errors. This is an assignment. Any help is appreciated. Here is the code I have wrote:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace hangman_projectW4
{
    class Program
    {
        static void Main(string[] args)
        {
            //variable list
            char letter0 = 'k';
            char letter1 = 'i';
            char letter2 = 'd';
            char letter3 = 'd';
            char letter4 = 'e';
            char letter5 = 'r';
            char letter;
            int score = 0;
            string user = "";

            //inputs inputs
            Console.ForegroundColor = ConsoleColor.Green;
            user = Console.ReadLine();
            Console.WriteLine("Hi! Welcome to Hangman.");
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("Player, please enter a letter at prompt.");
            Console.Write("_________________________________________________________________");
            user = Console.ReadLine();
            Console.ForegroundColor = ConsoleColor.Green;

            do
            {
            Console.WriteLine("Please enter a letter: ");
            letter = char.Parse(Console.ReadLine());

            user = Console.ReadLine();
            if (letter == letter0 || letter == letter1 || letter == letter2 || letter == letter3 || letter == letter4 || letter == letter5)
            {
                Console.WriteLine("You guessed correctly!");

            }
            else
            {
                Console.WriteLine("Incorrect. Try Again.");
                score++;
            }

            user = Console.ReadLine();
            Console.WriteLine("Please enter a letter: ");
            letter = char.Parse(Console.ReadLine());

            user = Console.ReadLine();
            if (letter == letter0 || letter == letter1 || letter == letter2 || letter == letter3 || letter == letter4 || letter == letter5)
            {
                Console.WriteLine("You guessed correctly!");

            }
            else
            {
                Console.WriteLine("Incorrect. Try Again.");
                score++;
            }

            user = Console.ReadLine();
            Console.WriteLine("Please enter a letter: ");
            letter = char.Parse(Console.ReadLine());

            user = Console.ReadLine();
            if (letter == letter0 || letter == letter1 || letter == letter2 || letter == letter3 || letter == letter4 || letter == letter5)
            {
                Console.WriteLine("You guessed correctly!");

            }
            else
            {
                Console.WriteLine("Incorrect. Try Again.");
                score++;
            }

            user = Console.ReadLine();
            Console.WriteLine("Please enter a letter: ");
            letter = char.Parse(Console.ReadLine());

            user = Console.ReadLine();
            if (letter == letter0 || letter == letter1 || letter == letter2 || letter == letter3 || letter == letter4 || letter == letter5)
            {
                Console.WriteLine("You guessed correctly!");

            }
            else
            {
                Console.WriteLine("Incorrect. Try Again.");
                score++;
            }

            user = Console.ReadLine();
            Console.WriteLine("Please enter a letter: ");
            letter = char.Parse(Console.ReadLine());

            user = Console.ReadLine();
            if (letter == letter0 || letter == letter1 || letter == letter2 || letter == letter3 || letter == letter4 || letter == letter5)
            {
                Console.WriteLine("You guessed correctly!");

            }
            else
            {
                Console.WriteLine("Incorrect. Try Again.");
                score++;
            }

            user = Console.ReadLine();
            Console.WriteLine("Please enter a letter: ");
            letter = char.Parse(Console.ReadLine());

            user = Console.ReadLine();
            if (letter == letter0 || letter == letter1 || letter == letter2 || letter == letter3 || letter == letter4 || letter == letter5)
            {
                Console.WriteLine("You guessed correctly!");

            }
            else
            {
                Console.WriteLine("Incorrect. Try Again.");
                score++;
            }

            user = Console.ReadLine();
            Console.WriteLine("Please enter a letter: ");
            letter = char.Parse(Console.ReadLine());

            user = Console.ReadLine();
            if (letter == letter0 || letter == letter1 || letter == letter2 || letter == letter3 || letter == letter4 || letter == letter5)
            {
                Console.WriteLine("You guessed correctly!");

            }
            else
            {
                Console.WriteLine("Incorrect. Try Again.");
                score++;
            }

            user = Console.ReadLine();
            Console.WriteLine("Please enter a letter: ");
            letter = char.Parse(Console.ReadLine());

            user = Console.ReadLine();
            if (letter == letter0 || letter == letter1 || letter == letter2 || letter == letter3 || letter == letter4 || letter == letter5)
            {
                Console.WriteLine("You guessed correctly!");

            }
            else
            {
                Console.WriteLine("Incorrect. Try Again.");
                score++;
            }

            user = Console.ReadLine();
            Console.WriteLine("Please enter a letter: ");
            letter = char.Parse(Console.ReadLine());

            user = Console.ReadLine();
            if (letter == letter0 || letter == letter1 || letter == letter2 || letter == letter3 || letter == letter4 || letter == letter5)
            {
                Console.WriteLine("You guessed correctly!");

            }
            else
            {
                Console.WriteLine("Incorrect. Try Again.");
                score++;
            }

            user = Console.ReadLine();
            Console.WriteLine("Please enter a letter: ");
            letter = char.Parse(Console.ReadLine());

            user = Console.ReadLine();
            if (letter == letter0 || letter == letter1 || letter == letter2 || letter == letter3 || letter == letter4 || letter == letter5)
            {
                Console.WriteLine("You guessed correctly!");

            }
            else
            {
                Console.WriteLine("Incorrect. Try Again.");
                score++;
            }
            }while (score <= 10);

            //outputs
            user = Console.ReadLine();
            user = Console.ReadLine();
            Console.Write("_________________________________________________________________");
            user = Console.ReadLine();
            Console.Write("Guessed Incorrectly: " + score);
            Console.ReadLine();
            Console.ReadLine();
            Console.Write("Thank you for playing Hangman.");
            Console.ReadLine();
        }
    }
}
</code>```

Also, if there is a better way to write the code so that I'm not repeating the if else ten times...pointers would be great! Thanks.

答:
If you try hard enough it will end. Once you've reached your score of 11 or more, your code may just continue and continue asking for another try. Stop copying code. Be smarter and minimize your code! Your loop repeats the same thing over and over again without even checking whether you have already reached more than 10 points (score).

Shorten your loop to something like this:

```<code>do
{
    Console.WriteLine("Please enter a letter: ");
    letter = char.Parse(Console.ReadLine());

    if (letter == letter0 ||
        letter == letter1 ||
        letter == letter2 ||
        letter == letter3 ||
        letter == letter4 ||
        letter == letter5)
    {
        Console.WriteLine("You guessed correctly!");
    }
    else
    {
        Console.WriteLine("Incorrect. Try Again.");
        score++;
    }
} while (score <= 10);
</code>```

Next step is to add all your letters to a collection or list and shorten your if statement. ;-)

Title: C# DO While loop - Hangman

Body:
I'm in the process of learning to code using C#. I have not been able to figure out why my loop won't end after 10 entries into my Hangman program, although the program works if set at a lesser number such as 6. I'm using a do while loop, and, when set to 10, I keep getting what seems to be an infinite loop, as it just keeps repeating and not ending as expected. I have no compiler errors. This is an assignment. Any help is appreciated. Here is the code I have wrote:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace hangman_projectW4
{
    class Program
    {
        static void Main(string[] args)
        {
            //variable list
            char letter0 = 'k';
            char letter1 = 'i';
            char letter2 = 'd';
            char letter3 = 'd';
            char letter4 = 'e';
            char letter5 = 'r';
            char letter;
            int score = 0;
            string user = "";

            //inputs inputs
            Console.ForegroundColor = ConsoleColor.Green;
            user = Console.ReadLine();
            Console.WriteLine("Hi! Welcome to Hangman.");
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("Player, please enter a letter at prompt.");
            Console.Write("_________________________________________________________________");
            user = Console.ReadLine();
            Console.ForegroundColor = ConsoleColor.Green;

            do
            {
            Console.WriteLine("Please enter a letter: ");
            letter = char.Parse(Console.ReadLine());

            user = Console.ReadLine();
            if (letter == letter0 || letter == letter1 || letter == letter2 || letter == letter3 || letter == letter4 || letter == letter5)
            {
                Console.WriteLine("You guessed correctly!");

            }
            else
            {
                Console.WriteLine("Incorrect. Try Again.");
                score++;
            }

            user = Console.ReadLine();
            Console.WriteLine("Please enter a letter: ");
            letter = char.Parse(Console.ReadLine());

            user = Console.ReadLine();
            if (letter == letter0 || letter == letter1 || letter == letter2 || letter == letter3 || letter == letter4 || letter == letter5)
            {
                Console.WriteLine("You guessed correctly!");

            }
            else
            {
                Console.WriteLine("Incorrect. Try Again.");
                score++;
            }

            user = Console.ReadLine();
            Console.WriteLine("Please enter a letter: ");
            letter = char.Parse(Console.ReadLine());

            user = Console.ReadLine();
            if (letter == letter0 || letter == letter1 || letter == letter2 || letter == letter3 || letter == letter4 || letter == letter5)
            {
                Console.WriteLine("You guessed correctly!");

            }
            else
            {
                Console.WriteLine("Incorrect. Try Again.");
                score++;
            }

            user = Console.ReadLine();
            Console.WriteLine("Please enter a letter: ");
            letter = char.Parse(Console.ReadLine());

            user = Console.ReadLine();
            if (letter == letter0 || letter == letter1 || letter == letter2 || letter == letter3 || letter == letter4 || letter == letter5)
            {
                Console.WriteLine("You guessed correctly!");

            }
            else
            {
                Console.WriteLine("Incorrect. Try Again.");
                score++;
            }

            user = Console.ReadLine();
            Console.WriteLine("Please enter a letter: ");
            letter = char.Parse(Console.ReadLine());

            user = Console.ReadLine();
            if (letter == letter0 || letter == letter1 || letter == letter2 || letter == letter3 || letter == letter4 || letter == letter5)
            {
                Console.WriteLine("You guessed correctly!");

            }
            else
            {
                Console.WriteLine("Incorrect. Try Again.");
                score++;
            }

            user = Console.ReadLine();
            Console.WriteLine("Please enter a letter: ");
            letter = char.Parse(Console.ReadLine());

            user = Console.ReadLine();
            if (letter == letter0 || letter == letter1 || letter == letter2 || letter == letter3 || letter == letter4 || letter == letter5)
            {
                Console.WriteLine("You guessed correctly!");

            }
            else
            {
                Console.WriteLine("Incorrect. Try Again.");
                score++;
            }

            user = Console.ReadLine();
            Console.WriteLine("Please enter a letter: ");
            letter = char.Parse(Console.ReadLine());

            user = Console.ReadLine();
            if (letter == letter0 || letter == letter1 || letter == letter2 || letter == letter3 || letter == letter4 || letter == letter5)
            {
                Console.WriteLine("You guessed correctly!");

            }
            else
            {
                Console.WriteLine("Incorrect. Try Again.");
                score++;
            }

            user = Console.ReadLine();
            Console.WriteLine("Please enter a letter: ");
            letter = char.Parse(Console.ReadLine());

            user = Console.ReadLine();
            if (letter == letter0 || letter == letter1 || letter == letter2 || letter == letter3 || letter == letter4 || letter == letter5)
            {
                Console.WriteLine("You guessed correctly!");

            }
            else
            {
                Console.WriteLine("Incorrect. Try Again.");
                score++;
            }

            user = Console.ReadLine();
            Console.WriteLine("Please enter a letter: ");
            letter = char.Parse(Console.ReadLine());

            user = Console.ReadLine();
            if (letter == letter0 || letter == letter1 || letter == letter2 || letter == letter3 || letter == letter4 || letter == letter5)
            {
                Console.WriteLine("You guessed correctly!");

            }
            else
            {
                Console.WriteLine("Incorrect. Try Again.");
                score++;
            }

            user = Console.ReadLine();
            Console.WriteLine("Please enter a letter: ");
            letter = char.Parse(Console.ReadLine());

            user = Console.ReadLine();
            if (letter == letter0 || letter == letter1 || letter == letter2 || letter == letter3 || letter == letter4 || letter == letter5)
            {
                Console.WriteLine("You guessed correctly!");

            }
            else
            {
                Console.WriteLine("Incorrect. Try Again.");
                score++;
            }
            }while (score <= 10);

            //outputs
            user = Console.ReadLine();
            user = Console.ReadLine();
            Console.Write("_________________________________________________________________");
            user = Console.ReadLine();
            Console.Write("Guessed Incorrectly: " + score);
            Console.ReadLine();
            Console.ReadLine();
            Console.Write("Thank you for playing Hangman.");
            Console.ReadLine();
        }
    }
}

Also, if there is a better way to write the code so that I'm not repeating the if else ten times...pointers would be great! Thanks.

Body:
If you try hard enough it will end. Once you've reached your score of 11 or more, your code may just continue and continue asking for another try. Stop copying code. Be smarter and minimize your code! Your loop repeats the same thing over and over again without even checking whether you have already reached more than 10 points (score).

Shorten your loop to something like this:

do
{
    Console.WriteLine("Please enter a letter: ");
    letter = char.Parse(Console.ReadLine());

    if (letter == letter0 ||
        letter == letter1 ||
        letter == letter2 ||
        letter == letter3 ||
        letter == letter4 ||
        letter == letter5)
    {
        Console.WriteLine("You guessed correctly!");
    }
    else
    {
        Console.WriteLine("Incorrect. Try Again.");
        score++;
    }
} while (score <= 10);

Next step is to add all your letters to a collection or list and shorten your if statement. ;-)


来源: stackexchange

问:
calling two js functions one after another using one button
Here is my code, not working please help I want to call two js functions using one submit button.I have tried the below code.But it gives error.

function scrollWin() {

    // First time click
    if (e.name != 'Click') {
        e.name = "Click";

        function scrollWin() {
            window.scrollBy(0, 85);
        }
    }

    // When click it again..
    else if (e.name == 'Click') {
        e.name = "Unclick";

        function myFunction() {
            document.getElementById("demo").innerHTML = "
 Second Click
";
        }
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="button" onclick="scrollWin(); this.style.visibility= 'hidden';
myFunction()" value="Click Me" />

<p id="demo"></p></code>```

答:
You need to define one function which handles this action. It is probably best to store a variable where you can save the state of the clicking. Here is an example:

var clickCount = 0;

function scrollWin(button) {
    // first click
    if (clickCount === 0) {
        window.scrollBy(0, 85);
    }
    // second or more click
    else {
        document.getElementById("demo").innerHTML = "
 Second Click
";
        button.style.display = 'none';
    }
    clickCount++;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="button" onclick="scrollWin(this)" value="Click Me" />

<p id="demo"></p></code>```

ContentLicense: CC BY-SA 3.0

Body:
Here is my code, not working please help I want to call two js functions using one submit button.I have tried the below code.But it gives error.

function scrollWin() {

    // First time click
    if (e.name != 'Click') {
        e.name = "Click";

        function scrollWin() {
            window.scrollBy(0, 85);
        }
    }

    // When click it again..
    else if (e.name == 'Click') {
        e.name = "Unclick";

        function myFunction() {
            document.getElementById("demo").innerHTML = "
 Second Click
";
        }
    }
}

<input type="button" onclick="scrollWin(); this.style.visibility= 'hidden';
myFunction()" value="Click Me" />

Body:
You need to define one function which handles this action. It is probably best to store a variable where you can save the state of the clicking. Here is an example:

var clickCount = 0;

function scrollWin(button) {
    // first click
    if (clickCount === 0) {
        window.scrollBy(0, 85);
    }
    // second or more click
    else {
        document.getElementById("demo").innerHTML = "<h2> Second Click </h2>";
        button.style.display = 'none';
    }
    clickCount++;
}

<input type="button" onclick="scrollWin(this)" value="Click Me" />

<p id="demo"></p>


问:
Throwable not catching include and require
I have a problem. Throwable doesn't return an exception for require or include functions. Is there any way to "fix" it? Code:

```<code>try {
    include 'non-existent-file.php';
    #require 'non-existent-file.php';
} catch (\Throwable $ex) {
    die('include error');
}
</code>```

Thank you in advance for your help.

答:
Have you thought of using file_exists ( string $filename )...

```<code>if ( file_exists('non-existent-file.php') === true)   {
    include 'non-existent-file.php';
}
else {
    die('include error');
}
</code>```

Body:
I have a problem. Throwable doesn't return an exception for require or include functions. Is there any way to "fix" it? Code:

try {
    include 'non-existent-file.php';
    #require 'non-existent-file.php';
} catch (\Throwable $ex) {
    die('include error');
}

Thank you in advance for your help.

Body:
Have you thought of using file_exists ( string $filename )...

if ( file_exists('non-existent-file.php') === true)   {
    include 'non-existent-file.php';
}
else {
    die('include error');
}


问:
Error with datetime insertion
I'm trying to insert a datetime in my table, but I can't figure why it isn't working. I'm running the following query:

```<code>DROP TABLE IF EXISTS dynamic_pricing ;
CREATE TABLE dynamic_pricing(
    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    time_start  TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    time_stop TIMESTAMP NOT NULL,
    change_ratio REAL NOT NULL
    -- day_of_week INT(1)
);

INSERT INTO  dynamic_pricing(id,time_start,time_stop,change_ratio)
VALUES(1,DATETIME('2000-01-01 00:00:00'),DATETIME('2000-01-01 00:00:02'),2);
</code>```

I tried using this, only to get

```<code>ERROR 1064 (42000): You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for the right
syntax to use near '('2000-01-01 00:00:00'),DATETIME('2000-01-01
00:00:02'),2)' at line 2
</code>```

What's wrong with this query?

答:
INSERT INTO  dynamic_pricing(id,time_start,time_stop,change_ratio)
VALUES(1,'2000-01-01 00:00:00','2000-01-01 00:00:02',2);

Title: Error with datetime insertion

Body:
I'm trying to insert a datetime in my table, but I can't figure why it isn't working. I'm running the following query:

DROP TABLE IF EXISTS dynamic_pricing ;
CREATE TABLE dynamic_pricing(
    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    time_start  TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    time_stop TIMESTAMP NOT NULL,
    change_ratio REAL NOT NULL
    -- day_of_week INT(1)
);

INSERT INTO  dynamic_pricing(id,time_start,time_stop,change_ratio)
VALUES(1,DATETIME('2000-01-01 00:00:00'),DATETIME('2000-01-01 00:00:02'),2);

I tried using this, only to get

ERROR 1064 (42000): You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for the right
syntax to use near '('2000-01-01 00:00:00'),DATETIME('2000-01-01
00:00:02'),2)' at line 2

What's wrong with this query?


问:
Twitter API: is it possible to get number of retweets and number of media images?
Is it possible through the Twitter API to get the total number of retweets a user has? Not just on a specific post, but the total number of retweets associated with a specific account? Or alternatively, what fraction of all tweets were retweeted content rather than original posts?

Also, is it possible to get the number of media images associated with an an account? What I mean is, if you go to a user's page, on the lefthand side it will say something like "2,200 Photos and Videos". Thanks!

答:
Not using the official API, no.

The documentation shows only the following "counts"

followers_count

friends_count

listed_count

favourites_count

statuses_count

If you want the number of media, you can scrape the HTML from the user's Twitter page.  Look for the class PhotoRail-headingWithCount

I've not seen anything which shows how many times a user has been retweeted. Where do you see that value?


问:
Data Not inserting into table PHP
The data is not inserting  into another table, here's the code below :

```<code>if (isset($_POST))
    {
        $job = $_POST['jobtitle'];
        $dur = $_POST['duration'];
        $deg = $_POST['requireddegree'];
        $exp = $_POST['experiance'];
        $sal = $_POST['salary'];
        $mark = $_POST['marks'];

        if ( !empty($job) && !empty($dur) && !empty($deg) && !empty($exp) && !empty($sal) && !empty($mark))
        {
            $dur = mysql_real_escape_string($dur);
            $deg= mysql_real_escape_string($deg);
            $exp = mysql_real_escape_string($exp);
            $sal = mysql_real_escape_string($sal);
            $mark = mysql_real_escape_string($mark);
            $job = mysql_real_escape_string($job);

            $query="INSERT INTO jobposting (duration,degree,experiance,salary,marks,Jobtitle) VALUES ('".$dur."','".$deg."','".$exp."','".$sal."','".$mark."','".$job."') ";

            if ($query_run= mysql_query($query))
            {
                header('location : Main.html');
            }
            else
            {
                echo ' Data not Inserted! ';
            }

        }
</code>```

With this it gives me server error or there was an error in CGI script.But when I write the variables in this form '$dur' instead of '".$dur." then the else conditon runs after insert query and displays data is not inserted.

However, i have written the same logic  while inserting data in my another table and it inserts successfully.But there I put '$dur'.

I can't find the problem.Will be glad for your suggestions :)

答:
I can't seem to find any other error by seeing this code expect for

```<code>$query="INSERT INTO jobposting (duration,degree,experiance,salary,marks,Jobtitle) VALUES ('$dur','$deg','$exp','$sal','$mark','$job') ";

//Use ".$job." only for stuff like '".md5($_POST['password'])."' otherwise this creates problem some times.

// Adding this always helps
if(!mysqli_query($con,$query))
 {
  die('error'.mysqli_error($con));
 }
 // in $con = $con=mysqli_connect("localhost","root","");
 else
 {
   if ($query_run= mysql_query($query))
     {
       header('location : Main.html');
      }
    else
    {
      echo ' Data not Inserted! ';
    }

 }
</code>```

I think by making these changes and making sure that your db name and other basic stuff are correct then you should be good to go otherwise, specify your exact error.

Title: Data Not inserting into table PHP

Body:
The data is not inserting  into another table, here's the code below :

if (isset($_POST))
    {
        $job = $_POST['jobtitle'];
        $dur = $_POST['duration'];
        $deg = $_POST['requireddegree'];
        $exp = $_POST['experiance'];
        $sal = $_POST['salary'];
        $mark = $_POST['marks'];

        if ( !empty($job) && !empty($dur) && !empty($deg) && !empty($exp) && !empty($sal) && !empty($mark))
        {
            $dur = mysql_real_escape_string($dur);
            $deg= mysql_real_escape_string($deg);
            $exp = mysql_real_escape_string($exp);
            $sal = mysql_real_escape_string($sal);
            $mark = mysql_real_escape_string($mark);
            $job = mysql_real_escape_string($job);

            $query="INSERT INTO jobposting (duration,degree,experiance,salary,marks,Jobtitle) VALUES ('".$dur."','".$deg."','".$exp."','".$sal."','".$mark."','".$job."') ";

            if ($query_run= mysql_query($query))
            {
                header('location : Main.html');
            }
            else
            {
                echo ' Data not Inserted! ';
            }

        }

With this it gives me server error or there was an error in CGI script.But when I write the variables in this form '$dur' instead of '".$dur." then the else conditon runs after insert query and displays data is not inserted.

However, i have written the same logic  while inserting data in my another table and it inserts successfully.But there I put '$dur'.

I can't find the problem.Will be glad for your suggestions :)

Body:
I can't seem to find any other error by seeing this code expect for

$query="INSERT INTO jobposting (duration,degree,experiance,salary,marks,Jobtitle) VALUES ('$dur','$deg','$exp','$sal','$mark','$job') ";

//Use ".$job." only for stuff like '".md5($_POST['password'])."' otherwise this creates problem some times.

// Adding this always helps
if(!mysqli_query($con,$query))
 {
  die('error'.mysqli_error($con));
 }
 // in $con = $con=mysqli_connect("localhost","root","");
 else
 {
   if ($query_run= mysql_query($query))
     {
       header('location : Main.html');
      }
    else
    {
      echo ' Data not Inserted! ';
    }

 }

I think by making these changes and making sure that your db name and other basic stuff are correct then you should be good to go otherwise, specify your exact error.


答:
You need to get the fundamentals right. A function call will have its own scope and once the scope of a function ends, the variables are destroyed. I think you want to capture a second click for the element.

Don't try declaring a global variable for the same but try to set the elements property on first click which you can access on the second click. read that property on click and then manipulate.

I would suggest you to call the click event as

```<code>onclick="click123(this);"
</code>```

and use this to set the property using setAttribute

Title: calling two js functions one after another using one button

Body:
You need to get the fundamentals right. A function call will have its own scope and once the scope of a function ends, the variables are destroyed. I think you want to capture a second click for the element.

Don't try declaring a global variable for the same but try to set the elements property on first click which you can access on the second click. read that property on click and then manipulate.

I would suggest you to call the click event as

onclick="click123(this);"

and use this to set the property using setAttribute


问:
FileNotFound Exception in FileOutputStream
I'm getting error of FileNotFound. Basically, I'm trying to upload file from client to server.

Please, help me with it.

This is client.java class
package ftppackage;

```<code>import java.net.*;
import java.io.*;

public class Client {

    public static void main (String [] args ) throws IOException {
        Socket socket = new Socket("127.0.0.1",15123);
        File transferFile = new File ("D:\\AsiaAd.wmv");
        byte [] bytearray = new byte [(int)transferFile.length()];
        FileInputStream fin = new FileInputStream(transferFile);
        BufferedInputStream bin = new BufferedInputStream(fin);
        bin.read(bytearray,0,bytearray.length);
        OutputStream os = socket.getOutputStream();
        System.out.println("Sending Files...");
        os.write(bytearray,0,bytearray.length);
        os.flush();
        socket.close();
        System.out.println("File transfer complete");
    }
}
</code>```

And this is my server.java class

```<code>package ftppackage;

import java.net.*;
import java.io.*;

public class Server {

    public static void main (String [] args ) throws IOException {
        int filesize=1022386;
        int bytesRead;
        int currentTot = 0;
        ServerSocket serverSocket = new ServerSocket(15123);
        Socket socket = serverSocket.accept();
        System.out.println("Accepted connection : " + socket);
        byte [] bytearray = new byte [filesize];
        InputStream is = socket.getInputStream();
        FileOutputStream fos = new FileOutputStream("E:\\0\\"); // it is creating new file not copying the one from client
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        bytesRead = is.read(bytearray,0,bytearray.length);
        currentTot = bytesRead;
        do {
            bytesRead = is.read(bytearray, currentTot, (bytearray.length-currentTot));
            if(bytesRead >= 0)
                currentTot += bytesRead;
        } while(bytesRead > -1);
        bos.write(bytearray, 0 , currentTot);
        bos.flush();
        bos.close();
        socket.close();
    }
}
</code>```

Plus, guide me how do add progress bar in it with percentage. I read about SwingWorker here but unable to implement it as I'm totally new with threading concepts.
Thank you for considering my questions.

答: FileNotFoundException is something you will get if you point the File Object to some File which is not existing in that path. it means what ever the file you are trying to upload in not there in the specified path. SO make sure you give a valid path.</p>

Body:
I'm getting error of FileNotFound. Basically, I'm trying to upload file from client to server.

Please, help me with it.

This is client.java class
package ftppackage;

import java.net.*;
import java.io.*;

public class Client {

    public static void main (String [] args ) throws IOException {
        Socket socket = new Socket("127.0.0.1",15123);
        File transferFile = new File ("D:\\AsiaAd.wmv");
        byte [] bytearray = new byte [(int)transferFile.length()];
        FileInputStream fin = new FileInputStream(transferFile);
        BufferedInputStream bin = new BufferedInputStream(fin);
        bin.read(bytearray,0,bytearray.length);
        OutputStream os = socket.getOutputStream();
        System.out.println("Sending Files...");
        os.write(bytearray,0,bytearray.length);
        os.flush();
        socket.close();
        System.out.println("File transfer complete");
    }
}

And this is my server.java class

package ftppackage;

import java.net.*;
import java.io.*;

public class Server {

    public static void main (String [] args ) throws IOException {
        int filesize=1022386;
        int bytesRead;
        int currentTot = 0;
        ServerSocket serverSocket = new ServerSocket(15123);
        Socket socket = serverSocket.accept();
        System.out.println("Accepted connection : " + socket);
        byte [] bytearray = new byte [filesize];
        InputStream is = socket.getInputStream();
        FileOutputStream fos = new FileOutputStream("E:\\0\\"); // it is creating new file not copying the one from client
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        bytesRead = is.read(bytearray,0,bytearray.length);
        currentTot = bytesRead;
        do {
            bytesRead = is.read(bytearray, currentTot, (bytearray.length-currentTot));
            if(bytesRead >= 0)
                currentTot += bytesRead;
        } while(bytesRead > -1);
        bos.write(bytearray, 0 , currentTot);
        bos.flush();
        bos.close();
        socket.close();
    }
}

Plus, guide me how do add progress bar in it with percentage. I read about SwingWorker here but unable to implement it as I'm totally new with threading concepts.
Thank you for considering my questions.


问:
Is there a way to render only after only a complete input? Delaying render() - ReactJS
I have some Controlled Component text inputs for a form:

```<code><input type="text" onChange={(e) => this.props.changeBusiness(e)}/>
</code>```

I also want to render the (above) text input in a separate component - however! It would be nice if I could render it with the COMPLETED text input to give (in my opinion), what would be a better feel.

How might this be implemented? I assume I could have an onBlur
handler that is triggered.

Is there any way to delay the render() till only after the complete text input?

Danke

答:
You have several posibilities.

Create custom Input wrapper around input component, which does trigger "change" event on "complete" change - e.g. on blur. While you typing, parent component won't receive incremental onChange events.

From parent, pass onBlur handler to child input component and as soon, as onBlur handler is triggered, render input's value wherever you wish.

Body:
I have some Controlled Component text inputs for a form:

<input type="text" onChange={(e) => this.props.changeBusiness(e)}/>

I also want to render the (above) text input in a separate component - however! It would be nice if I could render it with the COMPLETED text input to give (in my opinion), what would be a better feel.

How might this be implemented? I assume I could have an onBlur
handler that is triggered.

Is there any way to delay the render() till only after the complete text input?

Danke


问:
wordpress: session_id different in functions.php compared to all other *.php files
I am using php sessions in wordpress.  If I print the session_id from any of several custom php pages I have made, it is the same session_id (so I can access _SESSION variables from any of these pages).  However, if I try to read a session variable in my functions.php file (for shortcode mapping), I cannot access the _SESSION variables because the session_id is different in this file (functions.php) only.  It seems the session is getting unset when running the functions.php file (I don't see anywhere where this is getting done).  I am trying to figure out how to set a global session so all of my files can set/read session variables.  Any thoughts?</p>

答:
It's probably because wordpress is either using a different cookie name, or different cookie settings.

What you want to do is make sure you are on the same domain (you can prefix the domain with a dot to set a cross domain cookie) and are using the same cookie path.


问:
Java Multi-threading : Unexpected result
I am working on a Enterprise application. I am facing some issues while running application in multithreaded environment. I am writing a program in which there is a variable whose value is getting updated(incremented) at very fast rate (for example 10000 updates/persecond). A loop runs for certain iterations and the value of the variable is incremented and stored in HashMap. Once the loop terminates and value the variable in HashMap is printed. I am getting unexpected value of the variable.

Here is demo program (Please read comments for better understanding) :

class test implements Runnable {

    static ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
    static AtomicInteger value_to_be_incremented_stored = new AtomicInteger(0); // variable whose value to be updated
    static AtomicInteger i = new AtomicInteger(0);  // this runs the loop

    @Override
    public void run() {

        for (i.set(0); i.get() < 100000; i.incrementAndGet()) {
            /*
                This loop should run 100000 times and when loop terminates according to me value of variable
                "value_to_be_incremented_stored" should be 100000 as its value is incremented
                100000 times the loop also runs 100000 times.
            */
            System.out.println("Thread > " + Thread.currentThread() + "  " + value_to_be_incremented_stored.incrementAndGet());
            map.put("TC", value_to_be_incremented_stored.intValue());
        }

        System.out.println("Output by Thread  " + Thread.currentThread() + "     " + map.toString());
    }

    public static void main(String[] args) {

        test t1 = new test();
        Thread thread1 = new Thread(t1);
        thread1.setName("Thread 1");

        Thread thread2 = new Thread(t1);
        thread2.setName("Thread 2");

        Thread thread3 = new Thread(t1);
        thread3.setName("Thread 3");

        Thread thread4 = new Thread(t1);
        thread4.setName("Thread 4");

        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();

    }
}
```

Output (it varies) :

Issue :
I am running loop for 100000 times (i.get() < 100000) then how come value of variable value_to_be_incremented_stored becomes more than 100000.

答:
Your "demo program" suffers from two simultaneous defects.

Defect #1 is the i.set( 0 ) pointed out by tsolakp.  You say you fixed that but you are still getting a value of more than 100000.  I also tried it and indeed, the final value is still larger than 100000.

I modified the program to be able to create an arbitrary number of threads, and I tried with 3, 10, and 20 threads.  I got a final number of 100003, 100009, and 100019 respectively. See a pattern? So:

Defect #2 is that on the last iteration, when the value of i is 99999, the expression i.get() < 100000 is true for all threads, so all threads proceed to execute once more.  The i.incrementAndGet() clause is visually sitting right next to i.get() < 1000000; but it does not get executed until the end of the loop.

So, all threads get a chance to increment i once more after the last iteration.

Body:
I am working on a Enterprise application. I am facing some issues while running application in multithreaded environment. I am writing a program in which there is a variable whose value is getting updated(incremented) at very fast rate (for example 10000 updates/persecond). A loop runs for certain iterations and the value of the variable is incremented and stored in HashMap. Once the loop terminates and value the variable in HashMap is printed. I am getting unexpected value of the variable.

Here is demo program (Please read comments for better understanding) :

class test implements Runnable {

    static ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
    static AtomicInteger value_to_be_incremented_stored = new AtomicInteger(0); // variable whose value to be updated
    static AtomicInteger i = new AtomicInteger(0);  // this runs the loop

    @Override
    public void run() {

        for (i.set(0); i.get() < 100000; i.incrementAndGet()) {
            /*
                This loop should run 100000 times and when loop terminates according to me value of variable
                "value_to_be_incremented_stored" should be 100000 as its value is incremented
                100000 times the loop also runs 100000 times.
            */
            System.out.println("Thread > " + Thread.currentThread() + "  " + value_to_be_incremented_stored.incrementAndGet());
            map.put("TC", value_to_be_incremented_stored.intValue());
        }

        System.out.println("Output by Thread  " + Thread.currentThread() + "     " + map.toString());
    }

    public static void main(String[] args) {

        test t1 = new test();
        Thread thread1 = new Thread(t1);
        thread1.setName("Thread 1");

        Thread thread2 = new Thread(t1);
        thread2.setName("Thread 2");

        Thread thread3 = new Thread(t1);
        thread3.setName("Thread 3");

        Thread thread4 = new Thread(t1);
        thread4.setName("Thread 4");

        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();

    }
}

Output (it varies) :

Issue :
I am running loop for 100000 times (i.get() < 100000) then how come value of variable value_to_be_incremented_stored becomes more than 100000.

ContentLicense: CC BY-SA 4.0


问:
How to check for overlapping intervals when entering data in SQLite3?
I need to place a check in my SQLite3 database that ensures that the user cannot enter data with overlapping intervals.

For example:

```<code>hole #  Sample From    To
1          1     1      2
1          2     2      3
1          3    2.2    2.9
</code>```

With the example above I have checks in place that will catch any duplicate 'From' in each hole, but sample #3 is not a duplicate so it will not be caught, but it is an overlapping interval.

I don't want this for a query, but rather as a data-entry check built into the table.

So far I've tried adding a constraint check of ('From' NOT BETWEEN 'From' and 'To) but to no avail. I don't understand whether the check is trying to be applied on a row by row basis, which I want, or on a primary key basis.

Here is the table definition that I am trying:

```<code> CREATE TABLE assay (
    BHID       TEXT    NOT NULL
                       CONSTRAINT [Check BHID] REFERENCES collar (BHID) ON DELETE CASCADE
                                                                        ON UPDATE CASCADE
                                                                        MATCH SIMPLE,
    [Sample #] TEXT    UNIQUE,
    [FROM]     NUMERIC NOT NULL
                       CONSTRAINT [Interval Check] CHECK ( ("TO" > "FROM") ),
    [TO]       NUMERIC NOT NULL,
    Ag         NUMERIC CONSTRAINT [Max Silver] CHECK ( (Ag < 1000) ),
    Zn         NUMERIC CONSTRAINT [Max Zinc] CHECK ( (Zn < 50) ),
    Pb         NUMERIC CONSTRAINT [Max Lead] CHECK ( (Pb < 50) ),
    Fe         NUMERIC,
    PRIMARY KEY (
        BHID,
        [FROM]
    )
);
</code>```

And here is the table with the updated constraint (before commiting):

```<code>CREATE TABLE assay (
    BHID       TEXT    NOT NULL
                       CONSTRAINT [Check BHID] REFERENCES collar (BHID) ON DELETE CASCADE
                                                                        ON UPDATE CASCADE
                                                                        MATCH SIMPLE,
    [Sample #] TEXT    UNIQUE,
    [FROM]     NUMERIC NOT NULL
                       CONSTRAINT [Interval Check] CHECK ( ("TO" > "FROM") )
                       CONSTRAINT [Not Between] CHECK ( ('From' NOT BETWEEN 'From' AND 'To') ),
    [TO]       NUMERIC NOT NULL,
    Ag         NUMERIC CONSTRAINT [Max Silver] CHECK ( (Ag < 1000) ),
    Zn         NUMERIC CONSTRAINT [Max Zinc] CHECK ( (Zn < 50) ),
    Pb         NUMERIC CONSTRAINT [Max Lead] CHECK ( (Pb < 50) ),
    Fe         NUMERIC,
    PRIMARY KEY (
        BHID,
        [FROM]
    )
);
</code>```

I deleted the data row with the conflicting data (From: 2.2, To: 2.9) and committed the change before trying to add the new constraint check. But it won't let me commit the new constraint, I believe because it is trying to apply it to the entire column.

So my question should be this: Is there a way to apply a constraint check on a row by row basis in sql?

答:
In SQL, double quotes are used to quote table and column names; single quotes are used for string values. So the check

```<code>('FROM' NOT BETWEEN 'FROM' AND 'TO')
</code>```

just compares these constant string values. This check always fails.

Anyway, a CHECK constraint can access only values in the current row.
To be able to look at other rows, you have to use a trigger:

```<code>CREATE TRIGGER no_overlaps
BEFORE INSERT ON Assay
WHEN EXISTS (SELECT *
             FROM Assay
             WHERE "From" <= NEW."To"
               AND "To" >= NEW."From")
BEGIN
    SELECT RAISE(FAIL, "overlapping intervals");
END;
</code>```

Body:
I need to place a check in my SQLite3 database that ensures that the user cannot enter data with overlapping intervals.

For example:

hole #  Sample From    To
1          1     1      2
1          2     2      3
1          3    2.2    2.9

With the example above I have checks in place that will catch any duplicate 'From' in each hole, but sample #3 is not a duplicate so it will not be caught, but it is an overlapping interval.

I don't want this for a query, but rather as a data-entry check built into the table.

So far I've tried adding a constraint check of ('From' NOT BETWEEN 'From' and 'To) but to no avail. I don't understand whether the check is trying to be applied on a row by row basis, which I want, or on a primary key basis.

Here is the table definition that I am trying:

 CREATE TABLE assay (
    BHID       TEXT    NOT NULL
                       CONSTRAINT [Check BHID] REFERENCES collar (BHID) ON DELETE CASCADE
                                                                        ON UPDATE CASCADE
                                                                        MATCH SIMPLE,
    [Sample #] TEXT    UNIQUE,
    [FROM]     NUMERIC NOT NULL
                       CONSTRAINT [Interval Check] CHECK ( ("TO" > "FROM") ),
    [TO]       NUMERIC NOT NULL,
    Ag         NUMERIC CONSTRAINT [Max Silver] CHECK ( (Ag < 1000) ),
    Zn         NUMERIC CONSTRAINT [Max Zinc] CHECK ( (Zn < 50) ),
    Pb         NUMERIC CONSTRAINT [Max Lead] CHECK ( (Pb < 50) ),
    Fe         NUMERIC,
    PRIMARY KEY (
        BHID,
        [FROM]
    )
);

And here is the table with the updated constraint (before commiting):

CREATE TABLE assay (
    BHID       TEXT    NOT NULL
                       CONSTRAINT [Check BHID] REFERENCES collar (BHID) ON DELETE CASCADE
                                                                        ON UPDATE CASCADE
                                                                        MATCH SIMPLE,
    [Sample #] TEXT    UNIQUE,
    [FROM]     NUMERIC NOT NULL
                       CONSTRAINT [Interval Check] CHECK ( ("TO" > "FROM") )
                       CONSTRAINT [Not Between] CHECK ( ('From' NOT BETWEEN 'From' AND 'To') ),
    [TO]       NUMERIC NOT NULL,
    Ag         NUMERIC CONSTRAINT [Max Silver] CHECK ( (Ag < 1000) ),
    Zn         NUMERIC CONSTRAINT [Max Zinc] CHECK ( (Zn < 50) ),
    Pb         NUMERIC CONSTRAINT [Max Lead] CHECK ( (Pb < 50) ),
    Fe         NUMERIC,
    PRIMARY KEY (
        BHID,
        [FROM]
    )
);

I deleted the data row with the conflicting data (From: 2.2, To: 2.9) and committed the change before trying to add the new constraint check. But it won't let me commit the new constraint, I believe because it is trying to apply it to the entire column.

So my question should be this: Is there a way to apply a constraint check on a row by row basis in sql?

Body:
In SQL, double quotes are used to quote table and column names; single quotes are used for string values. So the check

('FROM' NOT BETWEEN 'FROM' AND 'TO')

just compares these constant string values. This check always fails.

Anyway, a CHECK constraint can access only values in the current row.
To be able to look at other rows, you have to use a trigger:

CREATE TRIGGER no_overlaps
BEFORE INSERT ON Assay
WHEN EXISTS (SELECT *
             FROM Assay
             WHERE "From" <= NEW."To"
               AND "To" >= NEW."From")
BEGIN
    SELECT RAISE(FAIL, "overlapping intervals");
END;


问:
SyntaxError: missing ) after argument list in cart.js
I'm getting

SyntaxError: missing ) after argument list | in cart.js file

```<code>// Purchase button.
        add('<button onclick="yaCounter44762137.reachGoal('zakaz'); return true;" class="btn btn-primary cart-purchase-button" type="button"></button>')
</code>```

答:
Or you can change the zakaz in double quotes. It would make things a lot easier to do. </p>

```<code>add('<button onclick="yaCounter44762137.reachGoal("zakaz"); return true;" class="btn btn-primary cart-purchase-button" type="button"></button>');
</code>```

<p>Or you can even use one double quote and put everything else in a single quote: </p>

```<code>add("<button onclick=yaCounter44762137.reachGoal('zakaz'); return true;' class='btn btn-primary cart-purchase-button' type='button'></button>");
</code>```

Body:
I'm getting

SyntaxError: missing ) after argument list | in cart.js file

// Purchase button.
        add('<button onclick="yaCounter44762137.reachGoal('zakaz'); return true;" class="btn btn-primary cart-purchase-button" type="button"></button>')

Body:
Or you can change the zakaz in double quotes. It would make things a lot easier to do.

add('<button onclick="yaCounter44762137.reachGoal("zakaz"); return true;" class="btn btn-primary cart-purchase-button" type="button"></button>');

Or you can even use one double quote and put everything else in a single quote:

add("<button onclick=yaCounter44762137.reachGoal('zakaz'); return true;' class='btn btn-primary cart-purchase-button' type='button'></button>");


答:
I think this accomplishes what you described. You need to pass in the event of the button click and read the button text, but e.name probably wont work you'll need to use innerHTML or textContent. Then you can either perform the operations or call the functions you wish to execute depending on the button text which changes after the 2nd click.

         function scrollWin(e) {

            //First time click
            if(e.textContent != 'Click'){
                e.textContent = "Click";
                window.scrollBy(0, 85);
            }

            else if(e.textContent == 'Click'){
                e.textContent = "Unclick";
                document.getElementById("demo").innerHTML = "
 Second Click
";
            }//end else
        }//end function```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button onclick="scrollWin(this)">Click</button>
<div id="demo"></div></code>```

Body:
I think this accomplishes what you described. You need to pass in the event of the button click and read the button text, but e.name probably wont work you'll need to use innerHTML or textContent. Then you can either perform the operations or call the functions you wish to execute depending on the button text which changes after the 2nd click.

         function scrollWin(e) {

            //First time click
            if(e.textContent != 'Click'){
                e.textContent = "Click";
                window.scrollBy(0, 85);
            }

            else if(e.textContent == 'Click'){
                e.textContent = "Unclick";
                document.getElementById("demo").innerHTML = "<h2> Second Click </h2>";
            }//end else
        }//end function

<button onclick="scrollWin(this)">Click</button>
<div id="demo"></div>


问:
binding two different transforms together in silverlight 4
I try to bind a translateTransform and a compositeTransform together in silverlight 4 in the code (c#). I can't do this in xaml because the UIelements are loaded dynamically. I just need the Xoffset. The compositeTransform is the source. I have the flowing code, but it doesn't work:

```<code>TranslateTransform trans = new TranslateTransform();
Binding transBind = new Binding("Value");
transBind.Source = ((CompositeTransform)SchedulePanel.RenderTransform);
BindingOperations.SetBinding(trans, TranslateTransform.XProperty, transBind);
line.TextChannelName.RenderTransform = trans;
</code>```

Thanks

答:
Since TranslateTransform is not a FrameworkElement, in order to be the target of a binding it must meet one of these conditions (from MSDN):

In Silverlight 4, the target can also be a DependencyProperty of a DependencyObject in the following cases:

The DependencyObject is the value of a property of a FrameworkElement.

The DependencyObject is in a collection that is the value of a FrameworkElement property (for example, the Resources property).

The DependencyObject is in a DependencyObjectCollection.

So try setting the trans TranslateTransform as the Transform of TextChannelName before setting the binding so that at the moment of setting the binsing, the target.

Try:

```<code>TranslateTransform trans = new TranslateTransform();
line.TextChannelName.RenderTransform = trans;

Binding transBind = new Binding("Value");
transBind.Source = ((CompositeTransform)SchedulePanel.RenderTransform);
BindingOperations.SetBinding(trans, TranslateTransform.XProperty, transBind);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I try to bind a translateTransform and a compositeTransform together in silverlight 4 in the code (c#). I can't do this in xaml because the UIelements are loaded dynamically. I just need the Xoffset. The compositeTransform is the source. I have the flowing code, but it doesn't work:

TranslateTransform trans = new TranslateTransform();
Binding transBind = new Binding("Value");
transBind.Source = ((CompositeTransform)SchedulePanel.RenderTransform);
BindingOperations.SetBinding(trans, TranslateTransform.XProperty, transBind);
line.TextChannelName.RenderTransform = trans;

Thanks

Body:
Since TranslateTransform is not a FrameworkElement, in order to be the target of a binding it must meet one of these conditions (from MSDN):

In Silverlight 4, the target can also be a DependencyProperty of a DependencyObject in the following cases:

The DependencyObject is the value of a property of a FrameworkElement.

The DependencyObject is in a collection that is the value of a FrameworkElement property (for example, the Resources property).

The DependencyObject is in a DependencyObjectCollection.

So try setting the trans TranslateTransform as the Transform of TextChannelName before setting the binding so that at the moment of setting the binsing, the target.

Try:

TranslateTransform trans = new TranslateTransform();
line.TextChannelName.RenderTransform = trans;

Binding transBind = new Binding("Value");
transBind.Source = ((CompositeTransform)SchedulePanel.RenderTransform);
BindingOperations.SetBinding(trans, TranslateTransform.XProperty, transBind);


问:
PHP Time: get next minute/hour what's divisible by five
I need a code what detect the current time and give me the following time what is divisible by five.

For example: It's: 06 03, 2017 21:22:23 , give me 06 03, 2017 21:25:00 in php.
I have no any idea to starting. Is there any code or solution to do this?

答:
Find the difference between 5 and modulo of current minutes. Then add this to current time. Example:

```<code>$now = intval(date('i'));
$minutesToAdd = 5 - $now % 5;
$nextTime = date('m d, Y H:i:00', strtotime("+$minutesToAdd minutes"));
echo $nextTime;
</code>```

Maybe it's not perfect solution, but shuld work, also for cases like 13:59 (modulo is 4, 5-4=1, 59+1=00).

Body:
Find the difference between 5 and modulo of current minutes. Then add this to current time. Example:

$now = intval(date('i'));
$minutesToAdd = 5 - $now % 5;
$nextTime = date('m d, Y H:i:00', strtotime("+$minutesToAdd minutes"));
echo $nextTime;

Maybe it's not perfect solution, but shuld work, also for cases like 13:59 (modulo is 4, 5-4=1, 59+1=00).


问:
HTML5/JQuery mobile input type date , How to prevent future dates
I am using Jquery mobile in my Html5 application.I have created datepicker with input type date tag like :

```<code> <input name="" id="mydate" placeholder="" value="" type="date"  data-mini="true">
</code>```

Now I want to disable future dates. Please suggest me workaround for this.
Note :I cannot use JQueryUI in my project.So cant use JqueryUI datepicker.

答:
https://www.w3schools.com/html/html_form_input_types.asp

You can use max property and set this value using js

Body:
I am using Jquery mobile in my Html5 application.I have created datepicker with input type date tag like :

 <input name="" id="mydate" placeholder="" value="" type="date"  data-mini="true">

Now I want to disable future dates. Please suggest me workaround for this.
Note :I cannot use JQueryUI in my project.So cant use JqueryUI datepicker.


问:
Identifying Exception in thread "main" java.lang.StackOverflowError
My code is below, I am trying to recursively call my binary search function but keep getting this Exception. I am trying to identify the source of the issue. Keep in mind i've excluded my code for creating the array list for simplicity and because i know they are functional.</p>

```<code>  import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.math.*;
public class nickclass {

public static void main(String[] args) {

for(int i = 0; i <(int)listTest.size();i++)
   {
  binarySearchHelp(listTest2,(String)listTest.get(i),0,listTest2.size());
 }

void binarySearchHelp(ArrayList list, String value, int left, int right) {

    if (left > right)
        System.exit(0);

    int middle = (int) Math.floor(list.size()/2);

    if (((String) list.get(middle)).compareTo(value) == 0)
        System.out.println(list.get(middle));

    else if (((String) list.get(middle)).compareTo(value) > 0)
         binarySearchHelp(list, value, left, middle - 1);

    else
         binarySearchHelp(list, value, middle + 1, right);

  }
}
}
</code>```

答:
The recursive call is never terminating (only when all memory is used) because middle is always the middle of the list, but it should be the middle between left and right:

```<code>middle = (left + right) / 2;
</code>```

I would also check that the interval (left-right) is big enough to be divided or if the algorithm can stop... and System.exit is kind of brutal, you really want to stop the virtual machine without any message?

Body:
My code is below, I am trying to recursively call my binary search function but keep getting this Exception. I am trying to identify the source of the issue. Keep in mind i've excluded my code for creating the array list for simplicity and because i know they are functional.

  import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.math.*;
public class nickclass {

public static void main(String[] args) {

for(int i = 0; i <(int)listTest.size();i++)
   {
  binarySearchHelp(listTest2,(String)listTest.get(i),0,listTest2.size());
 }

void binarySearchHelp(ArrayList list, String value, int left, int right) {

    if (left > right)
        System.exit(0);

    int middle = (int) Math.floor(list.size()/2);

    if (((String) list.get(middle)).compareTo(value) == 0)
        System.out.println(list.get(middle));

    else if (((String) list.get(middle)).compareTo(value) > 0)
         binarySearchHelp(list, value, left, middle - 1);

    else
         binarySearchHelp(list, value, middle + 1, right);

  }
}
}

Body:
The recursive call is never terminating (only when all memory is used) because middle is always the middle of the list, but it should be the middle between left and right:

middle = (left + right) / 2;

I would also check that the interval (left-right) is big enough to be divided or if the algorithm can stop... and System.exit is kind of brutal, you really want to stop the virtual machine without any message?


问:
Apache HttpClient receiving "406 Not Acceptable" error
I'm writing a podcast downloader using Java and Apache HttpClient.  It works fine for most RSS feeds, but this one is failing with a "406 Not Acceptable" error.

The link is http://sqrpt.com/feed/podcast/

The response I get back is:

```<code>HttpResponseProxy{HTTP/1.1 406 Not Acceptable [Server: nginx/1.12.0, Date: Sat, 03 Jun 2017 03:40:17 GMT, Content-Type: text/html; charset=iso-8859-1, Content-Length: 226, Connection: keep-alive] ResponseEntityProxy{[Content-Type: text/html; charset=iso-8859-1,Content-Length: 226,Chunked: false]}}
</code>```

My Java code is:

```<code>   HttpClient httpClient = HttpClients.custom().setUserAgent( "Mozilla/5.0" ).build();
   HttpGet httpGet = new HttpGet( url );
   httpGet.setHeader( "Accept", "*/*" );
   httpGet.setHeader( "Accept-Encoding", "gzip, deflate, sdch" );
   httpGet.setHeader( "Accept-Language", "en-US,en;q=0.8" );
   HttpResponse httpResponse = httpClient.execute( httpGet );
   return httpResponse.getEntity();
</code>```

I'm unsure what to do to debug this.  Most posts say its the Accept header at fault.  I've set mine to accept everything, yet am still failing.

When I go to the site in Chrome I get the following headers.  Could it be the 304 return code that is causing the problem?

```<code>General
Request URL:http://sqrpt.com/feed/podcast/
Request Method:GET
Status Code:304 Not Modified
Remote Address:192.185.32.200:80
Referrer Policy:no-referrer-when-downgrade

Response Headers
view source
Connection:keep-alive
Date:Sat, 03 Jun 2017 03:46:27 GMT
ETag:"c06764644cd3ec282be2807a54a3484c"
Server:nginx/1.12.0

Request Headers
view source
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Cache-Control:max-age=0
Connection:keep-alive
Host:sqrpt.com
If-Modified-Since:Fri, 02 Jun 2017 01:36:27 GMT
If-None-Match:"c06764644cd3ec282be2807a54a3484c"
Upgrade-Insecure-Requests:1
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36
</code>```

What else can I try?

答:
It seems that it checks the User-Agent. I got it to work with the following user agent:</p>

```<code>CloseableHttpClient httpClient = HttpClients.custom().setUserAgent( "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36" ).build();
</code>```

Body:
I'm writing a podcast downloader using Java and Apache HttpClient.  It works fine for most RSS feeds, but this one is failing with a "406 Not Acceptable" error.

The link is http://sqrpt.com/feed/podcast/

The response I get back is:

HttpResponseProxy{HTTP/1.1 406 Not Acceptable [Server: nginx/1.12.0, Date: Sat, 03 Jun 2017 03:40:17 GMT, Content-Type: text/html; charset=iso-8859-1, Content-Length: 226, Connection: keep-alive] ResponseEntityProxy{[Content-Type: text/html; charset=iso-8859-1,Content-Length: 226,Chunked: false]}}

My Java code is:

   HttpClient httpClient = HttpClients.custom().setUserAgent( "Mozilla/5.0" ).build();
   HttpGet httpGet = new HttpGet( url );
   httpGet.setHeader( "Accept", "*/*" );
   httpGet.setHeader( "Accept-Encoding", "gzip, deflate, sdch" );
   httpGet.setHeader( "Accept-Language", "en-US,en;q=0.8" );
   HttpResponse httpResponse = httpClient.execute( httpGet );
   return httpResponse.getEntity();

I'm unsure what to do to debug this.  Most posts say its the Accept header at fault.  I've set mine to accept everything, yet am still failing.

When I go to the site in Chrome I get the following headers.  Could it be the 304 return code that is causing the problem?

General
Request URL:http://sqrpt.com/feed/podcast/
Request Method:GET
Status Code:304 Not Modified
Remote Address:192.185.32.200:80
Referrer Policy:no-referrer-when-downgrade

Response Headers
view source
Connection:keep-alive
Date:Sat, 03 Jun 2017 03:46:27 GMT
ETag:"c06764644cd3ec282be2807a54a3484c"
Server:nginx/1.12.0

Request Headers
view source
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Cache-Control:max-age=0
Connection:keep-alive
Host:sqrpt.com
If-Modified-Since:Fri, 02 Jun 2017 01:36:27 GMT
If-None-Match:"c06764644cd3ec282be2807a54a3484c"
Upgrade-Insecure-Requests:1
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36

What else can I try?

Body:
It seems that it checks the User-Agent. I got it to work with the following user agent:

CloseableHttpClient httpClient = HttpClients.custom().setUserAgent( "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36" ).build();


问:
One hot representation giving error of index
I am trying to understand one hot representation by the following function. I have printed each and every single line of this function.But I'm getting an error only at the last line that the index is out of bound. I'm unable to understand the reason.How can I fix this problem?  </p>

```<code>def dense_to_one_hot(labels_dense, num_classes):
    num_labels = labels_dense.shape[0]
    index_offset = np.arange(num_labels) * num_classes
    labels_one_hot = np.zeros((num_labels, num_classes))
    labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1
    return labels_one_hot

labels_dense = np.arange(475000)
print labels_dense.shape
num_classes=10
num_labels = labels_dense.shape[0]
print num_labels
index_offset = np.arange(num_labels) * num_classes
print index_offset
print len(index_offset)
print 'index offset is '+str(index_offset.shape)
labels_one_hot = np.zeros((num_labels, num_classes))
print labels_one_hot.shape
x= labels_dense.ravel()
print x
print x.shape
plus= index_offset+x
print plus
print plus.shape
labels_one_hot.flat[plus]=1
</code>```

答:
For the others, the PO was referring to a the example from Tensorflow working with MNIST data, check out the official source code.

labels_dense is a numpy array which is supposed to store elements where each is a class identifier (like 0 represent images labeled as "zero", 9 represents images labeled as "nine").

Here is how the default test data labels look like:

```<code>In [20]: labels   # same as labels_dense
Out[20]: array([7, 2, 1, ..., 4, 5, 6], dtype=uint8)
</code>```

In your own code, you generated labels_dense in the right size, but wrong way:

```<code>In [34]: labels_dense
Out[34]: array([ 0, 1, 2, ..., 474997, 474998, 474999])
</code>```

You see? I am glad your code did not work, otherwise, it might create a 0.5M*0.5 M ~ 50B cells... phew..

The rest of the code is pretty straightforward but I just want to add a bit more intermediate steps to show how labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1 works. Also, instead of using 475K records, I suggest start using 3 record to prove the idea.

```<code>In [35]: labels_dense = labels[:3]
In [36]: labels_dense
Out[36]: array([7, 2, 1], dtype=uint8)
In [37]: num_classes = 10
In [38]: num_labels = labels_dense.shape[0]
In [39]: index_offset = np.arange(num_labels) * num_classes
In [40]: index_offset
Out[40]: array([ 0, 10, 20])
In [41]: labels_one_hot = np.zeros((num_labels, num_classes))
In [42]: labels_one_hot
Out[42]:
array([[ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]])
In [43]: index_offset + labels_dense.ravel()
Out[43]: array([ 7, 12, 21])
In [44]: labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1
In [45]: labels_one_hot
Out[45]:
array([[ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.,  0.,  0.],
       [ 0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]])
</code>```

Also, at this stage, your code has nothing to do with Tensorflow at all, if you label your question with numpy or even Python in general, you will get help much faster and probably better.

Reference: flat, ravel, arange, zeros

Body:
I am trying to understand one hot representation by the following function. I have printed each and every single line of this function.But I'm getting an error only at the last line that the index is out of bound. I'm unable to understand the reason.How can I fix this problem?

def dense_to_one_hot(labels_dense, num_classes):
    num_labels = labels_dense.shape[0]
    index_offset = np.arange(num_labels) * num_classes
    labels_one_hot = np.zeros((num_labels, num_classes))
    labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1
    return labels_one_hot

labels_dense = np.arange(475000)
print labels_dense.shape
num_classes=10
num_labels = labels_dense.shape[0]
print num_labels
index_offset = np.arange(num_labels) * num_classes
print index_offset
print len(index_offset)
print 'index offset is '+str(index_offset.shape)
labels_one_hot = np.zeros((num_labels, num_classes))
print labels_one_hot.shape
x= labels_dense.ravel()
print x
print x.shape
plus= index_offset+x
print plus
print plus.shape
labels_one_hot.flat[plus]=1

Body:
For the others, the PO was referring to a the example from Tensorflow working with MNIST data, check out the official source code.

labels_dense is a numpy array which is supposed to store elements where each is a class identifier (like 0 represent images labeled as "zero", 9 represents images labeled as "nine").

Here is how the default test data labels look like:

In [20]: labels   # same as labels_dense
Out[20]: array([7, 2, 1, ..., 4, 5, 6], dtype=uint8)

In your own code, you generated labels_dense in the right size, but wrong way:

In [34]: labels_dense
Out[34]: array([ 0, 1, 2, ..., 474997, 474998, 474999])

You see? I am glad your code did not work, otherwise, it might create a 0.5M*0.5 M ~ 50B cells... phew..

The rest of the code is pretty straightforward but I just want to add a bit more intermediate steps to show how labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1 works. Also, instead of using 475K records, I suggest start using 3 record to prove the idea.

In [35]: labels_dense = labels[:3]
In [36]: labels_dense
Out[36]: array([7, 2, 1], dtype=uint8)
In [37]: num_classes = 10
In [38]: num_labels = labels_dense.shape[0]
In [39]: index_offset = np.arange(num_labels) * num_classes
In [40]: index_offset
Out[40]: array([ 0, 10, 20])
In [41]: labels_one_hot = np.zeros((num_labels, num_classes))
In [42]: labels_one_hot
Out[42]:
array([[ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]])
In [43]: index_offset + labels_dense.ravel()
Out[43]: array([ 7, 12, 21])
In [44]: labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1
In [45]: labels_one_hot
Out[45]:
array([[ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.,  0.,  0.],
       [ 0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]])

Also, at this stage, your code has nothing to do with Tensorflow at all, if you label your question with numpy or even Python in general, you will get help much faster and probably better.

Reference: flat, ravel, arange, zeros


问:
Running lein repl :headless in the background

Goal: Run lein Headless in the Background

I am trying to run a leiningen REPL headless, without devoting a terminal to it. Namely, I would like to do

```<code>$ lein repl :headless &
</code>```

But after a few seconds bash reports that it has been stopped

```<code>$ [2]+  Stopped                 lein repl :headless
</code>```

Running this in zsh and sh has the same results. Those shells print the signal which is received, SIGTTIN, meaning the process attempted to read from STDIN despite not being the terminal-controlling process.

The following works:

```<code>$ bash -c "lein repl :headless &"
$ lein repl :headless </dev/null &
</code>```

I've taken a look at repl :headless does not work without stdin but I wasn't able to resolve my problem using what was there.

Some other details:

Putting

```<code>#!/bin/bash
lein repl :headless &
</code>```

into a script test.bash and running ./test.bash also works. But changing the line to lein repl :headless and running ./test.bash & does not.

Running

```<code>$ lein repl :headless &
$ disown %1
</code>```

Also does not work; ps of the process reports that it is terminated.

I also typically run tmux with reattach-to-user-namespace, but I have tried this inside and outside of tmux, and in multiple terminal emulators (iTerm2 and Terminal). If it helps, here are my stty -a settings.

答:
lein trampoline repl :headless & will resolve this.

You can read this for an explanation.

Body:
Goal: Run lein Headless in the Background

I am trying to run a leiningen REPL headless, without devoting a terminal to it. Namely, I would like to do

$ lein repl :headless &

But after a few seconds bash reports that it has been stopped

$ [2]+  Stopped                 lein repl :headless

Running this in zsh and sh has the same results. Those shells print the signal which is received, SIGTTIN, meaning the process attempted to read from STDIN despite not being the terminal-controlling process.

The following works:

$ bash -c "lein repl :headless &"
$ lein repl :headless </dev/null &

I've taken a look at repl :headless does not work without stdin but I wasn't able to resolve my problem using what was there.

Some other details:

Putting

#!/bin/bash
lein repl :headless &

into a script test.bash and running ./test.bash also works. But changing the line to lein repl :headless and running ./test.bash & does not.

Running

$ lein repl :headless &
$ disown %1

Also does not work; ps of the process reports that it is terminated.

I also typically run tmux with reattach-to-user-namespace, but I have tried this inside and outside of tmux, and in multiple terminal emulators (iTerm2 and Terminal). If it helps, here are my stty -a settings.


问:
AWS Cognito: update JWT ID token on user's attribute change
I want to add to the token's payload a specific attribute. This attribute can be changed rarely (once per month), however I would like that the tokens would be updated immediately after this change.

WORKFLOW

In web/mobile app, user opens a profile view and changes attribute X. The current value of this attribute is also stored in ID token. So when user submit edits, the new value of X should be saved on the backend and should replace the old value in ID token. It is important, because attribute X determines whether user can or cannot do specific things in app.

What does Cognito do when payload's attribute change? It sends new version of JWT ID token in the next request?

Should I use refresh token? Or force to sign-out and sign-in user?

答:
Refresh token will be more appropriate in this usecase. Currently, refresh token flow is not exposed in the high level android SDK for user pools because it is done behind the scene by the SDK. For now, you might have to call the refresh token from low level SDK to get around this.
(I am a developer from Amazon Cognito team,  we will take this as a feature request to allow this from our high level SDKs.)</p>


问:
Can custom elements' attributes be camelCased?
I have a custom element with attributes:

```<code>class MyElement extends HTMLElement {
    ...
    static get observedAttributes() {
        return ["camelCaseAttribute"];
    }

    set camelCaseAttribute(a) {
        this._a = a;
    }
    ...
 }
</code>```

I use it in my HTML like so:

```<code><my-element camelCaseAttribute="blubb"></my-element>
</code>```

The attribute camelCaseAttribute is not set when writing it in camelCase, but writing it without upper-case-letters works. Why?

答:
In the HTML Living Standard, Section 4.13.3 Core Concepts:

4.13.3 Core concepts

Any namespace-less attribute that is relevant to the element's functioning, as determined by the element's author, may be specified on an autonomous custom element, so long as the attribute name is XML-compatible and contains no ASCII upper alphas. The exception is the is attribute, which must not be specified on an autonomous custom element (and which will have no effect if it is).

It is defined in the HTML Living Standard that a custom element's namespace-less attributes must be XML-compatible with no ASCII uppercase letters, thus your attributes cannot be camelCased.

Body:
I have a custom element with attributes:

class MyElement extends HTMLElement {
    ...
    static get observedAttributes() {
        return ["camelCaseAttribute"];
    }

    set camelCaseAttribute(a) {
        this._a = a;
    }
    ...
 }

I use it in my HTML like so:

<my-element camelCaseAttribute="blubb"></my-element>

The attribute camelCaseAttribute is not set when writing it in camelCase, but writing it without upper-case-letters works. Why?


问:
How can i parse only the numbers from the string?
I want that in Rect.rectangles under the transform property instead to have the string "matrix(0.87142591,0.49052715,-0.49052715,0.87142591,0,0)" to have 2 properties like transform and transform1 and each one will have a number for example: transform "0.12345678"
         transform1 "1.12345678"

```<code>private void Parse()
    {
        XDocument document = XDocument.Load(@"C:\Users\mysvg\Documents\my.svg");

        Rect.rectangles = document.Descendants().Where(x => x.Name.LocalName == "rect").Select(x => new Rect()
        {
            style = Rect.GetStyle((string)x.Attribute("style")),
            id = (string)x.Attribute("id"),
            width = (double)x.Attribute("width"),
            height = (double)x.Attribute("width"),
            x = (double?)x.Attribute("width"),
            y = (double?)x.Attribute("width"),
            transform = x.Attribute("transform".Substring(18, 43)) == null ? "" : (string)x.Attribute("transform".Substring(18, 43))
        }).ToList();
    }
</code>```

And the Rect class:

```<code>public class Rect
    {
        public static List<Rect> rectangles { get; set; }
        public Dictionary<string, string> style { get; set; }
        public string id { get; set; }
        public double width { get; set; }
        public double height { get; set; }
        public double? x { get; set; }
        public double? y { get; set; }
        public string transform { get; set; }

        public static Dictionary<string, string> GetStyle(string styles)
        {
            string pattern = @"(?'name'[^:]+):(?'value'.*)";
            string[] splitArray = styles.Split(new char[] { ';' });
            Dictionary<string, string> style = splitArray.Select(x => Regex.Match(x, pattern))
                .GroupBy(x => x.Groups["name"].Value, y => y.Groups["value"].Value)
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());
            return style;
        }
    }
</code>```

I'm trying to use substring but getting out of range exception.

ArgumentOutOfRangeException: Cannot exceed length of string

On the line:

```<code>transform = x.Attribute("transform".Substring(18, 43)) == null ? "" : (string)x.Attribute("transform".Substring(18, 43))
</code>```

The string is:

transform="matrix(0.40438612,-0.91458836,0.92071162,0.39024365,0,0)"

And i want to get only the first two numbers: 0.40438612,-0.91458836

Update:

I found also a way to do it using foreach:

```<code>private void Parse()
    {
        XDocument document = XDocument.Load(@"C:\Users\mysvg\Documents\my.svg");

        Rect.rectangles = document.Descendants().Where(x => x.Name.LocalName == "rect").Select(x => new Rect()
        {
            style = Rect.GetStyle((string)x.Attribute("style")),
            id = (string)x.Attribute("id"),
            width = (double)x.Attribute("width"),
            height = (double)x.Attribute("width"),
            x = (double?)x.Attribute("width"),
            y = (double?)x.Attribute("width"),
            transform = x.Attribute("transform") == null ? "" : (string)x.Attribute("transform")
        }).ToList();
        string t = null;
        foreach(Rect rect in Rect.rectangles)
        {
            if (rect.transform != null && rect.transform != "")
            {
                t = rect.transform.Substring(7, 21);
            }
        }
    }
</code>```

But i don't want to do it after the new Rect() {
I want to do the first two numbers extraction on the line:

```<code>transform = x.Attribute("transform") == null ? "" : (string)x.Attribute("transform")
</code>```

The reason is that i have in the bottom of the code a class:

```<code>public class Rect
    {
        public static List<Rect> rectangles { get; set; }
        public Dictionary<string, string> style { get; set; }
        public string id { get; set; }
        public double width { get; set; }
        public double height { get; set; }
        public double? x { get; set; }
        public double? y { get; set; }
        public string transform { get; set; }

        public static Dictionary<string, string> GetStyle(string styles)
        {
            string pattern = @"(?'name'[^:]+):(?'value'.*)";
            string[] splitArray = styles.Split(new char[] { ';' });
            Dictionary<string, string> style = splitArray.Select(x => Regex.Match(x, pattern))
                .GroupBy(x => x.Groups["name"].Value, y => y.Groups["value"].Value)
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());
            return style;
        }
    }
</code>```

And i want that the property transform to hold/contain the two numbers already.

And another small problem how can i extract the first two numbers if for example one of the numbers have -(minus) in the start for example if transform contain the string: "matrix(0.40438612,-0.91458836,0.92071162,0.39024365,0,0)"

If one of the two numbers have minus in the start or both of them have minus in the start the Substring(7, 21) will not work. I need somehow to get in any case the first two numbers. But the main issue is how to extract the numbers directly from the attribute already.

答:
Without regular expression you can get the part of the string starting right after the first parenthesis and then split it using the comma:

```<code>var transform="matrix(0.40438612,-0.91458836,0.92071162,0.39024365,0,0)";
var numbers  = transform.Substring(transform.IndexOf('(') + 1).Split(',');
Console.WriteLine(double.Parse(numbers[0]));
Console.WriteLine(double.Parse(numbers[1]));
</code>```

Please add error handling.

<== Fiddle Me ==>

Body:
I want that in Rect.rectangles under the transform property instead to have the string "matrix(0.87142591,0.49052715,-0.49052715,0.87142591,0,0)" to have 2 properties like transform and transform1 and each one will have a number for example: transform "0.12345678"
         transform1 "1.12345678"

private void Parse()
    {
        XDocument document = XDocument.Load(@"C:\Users\mysvg\Documents\my.svg");

        Rect.rectangles = document.Descendants().Where(x => x.Name.LocalName == "rect").Select(x => new Rect()
        {
            style = Rect.GetStyle((string)x.Attribute("style")),
            id = (string)x.Attribute("id"),
            width = (double)x.Attribute("width"),
            height = (double)x.Attribute("width"),
            x = (double?)x.Attribute("width"),
            y = (double?)x.Attribute("width"),
            transform = x.Attribute("transform".Substring(18, 43)) == null ? "" : (string)x.Attribute("transform".Substring(18, 43))
        }).ToList();
    }

And the Rect class:

public class Rect
    {
        public static List<Rect> rectangles { get; set; }
        public Dictionary<string, string> style { get; set; }
        public string id { get; set; }
        public double width { get; set; }
        public double height { get; set; }
        public double? x { get; set; }
        public double? y { get; set; }
        public string transform { get; set; }

        public static Dictionary<string, string> GetStyle(string styles)
        {
            string pattern = @"(?'name'[^:]+):(?'value'.*)";
            string[] splitArray = styles.Split(new char[] { ';' });
            Dictionary<string, string> style = splitArray.Select(x => Regex.Match(x, pattern))
                .GroupBy(x => x.Groups["name"].Value, y => y.Groups["value"].Value)
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());
            return style;
        }
    }

I'm trying to use substring but getting out of range exception.

ArgumentOutOfRangeException: Cannot exceed length of string

On the line:

transform = x.Attribute("transform".Substring(18, 43)) == null ? "" : (string)x.Attribute("transform".Substring(18, 43))

The string is:

transform="matrix(0.40438612,-0.91458836,0.92071162,0.39024365,0,0)"

And i want to get only the first two numbers: 0.40438612,-0.91458836

Update:

I found also a way to do it using foreach:

private void Parse()
    {
        XDocument document = XDocument.Load(@"C:\Users\mysvg\Documents\my.svg");

        Rect.rectangles = document.Descendants().Where(x => x.Name.LocalName == "rect").Select(x => new Rect()
        {
            style = Rect.GetStyle((string)x.Attribute("style")),
            id = (string)x.Attribute("id"),
            width = (double)x.Attribute("width"),
            height = (double)x.Attribute("width"),
            x = (double?)x.Attribute("width"),
            y = (double?)x.Attribute("width"),
            transform = x.Attribute("transform") == null ? "" : (string)x.Attribute("transform")
        }).ToList();
        string t = null;
        foreach(Rect rect in Rect.rectangles)
        {
            if (rect.transform != null && rect.transform != "")
            {
                t = rect.transform.Substring(7, 21);
            }
        }
    }

But i don't want to do it after the new Rect() {
I want to do the first two numbers extraction on the line:

transform = x.Attribute("transform") == null ? "" : (string)x.Attribute("transform")

The reason is that i have in the bottom of the code a class:

public class Rect
    {
        public static List<Rect> rectangles { get; set; }
        public Dictionary<string, string> style { get; set; }
        public string id { get; set; }
        public double width { get; set; }
        public double height { get; set; }
        public double? x { get; set; }
        public double? y { get; set; }
        public string transform { get; set; }

        public static Dictionary<string, string> GetStyle(string styles)
        {
            string pattern = @"(?'name'[^:]+):(?'value'.*)";
            string[] splitArray = styles.Split(new char[] { ';' });
            Dictionary<string, string> style = splitArray.Select(x => Regex.Match(x, pattern))
                .GroupBy(x => x.Groups["name"].Value, y => y.Groups["value"].Value)
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());
            return style;
        }
    }

And i want that the property transform to hold/contain the two numbers already.

And another small problem how can i extract the first two numbers if for example one of the numbers have -(minus) in the start for example if transform contain the string: "matrix(0.40438612,-0.91458836,0.92071162,0.39024365,0,0)"

If one of the two numbers have minus in the start or both of them have minus in the start the Substring(7, 21) will not work. I need somehow to get in any case the first two numbers. But the main issue is how to extract the numbers directly from the attribute already.

Body:
Without regular expression you can get the part of the string starting right after the first parenthesis and then split it using the comma:

var transform="matrix(0.40438612,-0.91458836,0.92071162,0.39024365,0,0)";
var numbers  = transform.Substring(transform.IndexOf('(') + 1).Split(',');
Console.WriteLine(double.Parse(numbers[0]));
Console.WriteLine(double.Parse(numbers[1]));

Please add error handling.

<== Fiddle Me ==>


问:
whats wrong with this code?
I am reading contents from files of a directory. I have to segregate the files according to their names and then read their contents. When I run the code simply without reading the contents, all the files are being listed of a particular file name, but when I try to read the contents, it reads contents from only few files, in fact just 10 of them. But the directory has about 1000 files of a particular name. I am posting the code here.

```<code>for (i = 0; i <= filenames.length; i++) {
    read = new FileReader("trainfiles/"+filenames[i]);
    br = new BufferedReader(read);

    if (filenames[i].matches(".*ham.*")) {
        System.out.println("ham:" + filenames[i]);
        while ((lines = br.readLine()) != null) {
            st = new StringTokenizer(lines);
            while (st.hasMoreTokens()) {
                System.out.println(st.nextToken());
            }
        }
        br.close();
    }
}
</code>```

Could anyone tell me where am i doing wrong!?

thanks

EDIT #1 I did some modifications which I have been told here, but the problem still persists, here is the code.

```<code>for(i=0;i<=filenames.length;i++){
            read = new FileReader("trainfiles/"+filenames[i]);

            br = new BufferedReader(read);

            if(filenames[i].matches(".*ham.*")){
                System.out.println("ham:"+filenames[i]);

                        while((lines = br.readLine())!= null){
                            st = new StringTokenizer(lines);
                            while(st.hasMoreTokens()){
                                System.out.println(st.nextToken());
                            }

                        }

            }
            br.close();
            read.close();

                        }
</code>```

EDIT #2 Now the code looks like this, but again...its not giving me the result I want.

```<code>for (i = 0; i < filenames.length; i++) {
               try {

                if (filenames[i].matches(".*ham.*")) {
                     read = new FileReader("trainfiles/"+filenames[i]);
                        br = new BufferedReader(read);
                    System.out.println("ham:" + filenames[i]);
                    while ((lines = br.readLine()) != null) {
                        st = new StringTokenizer(lines);
                        while (st.hasMoreTokens()) {
                            System.out.println(st.nextToken());
                        }
                    }
                }
               } finally {

                read.close();
                br.close();
               }
            }
</code>```

答:
First of all you should use i<filenames.length. Second, matches expects a regular expression, not *-globs. The expression you used is a valid regular expression for [something]ham[something] - is that what you meant?

I don't think you need to close the Filereader - I think BR's close propagates up. But that's worth checking. EDIT as was mentioned, you need to always close the file, outside the if.

Title: whats wrong with this code?

Body:
I am reading contents from files of a directory. I have to segregate the files according to their names and then read their contents. When I run the code simply without reading the contents, all the files are being listed of a particular file name, but when I try to read the contents, it reads contents from only few files, in fact just 10 of them. But the directory has about 1000 files of a particular name. I am posting the code here.

for (i = 0; i <= filenames.length; i++) {
    read = new FileReader("trainfiles/"+filenames[i]);
    br = new BufferedReader(read);

    if (filenames[i].matches(".*ham.*")) {
        System.out.println("ham:" + filenames[i]);
        while ((lines = br.readLine()) != null) {
            st = new StringTokenizer(lines);
            while (st.hasMoreTokens()) {
                System.out.println(st.nextToken());
            }
        }
        br.close();
    }
}

Could anyone tell me where am i doing wrong!?

thanks

EDIT #1 I did some modifications which I have been told here, but the problem still persists, here is the code.

for(i=0;i<=filenames.length;i++){
            read = new FileReader("trainfiles/"+filenames[i]);

            br = new BufferedReader(read);

            if(filenames[i].matches(".*ham.*")){
                System.out.println("ham:"+filenames[i]);

                        while((lines = br.readLine())!= null){
                            st = new StringTokenizer(lines);
                            while(st.hasMoreTokens()){
                                System.out.println(st.nextToken());
                            }

                        }

            }
            br.close();
            read.close();

                        }

EDIT #2 Now the code looks like this, but again...its not giving me the result I want.

for (i = 0; i < filenames.length; i++) {
               try {

                if (filenames[i].matches(".*ham.*")) {
                     read = new FileReader("trainfiles/"+filenames[i]);
                        br = new BufferedReader(read);
                    System.out.println("ham:" + filenames[i]);
                    while ((lines = br.readLine()) != null) {
                        st = new StringTokenizer(lines);
                        while (st.hasMoreTokens()) {
                            System.out.println(st.nextToken());
                        }
                    }
                }
               } finally {

                read.close();
                br.close();
               }
            }


问:
Application terminates when running in Ipad
I am seeing this message every time when I'm running my app in iPad .I'm getting issue in popup as Restore the connection to "iPad" and run "AppName" again, or if "AppName" is still running, you can attach to it by selecting Debug > Attach to Process > AppName. and in console it is showing this issue Connection to assetsd was interrupted or assetsd died

This issue was occurring each and every time while running in iPad.How to solve this?

Update: Actually I'm getting issue while presenting second view  GADInterstitial Ad is also presented,because of this Ad I'm getting this issue.If I remove this Ad code there is no issue .But in my view i need to get Ad.

答:
Not sure if this fits into your problem. But I had the problem that I had 2 significant problems that caused this:

I used RawMutablePointers, which I had to deinitialize and deallocate to release memory capacities. Otherwise the memory is crowded after some seconds (I used this for capturing camera feed). Taken memory was shown as >500mb.

I processed images. Camera feed was taken and converted to UIImage. To show this image I added those UIImages to subviews. By using the .addSubViewit started to crowd my memory even if the used memory always has been below 50mb. Before I added a new sublayer I removed everything before by this:
self.grayScaledCameraView.subviews.forEach({ $0.removeFromSuperview() })

Doing both solved my crashing like you described.


问:
Guava null tester keeps throwing error
Here is my piece of code:

```<code>public class MyTest {
    @NonNull
    private MyObject MyObjectClient;

    private Object copyOfTestObject;

    public TestMyResult methodFoo(Object testobject) {
        ...
        ...
        ...
        copyOfTestObject = clone(testObject);
    }

}
</code>```

Now, i have a unit test for this class:

```<code>public class MyTestUnitTest {

    @Rule public MockitoRule mockitoRule = MockitoJUnit.rule();

    private MyTest classUnderTest;

    @Test
    public void testNulls() {
        NullPointerTester nullPointerTester = new NullPointerTester();
        nullPointerTester.testConstructors(MyTest.class, NullPointerTester.Visibility.PACKAGE);
        nullPointerTester.testAllPublicInstanceMethods(classUnderTest);
    }
}
</code>```

When I run the unit test, I keep getting this error:
No exception thrown for parameter at index 1 from MyTest(MyObject, MyObject2) for class MyTest.

I am unclear why exactly this error is being thrown. Do I have to add the annotation @Nullable to te copyOfTestObject variable? If not, is there a way to have this unit test work?

Thanks.

答: It looks like the issue is not with methodFoo but with the constructor MyTest(MyObject, MyObject2)... the MyObject2 parameter is not @Nullable, your constructor isn't throwing an exception if null is passed in for it.

Title: Guava null tester keeps throwing error

Body:
Here is my piece of code:

public class MyTest {
    @NonNull
    private MyObject MyObjectClient;

    private Object copyOfTestObject;

    public TestMyResult methodFoo(Object testobject) {
        ...
        ...
        ...
        copyOfTestObject = clone(testObject);
    }

}

Now, i have a unit test for this class:

public class MyTestUnitTest {

    @Rule public MockitoRule mockitoRule = MockitoJUnit.rule();

    private MyTest classUnderTest;

    @Test
    public void testNulls() {
        NullPointerTester nullPointerTester = new NullPointerTester();
        nullPointerTester.testConstructors(MyTest.class, NullPointerTester.Visibility.PACKAGE);
        nullPointerTester.testAllPublicInstanceMethods(classUnderTest);
    }
}

When I run the unit test, I keep getting this error:
No exception thrown for parameter at index 1 from MyTest(MyObject, MyObject2) for class MyTest.

I am unclear why exactly this error is being thrown. Do I have to add the annotation @Nullable to te copyOfTestObject variable? If not, is there a way to have this unit test work?

Thanks.